unitype-runtime 0.2.0

Implementation registry, pluggable executors, and policy dispatch for unitype
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
//! Choosing which proof answers a call.
//!
//! A proposition may have several proofs. Which one runs is decided here, at
//! the moment of the call, from a policy the caller supplies — ask for speed
//! and you get the fast one, ask for a small footprint and you get the frugal
//! one, and the answer is the same either way. That is the arrangement this
//! whole system exists to make possible, and it is a policy decision rather
//! than an architectural one precisely because nothing above this layer had to
//! know which proof it was getting.
//!
//! # Checking both sides
//!
//! Arguments are checked against the signature before an implementation sees
//! them, and the result is checked before the caller does. The second check is
//! the one that earns its keep: an implementation that returns the wrong shape
//! has failed to prove what it claimed, and that has to be loud. It is the only
//! failure that never falls back to another proof, because trying someone else
//! would be papering over a broken proof rather than working around a broken
//! machine.
//!
//! # Refinement widens the search
//!
//! Asking for `sort` also considers proofs of anything that *refines* `sort`,
//! since a proof of a stronger claim proves the weaker one too. A caller gets
//! the benefit of a specialised implementation without having to know it exists.
//!
//! # Equivalence reorders the call
//!
//! An equivalence link says two signatures are one proposition with the
//! parameters renamed and reordered — `request(url, cb)` and
//! `request(callback, getUrl)`. Asking for either considers the proofs of both,
//! and a proof of the other one is handed the arguments in the order it takes
//! them. Nothing is converted: an equivalence only pairs parameters that hold
//! the same data, so putting them in another order is the whole of it.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};

use unitype_core::check::CheckedWorkspace;
use unitype_core::ir::{FunctionSig, Type};
use unitype_core::meta::ImplProfile;
use unitype_core::value::Value;
use unitype_core::{Ident, QualifiedName};

use crate::environment::Reach;
use crate::error::{DispatchError, ExecError};
use crate::implementation::{ImplId, Implementation};
use crate::interpret::{BoxFuture, Calls, eval_signature};
use crate::registry::{INTRINSIC_ENTRY, Registry};

/// How to choose among the proofs of a proposition.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Policy {
    /// Whatever is cheapest overall, preferring not to leave the process.
    #[default]
    Default,
    /// The best time complexity on offer.
    Fastest,
    /// The smallest memory footprint on offer.
    MinMemory,
    /// This proof and no other. If it cannot run, the call fails rather than
    /// quietly becoming a different call.
    Pinned(ImplId),
    /// Anything in this environment, if there is one; otherwise the default.
    PreferEnvironment(Ident),
}

/// What the dispatcher checks and how forgiving it is.
#[derive(Clone, Debug)]
pub struct Options {
    /// Check arguments against the signature before running anything.
    pub check_arguments: bool,
    /// Check the result against the signature before returning it.
    pub check_result: bool,
    /// On an environmental failure, try the next proof.
    ///
    /// Off by default: silently succeeding somewhere else hides the fact that
    /// an environment is broken. A proof returning the wrong answer never falls
    /// back regardless of this.
    pub fall_back: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            check_arguments: true,
            check_result: true,
            fall_back: false,
        }
    }
}

/// Why a candidate was passed over, or what happened to it.
#[derive(Clone, Debug, PartialEq)]
pub enum Outcome {
    /// It ran and answered.
    Answered,
    /// It could not be reached from here.
    Unavailable(String),
    /// The policy ruled it out.
    NotPreferred,
    /// It ran and failed.
    Failed(String),
}

/// One candidate and what became of it.
#[derive(Clone, Debug, PartialEq)]
pub struct Considered {
    /// The implementation.
    pub id: ImplId,
    /// Where it would have run.
    pub environment: Ident,
    /// What it claims to cost.
    pub cost: String,
    /// What became of it.
    pub outcome: Outcome,
}

/// What happened when a proposition was called.
#[derive(Clone, Debug)]
pub struct Invocation {
    /// What came back.
    pub value: Value,
    /// The proof that answered.
    pub implementation: ImplId,
    /// Where it ran.
    pub environment: Ident,
    /// How long it took, including reaching the environment.
    pub elapsed: Duration,
    /// Every candidate and what became of it, so a caller can see why.
    pub considered: Vec<Considered>,
}

/// Why a proof's claimed cost is over what a proposition allows, if it is. An
/// unnamed claim cannot be compared, so it is not allowed under any bound.
fn over_budget(sig: &FunctionSig, claimed: &ImplProfile) -> Option<String> {
    for (axis, allowed, claim) in [
        ("time", &sig.time, &claimed.time),
        ("space", &sig.space, &claimed.space),
    ] {
        let Some(allowed) = allowed else {
            continue;
        };
        let fits = match (claim.rank(), allowed.rank()) {
            (Some(claim), Some(allowed)) => claim <= allowed,
            _ => false,
        };
        if !fits {
            return Some(format!(
                "claims {claim} for {axis}, but the proposition allows at most {allowed}"
            ));
        }
    }
    None
}

/// A window's end or start as a duration. The checker refuses a negative one,
/// so this only has to be safe, not exact.
fn millis(n: i64) -> Duration {
    Duration::from_millis(u64::try_from(n).unwrap_or(0))
}

/// Decides which proof answers a call, and runs it.
pub struct Dispatcher {
    ws: Arc<CheckedWorkspace>,
    registry: Arc<Registry>,
    options: Options,
    /// Processes kept alive between calls, for environments that asked to be.
    workers: crate::worker::Workers,
    /// Compiled WebAssembly guests, kept so only the first call pays for one.
    ///
    /// Built on first use rather than up front. Standing up a WebAssembly
    /// engine is not free — on macOS it installs a Mach exception handler for
    /// the whole process — and a dispatcher with no sandboxed proof registered
    /// should cost nothing for a capability it never uses.
    #[cfg(feature = "wasm")]
    wasm: std::sync::OnceLock<crate::wasm::WasmHost>,
}

impl Dispatcher {
    /// A dispatcher over a workspace and what has been registered against it.
    pub fn new(ws: Arc<CheckedWorkspace>, registry: Arc<Registry>) -> Self {
        Self {
            ws,
            registry,
            options: Options::default(),
            workers: crate::worker::Workers::new(),
            #[cfg(feature = "wasm")]
            wasm: std::sync::OnceLock::new(),
        }
    }

    /// The workers this dispatcher is keeping alive.
    ///
    /// Exposed so a program can stop them at a moment of its choosing; dropping
    /// the dispatcher stops them anyway.
    pub fn workers(&self) -> &crate::worker::Workers {
        &self.workers
    }

    /// The same, with different checking.
    pub fn with_options(mut self, options: Options) -> Self {
        self.options = options;
        self
    }

    /// The workspace being dispatched against.
    pub fn workspace(&self) -> &CheckedWorkspace {
        &self.ws
    }

    /// What is registered.
    pub fn registry(&self) -> &Registry {
        &self.registry
    }

    /// Every proof that would answer this proposition, best first under the
    /// given policy.
    ///
    /// Useful on its own: it is what "why did it choose that one" looks like
    /// before anything has run.
    pub fn candidates(&self, sig: &QualifiedName, policy: &Policy) -> Vec<&Implementation> {
        self.routes(sig, policy)
            .into_iter()
            .map(|(implementation, _)| implementation)
            .collect()
    }

    /// Every proof that would answer this proposition, best first, each with
    /// the order to hand it the caller's arguments in: `order[j]` is which of
    /// them becomes its `j`th.
    fn routes(&self, sig: &QualifiedName, policy: &Policy) -> Vec<(&Implementation, Vec<usize>)> {
        let mut found: Vec<(&Implementation, Vec<usize>)> = Vec::new();
        let mut seen = HashSet::new();
        let arity = self.ws.sig(sig).map_or(0, |s| s.params.len());

        // A proof of anything that strengthens this proposition proves it too,
        // with the arguments where they were. A proof of anything equivalent to
        // it proves it once they are put in that signature's order.
        let mut frontier = vec![(sig.clone(), (0..arity).collect::<Vec<usize>>())];
        while let Some((name, order)) = frontier.pop() {
            if !seen.insert(name.clone()) {
                continue;
            }
            found.extend(
                self.registry
                    .proofs_of(&name)
                    .into_iter()
                    .map(|i| (i, order.clone())),
            );
            frontier.extend(
                self.ws
                    .refiners_of(&name)
                    .iter()
                    .map(|r| (r.clone(), order.clone())),
            );
            frontier.extend(
                self.ws
                    .equivalents_of(&name)
                    .iter()
                    .map(|e| (e.sig.clone(), e.apply(&order))),
            );
        }

        if let Policy::Pinned(id) = policy {
            found.retain(|(i, _)| &i.id == id);
            return found;
        }

        found.sort_by_key(|(i, _)| self.rank(i, policy));
        found
    }

    /// Where a proof sorts under a policy. Lower is preferred.
    fn rank(&self, implementation: &Implementation, policy: &Policy) -> (u8, u8, u8, u8, String) {
        let overhead = self
            .registry
            .environment(&implementation.environment)
            .map(|e| e.reach.overhead())
            .unwrap_or(u8::MAX);
        let (time, space, _) = implementation.cost_key();
        let id = implementation.id.to_string();

        match policy {
            // Nearest to hand first. Reaching another environment costs
            // something real — a process to start, a message to serialize —
            // and for the sizes most calls actually carry, that dominates the
            // difference between one complexity class and the next. A caller
            // who knows their input is large asks for `Fastest` and means it.
            Policy::Default => (0, overhead, time, space, id),
            Policy::Fastest => (0, time, space, overhead, id),
            Policy::MinMemory => (0, space, time, overhead, id),
            Policy::PreferEnvironment(wanted) => (
                u8::from(&implementation.environment != wanted),
                time,
                space,
                overhead,
                id,
            ),
            Policy::Pinned(_) => (0, time, space, overhead, id),
        }
    }

    /// Calls a proposition, choosing a proof by policy.
    ///
    /// For a generic proposition use [`Dispatcher::call_at`]: this is the same
    /// call with no type arguments, which is only enough when there is nothing
    /// to bind.
    pub fn call<'a>(
        &'a self,
        sig: &'a QualifiedName,
        args: Vec<Value>,
        policy: &'a Policy,
    ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
        Box::pin(async move { self.dispatch(sig, &[], args, policy).await })
    }

    /// Calls a generic proposition at particular types.
    ///
    /// `reverse<T>` says something about every `T`; `reverse<i64>` is the
    /// claim a list of integers can actually be checked against. The type
    /// arguments bind the proposition's parameters in order, and both sides of
    /// the boundary are then checked against the instantiated signature. The
    /// proof itself is not told: a proof of a generic proposition is one that
    /// did not need to know.
    pub fn call_at<'a>(
        &'a self,
        sig: &'a QualifiedName,
        type_args: &'a [Type],
        args: Vec<Value>,
        policy: &'a Policy,
    ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
        Box::pin(async move { self.dispatch(sig, type_args, args, policy).await })
    }

    async fn dispatch(
        &self,
        name: &QualifiedName,
        type_args: &[Type],
        args: Vec<Value>,
        policy: &Policy,
    ) -> Result<Invocation, DispatchError> {
        let Some(declared) = self.ws.sig(name) else {
            return Err(DispatchError::UnknownSignature(name.clone()));
        };

        if declared.params_decl.len() != type_args.len() {
            return Err(DispatchError::TypeArity {
                sig: name.clone(),
                expected: declared.params_decl.len(),
                got: type_args.len(),
            });
        }
        // A bound may mention the other parameters, as in `<A, B: Holder<A>>`,
        // so the arguments are put into it before it is asked.
        let subst = unitype_core::check::bind(&declared.params_decl, type_args);
        for (param, arg) in declared.params_decl.iter().zip(type_args) {
            for bound in &param.bounds {
                let required = Type::Ref(unitype_core::check::substitute_ref(bound, &subst));
                if !self.ws.is_subtype(arg, &required) {
                    return Err(DispatchError::BoundNotMet {
                        sig: name.clone(),
                        param: param.name.clone(),
                        arg: arg.to_string(),
                        bound: required.to_string(),
                    });
                }
            }
        }
        // Only a generic signature has anything to substitute, so only one
        // pays for the copy.
        let instantiated;
        let sig = if type_args.is_empty() {
            declared
        } else {
            instantiated = declared.instantiate(type_args);
            &instantiated
        };

        if sig.params.len() != args.len() {
            return Err(DispatchError::Arity {
                sig: name.clone(),
                expected: sig.params.len(),
                got: args.len(),
            });
        }
        if self.options.check_arguments {
            for (index, (param, arg)) in sig.params.iter().zip(&args).enumerate() {
                if let Err(errors) = self.ws.validate(arg, &param.ty) {
                    return Err(DispatchError::BadArgument {
                        sig: name.clone(),
                        index,
                        errors,
                    });
                }
            }
        }

        let candidates = self.routes(name, policy);
        if candidates.is_empty() {
            return match policy {
                Policy::Pinned(id) => Err(DispatchError::Unusable {
                    id: id.to_string(),
                    reason: format!("nothing registered under that name proves `{name}`"),
                }),
                _ => Err(DispatchError::NoImplementation(name.clone())),
            };
        }

        // A future is a promise about when, not about what, so a signature
        // returning one is satisfied by the value it eventually holds.
        let expected = sig
            .ret
            .future_of()
            .cloned()
            .unwrap_or_else(|| sig.ret.clone());
        // A future restricted to a window must deliver inside it. A proof that
        // misses the window is passed over, as one that is unavailable is, so
        // another proof that meets it can answer.
        let window = match &sig.ret {
            Type::Bounded { wait, .. } => *wait,
            _ => None,
        };

        let mut considered = Vec::with_capacity(candidates.len());
        for (implementation, order) in candidates {
            let cost = implementation.cost.to_string();
            let environment = implementation.environment.clone();

            if let Err(reason) = self.reachable(implementation) {
                considered.push(Considered {
                    id: implementation.id.clone(),
                    environment,
                    cost,
                    outcome: Outcome::Unavailable(reason),
                });
                continue;
            }

            // A proof that claims more than the proposition allows is not a
            // candidate for it, whatever it would answer.
            if let Some(reason) = over_budget(sig, &implementation.cost) {
                considered.push(Considered {
                    id: implementation.id.clone(),
                    environment,
                    cost,
                    outcome: Outcome::Unavailable(reason),
                });
                continue;
            }

            let started = Instant::now();
            // In the order the proof's own signature takes them, which is the
            // caller's order unless it proves an equivalent signature.
            let handed: Vec<Value> = order.iter().map(|&i| args[i].clone()).collect();
            // Each written against the type the call checked it at, which an
            // equivalent signature's parameter holds the same data as.
            let types: Vec<Type> = order.iter().map(|&i| sig.params[i].ty.clone()).collect();
            let call = self.invoke(implementation, handed, &types, &expected, policy);
            let outcome = match window.and_then(|w| w.max) {
                // One millisecond past the end, since the late check below
                // works in whole milliseconds and must have the final word.
                Some(max) => {
                    match tokio::time::timeout(millis(max.saturating_add(1)), call).await {
                        Ok(outcome) => outcome,
                        Err(_) => {
                            considered.push(Considered {
                                id: implementation.id.clone(),
                                environment: environment.clone(),
                                cost: cost.clone(),
                                outcome: Outcome::Failed(format!(
                                    "did not answer within {max} ms, the window's end"
                                )),
                            });
                            continue;
                        }
                    }
                }
                None => call.await,
            };
            let elapsed = started.elapsed();
            // The timeout above cannot stop a proof that blocks its thread, so
            // a late answer is refused here too, whichever way it arrived.
            if let Some(w) = window {
                // Whole milliseconds, as a window is written, so that
                // `not by 5000` and `up until 4999` admit the same answers.
                let ms = i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX);
                let early = w.min.is_some_and(|min| ms < min);
                let late = w.max.is_some_and(|max| ms > max);
                if early || late {
                    let why = if early {
                        format!(
                            "answered after {} ms, before the window opens at {} ms",
                            elapsed.as_millis(),
                            w.min.unwrap_or_default()
                        )
                    } else {
                        format!(
                            "answered after {} ms, after the window closes at {} ms",
                            elapsed.as_millis(),
                            w.max.unwrap_or_default()
                        )
                    };
                    considered.push(Considered {
                        id: implementation.id.clone(),
                        environment: environment.clone(),
                        cost: cost.clone(),
                        outcome: Outcome::Failed(why),
                    });
                    continue;
                }
            }

            match outcome {
                Ok(value) => {
                    if self.options.check_result {
                        if let Err(errors) = self.ws.validate(&value, &expected) {
                            // Never a fallback. A proof that does not prove
                            // what it claims is a fact about the proof, and
                            // asking someone else would bury it.
                            return Err(DispatchError::BadResult {
                                id: implementation.id.to_string(),
                                sig: name.clone(),
                                errors,
                            });
                        }
                    }
                    considered.push(Considered {
                        id: implementation.id.clone(),
                        environment: environment.clone(),
                        cost,
                        outcome: Outcome::Answered,
                    });
                    return Ok(Invocation {
                        value,
                        implementation: implementation.id.clone(),
                        environment,
                        elapsed,
                        considered,
                    });
                }
                Err(error) => {
                    let recoverable = self.options.fall_back && error.is_environmental();
                    considered.push(Considered {
                        id: implementation.id.clone(),
                        environment,
                        cost,
                        outcome: Outcome::Failed(error.to_string()),
                    });
                    if !recoverable {
                        return Err(DispatchError::Exec {
                            id: implementation.id.to_string(),
                            source: error,
                        });
                    }
                }
            }
        }

        Err(DispatchError::NoneAvailable {
            sig: name.clone(),
            skipped: considered
                .iter()
                .map(|c| match &c.outcome {
                    Outcome::Unavailable(why) | Outcome::Failed(why) => {
                        format!("{}: {why}", c.id)
                    }
                    other => format!("{}: {other:?}", c.id),
                })
                .collect(),
        })
    }

    /// Whether this process can get to where an implementation lives.
    fn reachable(&self, implementation: &Implementation) -> Result<(), String> {
        let Some(environment) = self.registry.environment(&implementation.environment) else {
            return Err(format!(
                "environment `{}` is not registered",
                implementation.environment
            ));
        };
        match &environment.reach {
            Reach::Here => {
                if implementation.entry == INTRINSIC_ENTRY
                    || self.registry.native(&implementation.entry).is_some()
                {
                    Ok(())
                } else {
                    Err(format!(
                        "nothing is registered in this process under `{}`",
                        implementation.entry
                    ))
                }
            }
            // Whether the program is actually there is discovered by trying to
            // start it, which gives a precise reason rather than a guess. The
            // same goes for a module that will not load.
            Reach::Subprocess { .. } => Ok(()),
            #[cfg(feature = "wasm")]
            Reach::Wasm { .. } => Ok(()),
            other => Err(format!(
                "reaching a `{}` environment is not built into this binary",
                other.kind()
            )),
        }
    }

    /// Runs one implementation.
    ///
    /// `params` is the type each argument was checked at, in the order the
    /// proof takes them, which is what anything reached over a wire is sent
    /// them written against.
    async fn invoke(
        &self,
        implementation: &Implementation,
        args: Vec<Value>,
        params: &[Type],
        expected: &Type,
        policy: &Policy,
    ) -> Result<Value, ExecError> {
        let Some(environment) = self.registry.environment(&implementation.environment) else {
            return Err(ExecError::Unreachable {
                environment: implementation.environment.to_string(),
                detail: "not registered".into(),
            });
        };

        match &environment.reach {
            Reach::Here => {
                // A body proves its own signature, and calls inside it come
                // back through here, so a nested call is chosen under the same
                // policy.
                if implementation.entry == INTRINSIC_ENTRY {
                    let calls = Through {
                        dispatcher: self,
                        policy,
                    };
                    return eval_signature(&self.ws, &implementation.proves, args, &calls).await;
                }
                let Some(native) = self.registry.native(&implementation.entry) else {
                    return Err(ExecError::NotRegistered(implementation.entry.clone()));
                };
                native(args).await
            }
            // An environment that asked to stay alive is answered by whatever
            // worker is already running for it, or by one started now.
            Reach::Subprocess {
                persistent: true, ..
            } => {
                self.workers
                    .invoke(
                        &self.ws,
                        environment,
                        implementation,
                        args,
                        params,
                        expected,
                    )
                    .await
            }
            Reach::Subprocess { .. } => {
                crate::subprocess::invoke(
                    &self.ws,
                    environment,
                    implementation,
                    args,
                    params,
                    expected,
                )
                .await
            }
            #[cfg(feature = "wasm")]
            Reach::Wasm { .. } => {
                self.wasm
                    .get_or_init(crate::wasm::WasmHost::new)
                    .invoke(
                        &self.ws,
                        environment,
                        implementation,
                        args,
                        params,
                        expected,
                    )
                    .await
            }
            other => Err(ExecError::Unreachable {
                environment: environment.id.to_string(),
                detail: format!(
                    "reaching a `{}` environment is not built into this binary",
                    other.kind()
                ),
            }),
        }
    }
}

/// The dispatcher, seen from inside a body, with a policy carried along.
struct Through<'a> {
    dispatcher: &'a Dispatcher,
    policy: &'a Policy,
}

impl Calls for Through<'_> {
    fn call<'a>(
        &'a self,
        sig: &'a QualifiedName,
        args: Vec<Value>,
    ) -> BoxFuture<'a, Result<Value, ExecError>> {
        Box::pin(async move {
            // A nested call is pinned only if the caller pinned *this* one, and
            // that pin was about this signature, not about anything it calls.
            let policy = match self.policy {
                Policy::Pinned(_) => &Policy::Default,
                other => other,
            };
            self.dispatcher
                .call(sig, args, policy)
                .await
                .map(|i| i.value)
                .map_err(|e| ExecError::Failed {
                    id: sig.to_string(),
                    message: e.to_string(),
                })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use unitype_core::check::check_workspace;
    use unitype_core::{BigO, ImplProfile, Workspace};

    use crate::environment::Environment;
    use crate::implementation::Implementation;

    fn q(s: &str) -> QualifiedName {
        s.parse().unwrap()
    }

    fn here() -> Ident {
        Ident::new("here").unwrap()
    }

    const SORT_WS: &str = r#"{"universes":[{"name":"demo","functions":[
        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
        {"name":"mergesort","refines":"demo::sort",
         "params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#;

    /// Sorts, slowly but frugally.
    fn bubble(mut items: Vec<i64>) -> Vec<i64> {
        for i in 0..items.len() {
            for j in 0..items.len().saturating_sub(i + 1) {
                if items[j] > items[j + 1] {
                    items.swap(j, j + 1);
                }
            }
        }
        items
    }

    fn ints(value: &Value) -> Vec<i64> {
        let Value::List(items) = value else {
            return Vec::new();
        };
        items.iter().filter_map(Value::as_int).collect()
    }

    /// Two proofs of one proposition, with different costs, both compiled in.
    fn sorting_dispatcher() -> Dispatcher {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();

        registry.register_native_sync("merge_sort", |args| {
            let mut items = ints(args.first().unwrap_or(&Value::Null));
            items.sort_unstable();
            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
        });
        registry.register_native_sync("bubble_sort", |args| {
            let items = bubble(ints(args.first().unwrap_or(&Value::Null)));
            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
        });

        registry
            .register(Implementation::new(
                "sort.merge",
                q("demo::sort"),
                here(),
                "merge_sort",
                ImplProfile::new(BigO::ONLogN, BigO::ON),
            ))
            .unwrap();
        registry
            .register(Implementation::new(
                "sort.bubble",
                q("demo::sort"),
                here(),
                "bubble_sort",
                ImplProfile::new(BigO::ON2, BigO::O1),
            ))
            .unwrap();

        Dispatcher::new(ws, Arc::new(registry))
    }

    async fn sort_with(policy: Policy) -> Invocation {
        sorting_dispatcher()
            .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &policy)
            .await
            .expect("answers")
    }

    fn list(items: &[i64]) -> Value {
        Value::List(items.iter().copied().map(Value::Int).collect())
    }

    /// One proposition stated twice, with the arguments the other way round,
    /// and proved only once.
    fn request_dispatcher() -> Dispatcher {
        let ws = Arc::new(
            check_workspace(
                Workspace::from_json(
                    r#"{"universes":[
                        {"name":"node","functions":[{"name":"fetch","ret":"str","params":[
                            {"name":"url","ty":"str"},{"name":"retries","ty":"i64"}]}]},
                        {"name":"browser","functions":[{"name":"get","ret":"str","params":[
                            {"name":"attempts","ty":"i64"},{"name":"getUrl","ty":"str"}]}]}],
                      "links":[{"name":"fetch_is_get","from":"node::fetch","to":"browser::get",
                                "kind":{"k":"equivalent"}}]}"#,
                )
                .expect("reads"),
            )
            .expect("checks"),
        );
        let mut registry = Registry::new();
        // Written against `node::fetch`, so it reads the URL first.
        registry.register_native_sync("node_fetch", |args| {
            let url = args.first().and_then(Value::as_str).unwrap_or("?");
            let retries = args.get(1).and_then(Value::as_int).unwrap_or(-1);
            Ok(Value::Str(format!("{url} x{retries}")))
        });
        registry
            .register(Implementation::new(
                "fetch.node",
                q("node::fetch"),
                here(),
                "node_fetch",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();
        Dispatcher::new(ws, Arc::new(registry))
    }

    #[tokio::test]
    async fn a_proof_of_an_equivalent_proposition_gets_the_arguments_its_own_way_round() {
        let dispatcher = request_dispatcher();

        let answered = dispatcher
            .call(
                &q("browser::get"),
                vec![Value::Int(3), Value::Str("https://x".into())],
                &Policy::Default,
            )
            .await
            .expect("the node proof answers the browser's call");
        assert_eq!(answered.implementation.as_str(), "fetch.node");
        assert_eq!(
            answered.value,
            Value::Str("https://x x3".into()),
            "the URL went where the proof reads it"
        );

        let direct = dispatcher
            .call(
                &q("node::fetch"),
                vec![Value::Str("https://x".into()), Value::Int(3)],
                &Policy::Default,
            )
            .await
            .expect("answers its own proposition");
        assert_eq!(direct.value, answered.value, "and the same call either way");
    }

    #[tokio::test]
    async fn pinning_a_proof_of_an_equivalent_proposition_still_reorders() {
        let answered = request_dispatcher()
            .call(
                &q("browser::get"),
                vec![Value::Int(1), Value::Str("https://y".into())],
                &Policy::Pinned(ImplId::new("fetch.node")),
            )
            .await
            .expect("answers");
        assert_eq!(answered.value, Value::Str("https://y x1".into()));
    }

    #[tokio::test]
    async fn a_generic_proposition_is_answered_by_a_proof_of_its_equivalent() {
        // The same claim declared with its generic parameters and its
        // parameters the other way round, and proved only on one side.
        let ws = Arc::new(
            check_workspace(
                Workspace::from_json(
                    r#"{"universes":[
                        {"name":"py","functions":[{"name":"konst",
                            "params_decl":[{"name":"A"},{"name":"B"}],
                            "params":[{"name":"x","ty":{"k":"param","name":"A"}},
                                      {"name":"y","ty":{"k":"param","name":"B"}}],
                            "ret":{"k":"param","name":"A"}}]},
                        {"name":"js","functions":[{"name":"always",
                            "params_decl":[{"name":"Y"},{"name":"X"}],
                            "params":[{"name":"ignored","ty":{"k":"param","name":"Y"}},
                                      {"name":"kept","ty":{"k":"param","name":"X"}}],
                            "ret":{"k":"param","name":"X"}}]}],
                      "links":[{"name":"konst_is_always","from":"py::konst","to":"js::always",
                                "kind":{"k":"equivalent"}}]}"#,
                )
                .expect("reads"),
            )
            .expect("checks"),
        );
        let mut registry = Registry::new();
        // Written against `py::konst`: keeps the first thing it is given.
        registry.register_native_sync("py_konst", |args| Ok(args[0].clone()));
        registry
            .register(Implementation::new(
                "konst.py",
                q("py::konst"),
                here(),
                "py_konst",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();
        let dispatcher = Dispatcher::new(ws, Arc::new(registry));

        // `always<str, i64>("dropped", 7)` keeps the integer.
        let answered = dispatcher
            .call_at(
                &q("js::always"),
                &[Type::String, Type::I64],
                vec![Value::Str("dropped".into()), Value::Int(7)],
                &Policy::Default,
            )
            .await
            .expect("the proof of konst answers, checked against always<str, i64>");
        assert_eq!(answered.implementation.as_str(), "konst.py");
        assert_eq!(answered.value, Value::Int(7));
    }

    #[tokio::test]
    async fn asking_for_speed_and_asking_for_memory_choose_differently() {
        let fast = sort_with(Policy::Fastest).await;
        let frugal = sort_with(Policy::MinMemory).await;

        assert_eq!(fast.implementation.as_str(), "sort.merge");
        assert_eq!(frugal.implementation.as_str(), "sort.bubble");
    }

    #[tokio::test]
    async fn and_both_give_the_same_answer() {
        let fast = sort_with(Policy::Fastest).await;
        let frugal = sort_with(Policy::MinMemory).await;
        assert_eq!(fast.value, list(&[1, 2, 3]));
        assert_eq!(
            fast.value, frugal.value,
            "which proof ran should not change what is true"
        );
    }

    #[tokio::test]
    async fn a_caller_can_see_what_was_considered_and_why() {
        let chosen = sort_with(Policy::Fastest).await;
        assert_eq!(chosen.considered.len(), 1, "the first one worked");
        assert_eq!(chosen.considered[0].outcome, Outcome::Answered);
        assert_eq!(chosen.environment, here());

        let ranked: Vec<String> = sorting_dispatcher()
            .candidates(&q("demo::sort"), &Policy::MinMemory)
            .iter()
            .map(|i| i.id.to_string())
            .collect();
        assert_eq!(ranked, ["sort.bubble", "sort.merge"]);
    }

    #[tokio::test]
    async fn the_default_stays_in_the_process_where_it_can() {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();
        registry.register_native_sync("bubble_sort", |args| {
            Ok(Value::List(
                bubble(ints(&args[0])).into_iter().map(Value::Int).collect(),
            ))
        });
        registry
            .add_environment(Environment::subprocess("py", "python", "python3", &[]))
            .unwrap();
        // The faster proof is elsewhere; the slower one is right here.
        registry
            .register(Implementation::new(
                "sort.py_merge",
                q("demo::sort"),
                Ident::new("py").unwrap(),
                "merge_sort",
                ImplProfile::new(BigO::ONLogN, BigO::ON),
            ))
            .unwrap();
        registry
            .register(Implementation::new(
                "sort.here_bubble",
                q("demo::sort"),
                here(),
                "bubble_sort",
                ImplProfile::new(BigO::ON2, BigO::O1),
            ))
            .unwrap();

        let dispatcher = Dispatcher::new(ws, Arc::new(registry));
        let ranked: Vec<String> = dispatcher
            .candidates(&q("demo::sort"), &Policy::Default)
            .iter()
            .map(|i| i.id.to_string())
            .collect();
        assert_eq!(
            ranked[0], "sort.here_bubble",
            "starting a process costs more than the difference in complexity, \
             for the sizes most calls carry"
        );

        let ranked: Vec<String> = dispatcher
            .candidates(&q("demo::sort"), &Policy::Fastest)
            .iter()
            .map(|i| i.id.to_string())
            .collect();
        assert_eq!(
            ranked[0], "sort.py_merge",
            "asked for speed, the better algorithm wins wherever it lives"
        );
    }

    #[tokio::test]
    async fn a_pinned_proof_is_the_one_that_runs() {
        let pinned = sorting_dispatcher()
            .call(
                &q("demo::sort"),
                vec![list(&[2, 1])],
                &Policy::Pinned(ImplId::new("sort.bubble")),
            )
            .await
            .expect("answers");
        assert_eq!(pinned.implementation.as_str(), "sort.bubble");
    }

    #[tokio::test]
    async fn pinning_something_that_proves_nothing_fails_rather_than_substituting() {
        let err = sorting_dispatcher()
            .call(
                &q("demo::sort"),
                vec![list(&[1])],
                &Policy::Pinned(ImplId::new("sort.nonexistent")),
            )
            .await
            .unwrap_err();
        assert!(
            matches!(err, DispatchError::Unusable { .. }),
            "asking for one thing and getting another would be worse: {err}"
        );
    }

    #[tokio::test]
    async fn a_proposition_nobody_proves_says_so() {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
        assert!(matches!(
            dispatcher
                .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
                .await,
            Err(DispatchError::NoImplementation(_))
        ));
    }

    #[tokio::test]
    async fn arguments_are_checked_before_anything_runs() {
        let err = sorting_dispatcher()
            .call(
                &q("demo::sort"),
                vec![Value::Str("not a list".into())],
                &Policy::Default,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(err, DispatchError::BadArgument { index: 0, .. }),
            "{err}"
        );
    }

    #[tokio::test]
    async fn the_wrong_number_of_arguments_is_caught() {
        let err = sorting_dispatcher()
            .call(&q("demo::sort"), vec![], &Policy::Default)
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            DispatchError::Arity {
                expected: 1,
                got: 0,
                ..
            }
        ));
    }

    /// A proposition that allows at most n log n time and constant space.
    const BUDGET_WS: &str = r#"{"universes":[{"name":"demo","functions":[
        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
         "time":"o_n_log_n","space":"o1"}]}]}"#;

    fn budget_dispatcher(registry: Registry) -> Dispatcher {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(BUDGET_WS).expect("reads")).expect("checks"),
        );
        Dispatcher::new(ws, Arc::new(registry))
    }

    fn sorting_proof(registry: &mut Registry, id: &str, profile: ImplProfile) {
        registry.register_native_sync(id, |args| Ok(args[0].clone()));
        registry
            .register(Implementation::new(
                format!("sort.{id}").as_str(),
                q("demo::sort"),
                here(),
                id,
                profile,
            ))
            .unwrap();
    }

    #[tokio::test]
    async fn a_proof_that_claims_more_than_the_proposition_allows_is_not_asked() {
        let mut registry = Registry::new();
        sorting_proof(
            &mut registry,
            "bubble",
            ImplProfile::new(BigO::ON2, BigO::O1),
        );
        let err = budget_dispatcher(registry)
            .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
            .await
            .unwrap_err();
        let DispatchError::NoneAvailable { skipped, .. } = err else {
            panic!("expected the claim to be ruled out");
        };
        assert!(
            skipped
                .iter()
                .any(|s| s.contains("allows at most O(n log n)")),
            "{skipped:?}"
        );
    }

    #[tokio::test]
    async fn a_proof_within_the_budget_answers_and_an_unnamed_claim_does_not() {
        let mut registry = Registry::new();
        sorting_proof(
            &mut registry,
            "merge",
            ImplProfile::new(BigO::ONLogN, BigO::O1),
        );
        let done = budget_dispatcher(registry)
            .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
            .await
            .expect("the claim fits the budget");
        assert_eq!(done.implementation.to_string(), "sort.merge");

        let mut registry = Registry::new();
        sorting_proof(
            &mut registry,
            "vague",
            ImplProfile::new(BigO::Custom("usually fast".into()), BigO::O1),
        );
        assert!(
            budget_dispatcher(registry)
                .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
                .await
                .is_err(),
            "a claim with no rank cannot be shown to fit a bound"
        );
    }

    /// A future that must deliver its value between 20 and 200 milliseconds
    /// after the call.
    const WINDOW_WS: &str = r#"{"universes":[{"name":"demo","functions":[
        {"name":"fetch","params":[{"name":"url","ty":"str"}],
         "ret":{"k":"bounded","of":{"k":"future","of":"str"},"wait":{"min":20,"max":200}}}]}]}"#;

    fn window_dispatcher(registry: Registry) -> Dispatcher {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(WINDOW_WS).expect("reads")).expect("checks"),
        );
        Dispatcher::new(ws, Arc::new(registry))
    }

    #[tokio::test]
    async fn a_proof_that_delivers_inside_its_window_answers() {
        let mut registry = Registry::new();
        registry.register_native_sync("steady", |_| {
            std::thread::sleep(Duration::from_millis(60));
            Ok(Value::Str("page".into()))
        });
        registry
            .register(Implementation::new(
                "fetch.steady",
                q("demo::fetch"),
                here(),
                "steady",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();

        let done = window_dispatcher(registry)
            .call(
                &q("demo::fetch"),
                vec![Value::Str("https://example.com".into())],
                &Policy::Default,
            )
            .await
            .expect("it delivers inside the window");
        assert!(matches!(done.value, Value::Str(ref s) if s == "page"));
    }

    #[tokio::test]
    async fn a_proof_that_misses_the_window_is_passed_over_for_one_that_meets_it() {
        let mut registry = Registry::new();
        registry.register_native_sync("late", |_| {
            std::thread::sleep(Duration::from_millis(300));
            Ok(Value::Str("late".into()))
        });
        registry.register_native_sync("prompt", |_| {
            std::thread::sleep(Duration::from_millis(50));
            Ok(Value::Str("prompt".into()))
        });
        registry
            .register(Implementation::new(
                "fetch.late",
                q("demo::fetch"),
                here(),
                "late",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();
        registry
            .register(Implementation::new(
                "fetch.prompt",
                q("demo::fetch"),
                here(),
                "prompt",
                ImplProfile::new(BigO::ON, BigO::ON),
            ))
            .unwrap();

        // The late proof is the cheaper one, so it is asked first.
        let done = window_dispatcher(registry)
            .call(
                &q("demo::fetch"),
                vec![Value::Str("https://example.com".into())],
                &Policy::Fastest,
            )
            .await
            .expect("the prompt one meets the window");
        assert_eq!(done.implementation.to_string(), "fetch.prompt");
        assert!(
            done.considered.iter().any(|c| matches!(
                &c.outcome,
                Outcome::Failed(why) if why.contains("after the window closes")
            )),
            "the late answer is recorded, not hidden"
        );
    }

    #[tokio::test]
    async fn a_window_nothing_meets_says_which_end_it_missed() {
        let mut registry = Registry::new();
        registry.register_native_sync("instant", |_| Ok(Value::Str("too soon".into())));
        registry
            .register(Implementation::new(
                "fetch.instant",
                q("demo::fetch"),
                here(),
                "instant",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();

        let err = window_dispatcher(registry)
            .call(
                &q("demo::fetch"),
                vec![Value::Str("https://example.com".into())],
                &Policy::Default,
            )
            .await
            .unwrap_err();
        let DispatchError::NoneAvailable { skipped, .. } = err else {
            panic!("expected no proof to meet the window, got {err}");
        };
        assert!(
            skipped
                .iter()
                .any(|s| s.contains("before the window opens")),
            "{skipped:?}"
        );
    }

    #[tokio::test]
    async fn a_proof_that_returns_the_wrong_thing_is_caught_and_never_excused() {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();
        registry.register_native_sync("liar", |_| Ok(Value::Str("not a list at all".into())));
        registry.register_native_sync("honest", |args| Ok(args[0].clone()));
        registry
            .register(Implementation::new(
                "sort.liar",
                q("demo::sort"),
                here(),
                "liar",
                ImplProfile::new(BigO::O1, BigO::O1),
            ))
            .unwrap();
        registry
            .register(Implementation::new(
                "sort.honest",
                q("demo::sort"),
                here(),
                "honest",
                ImplProfile::new(BigO::ON, BigO::ON),
            ))
            .unwrap();

        let dispatcher = Dispatcher::new(ws, Arc::new(registry)).with_options(Options {
            fall_back: true,
            ..Options::default()
        });

        let err = dispatcher
            .call(&q("demo::sort"), vec![list(&[1])], &Policy::Fastest)
            .await
            .unwrap_err();

        assert!(
            matches!(err, DispatchError::BadResult { .. }),
            "even with fallback on, a broken proof must not be quietly replaced: {err}"
        );
    }

    #[tokio::test]
    async fn a_proof_of_a_stronger_claim_answers_the_weaker_one() {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();
        registry.register_native_sync("merge_sort", |args| {
            let mut items = ints(&args[0]);
            items.sort_unstable();
            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
        });
        // Registered against `mergesort`, which refines `sort`. Nobody has
        // registered anything against `sort` itself.
        registry
            .register(Implementation::new(
                "mergesort.rust",
                q("demo::mergesort"),
                here(),
                "merge_sort",
                ImplProfile::new(BigO::ONLogN, BigO::ON),
            ))
            .unwrap();

        let answer = Dispatcher::new(ws, Arc::new(registry))
            .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &Policy::Default)
            .await
            .expect("a proof of the stronger claim proves this one");

        assert_eq!(answer.implementation.as_str(), "mergesort.rust");
        assert_eq!(answer.value, list(&[1, 2, 3]));
    }

    #[tokio::test]
    async fn an_environment_that_cannot_be_reached_is_reported_with_the_reason() {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();
        registry
            .add_environment(Environment::subprocess(
                "missing",
                "python",
                "unitype_no_such_interpreter",
                &[],
            ))
            .unwrap();
        registry
            .register(Implementation::new(
                "sort.elsewhere",
                q("demo::sort"),
                Ident::new("missing").unwrap(),
                "bubble_sort",
                ImplProfile::new(BigO::ON2, BigO::O1),
            ))
            .unwrap();

        let err = Dispatcher::new(ws, Arc::new(registry))
            .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
            .await
            .unwrap_err();

        let message = err.to_string();
        assert!(message.contains("sort.elsewhere"), "{message}");
        assert!(
            message.contains("could not start"),
            "the reason should be the actual one: {message}"
        );
    }

    #[tokio::test]
    async fn a_body_that_calls_out_is_answered_by_the_dispatcher() {
        let ws = Arc::new(
            check_workspace(
                Workspace::from_json(
                    r#"{"universes":[{"name":"demo","functions":[
                        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
                        {"name":"sorted_twice","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
                         "body":{"k":"call","sig":"demo::sort","args":[
                            {"k":"call","sig":"demo::sort","args":[{"k":"var","name":"xs"}]}]}}]}]}"#,
                )
                .expect("reads"),
            )
            .expect("checks"),
        );

        let mut registry = Registry::new();
        registry.register_bodies(&ws).unwrap();
        registry.register_native_sync("merge_sort", |args| {
            let mut items = ints(&args[0]);
            items.sort_unstable();
            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
        });
        registry
            .register(Implementation::new(
                "sort.merge",
                q("demo::sort"),
                here(),
                "merge_sort",
                ImplProfile::new(BigO::ONLogN, BigO::ON),
            ))
            .unwrap();

        let answer = Dispatcher::new(ws, Arc::new(registry))
            .call(
                &q("demo::sorted_twice"),
                vec![list(&[3, 1, 2])],
                &Policy::Default,
            )
            .await
            .expect("answers");

        assert_eq!(answer.value, list(&[1, 2, 3]));
        assert!(
            answer.implementation.as_str().ends_with("#body"),
            "the body proved it, and the dispatcher answered what the body asked"
        );
    }

    const GENERIC_WS: &str = r#"{"universes":[{"name":"demo","functions":[
        {"name":"reverse","params_decl":[{"name":"T"}],
         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
         "ret":{"k":"list","of":{"k":"param","name":"T"}}}]}]}"#;

    /// One proof of a generic proposition, which never looks at an element.
    fn reversing_dispatcher() -> Dispatcher {
        let ws = Arc::new(
            check_workspace(Workspace::from_json(GENERIC_WS).expect("reads")).expect("checks"),
        );
        let mut registry = Registry::new();
        registry.register_native_sync("reverse", |mut args| {
            let Value::List(items) = args.remove(0) else {
                return Err(ExecError::Untyped("expected a list".into()));
            };
            Ok(Value::List(items.into_iter().rev().collect()))
        });
        registry
            .register(Implementation::new(
                "reverse.here",
                q("demo::reverse"),
                here(),
                "reverse",
                ImplProfile::new(BigO::ON, BigO::ON),
            ))
            .unwrap();
        Dispatcher::new(ws, Arc::new(registry))
    }

    #[tokio::test]
    async fn a_generic_proposition_is_called_at_a_type() {
        let dispatcher = reversing_dispatcher();
        let words = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())]);

        let at_strings = dispatcher
            .call_at(
                &q("demo::reverse"),
                &[Type::String],
                vec![words],
                &Policy::Default,
            )
            .await
            .expect("answers");
        assert_eq!(
            at_strings.value,
            Value::List(vec![Value::Str("b".into()), Value::Str("a".into())])
        );

        let at_ints = dispatcher
            .call_at(
                &q("demo::reverse"),
                &[Type::I64],
                vec![list(&[1, 2])],
                &Policy::Default,
            )
            .await
            .expect("answers");
        assert_eq!(at_ints.value, list(&[2, 1]));
    }

    #[tokio::test]
    async fn a_generic_proposition_called_without_its_type_says_what_is_missing() {
        // A list of integers is not a `[T]`; it is a `[i64]`. The call has to
        // say so before either side of the boundary can be checked.
        let err = reversing_dispatcher()
            .call(&q("demo::reverse"), vec![list(&[1, 2])], &Policy::Default)
            .await
            .unwrap_err();
        assert!(
            matches!(
                err,
                DispatchError::TypeArity {
                    expected: 1,
                    got: 0,
                    ..
                }
            ),
            "{err}"
        );
    }

    #[tokio::test]
    async fn a_generic_proposition_is_not_asked_at_a_type_its_bound_rules_out() {
        let ws = Arc::new(
            check_workspace(
                Workspace::from_json(
                    r#"{"universes":[{"name":"demo",
                        "types":[{"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
                                 {"k":"struct","name":"Person","implements":["Named"],
                                  "fields":[{"name":"name","ty":"str"}]}],
                        "functions":[{"name":"first_named",
                            "params_decl":[{"name":"T","bounds":["Named"]}],
                            "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
                            "ret":{"k":"optional","of":{"k":"param","name":"T"}}}]}]}"#,
                )
                .expect("reads"),
            )
            .expect("checks"),
        );
        let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
        let person = Type::Ref(unitype_core::ir::TypeRef::qualified(
            Ident::new("demo").unwrap(),
            Ident::new("Person").unwrap(),
        ));

        let err = dispatcher
            .call_at(
                &q("demo::first_named"),
                &[Type::I64],
                vec![list(&[1])],
                &Policy::Default,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(&err, DispatchError::BoundNotMet { param, .. } if param.as_str() == "T"),
            "an integer has no name: {err}"
        );

        // At a type that meets the bound, the call gets as far as finding no
        // proof, which is the next thing that can go wrong.
        let err = dispatcher
            .call_at(
                &q("demo::first_named"),
                &[person],
                vec![Value::List(vec![])],
                &Policy::Default,
            )
            .await
            .unwrap_err();
        assert!(matches!(err, DispatchError::NoImplementation(_)), "{err}");
    }

    #[tokio::test]
    async fn the_boundary_is_checked_at_the_type_the_call_named() {
        // Calling at `str` with integers is a mistake in the call, and it is
        // caught before any proof runs.
        let err = reversing_dispatcher()
            .call_at(
                &q("demo::reverse"),
                &[Type::String],
                vec![list(&[1, 2])],
                &Policy::Default,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(err, DispatchError::BadArgument { index: 0, .. }),
            "{err}"
        );
    }
}