1use std::collections::HashSet;
37use std::sync::Arc;
38use std::time::{Duration, Instant};
39
40use unitype_core::check::CheckedWorkspace;
41use unitype_core::ir::{FunctionSig, Type};
42use unitype_core::meta::ImplProfile;
43use unitype_core::value::Value;
44use unitype_core::{Ident, QualifiedName};
45
46use crate::environment::Reach;
47use crate::error::{DispatchError, ExecError};
48use crate::implementation::{ImplId, Implementation};
49use crate::interpret::{BoxFuture, Calls, eval_signature};
50use crate::registry::{INTRINSIC_ENTRY, Registry};
51
52#[derive(Clone, Debug, Default, PartialEq)]
54pub enum Policy {
55 #[default]
57 Default,
58 Fastest,
60 MinMemory,
62 Pinned(ImplId),
65 PreferEnvironment(Ident),
67}
68
69#[derive(Clone, Debug)]
71pub struct Options {
72 pub check_arguments: bool,
74 pub check_result: bool,
76 pub fall_back: bool,
82}
83
84impl Default for Options {
85 fn default() -> Self {
86 Self {
87 check_arguments: true,
88 check_result: true,
89 fall_back: false,
90 }
91 }
92}
93
94#[derive(Clone, Debug, PartialEq)]
96pub enum Outcome {
97 Answered,
99 Unavailable(String),
101 NotPreferred,
103 Failed(String),
105}
106
107#[derive(Clone, Debug, PartialEq)]
109pub struct Considered {
110 pub id: ImplId,
112 pub environment: Ident,
114 pub cost: String,
116 pub outcome: Outcome,
118}
119
120#[derive(Clone, Debug)]
122pub struct Invocation {
123 pub value: Value,
125 pub implementation: ImplId,
127 pub environment: Ident,
129 pub elapsed: Duration,
131 pub considered: Vec<Considered>,
133}
134
135fn over_budget(sig: &FunctionSig, claimed: &ImplProfile) -> Option<String> {
138 for (axis, allowed, claim) in [
139 ("time", &sig.time, &claimed.time),
140 ("space", &sig.space, &claimed.space),
141 ] {
142 let Some(allowed) = allowed else {
143 continue;
144 };
145 let fits = match (claim.rank(), allowed.rank()) {
146 (Some(claim), Some(allowed)) => claim <= allowed,
147 _ => false,
148 };
149 if !fits {
150 return Some(format!(
151 "claims {claim} for {axis}, but the proposition allows at most {allowed}"
152 ));
153 }
154 }
155 None
156}
157
158fn millis(n: i64) -> Duration {
161 Duration::from_millis(u64::try_from(n).unwrap_or(0))
162}
163
164pub struct Dispatcher {
166 ws: Arc<CheckedWorkspace>,
167 registry: Arc<Registry>,
168 options: Options,
169 workers: crate::worker::Workers,
171 #[cfg(feature = "wasm")]
178 wasm: std::sync::OnceLock<crate::wasm::WasmHost>,
179}
180
181impl Dispatcher {
182 pub fn new(ws: Arc<CheckedWorkspace>, registry: Arc<Registry>) -> Self {
184 Self {
185 ws,
186 registry,
187 options: Options::default(),
188 workers: crate::worker::Workers::new(),
189 #[cfg(feature = "wasm")]
190 wasm: std::sync::OnceLock::new(),
191 }
192 }
193
194 pub fn workers(&self) -> &crate::worker::Workers {
199 &self.workers
200 }
201
202 pub fn with_options(mut self, options: Options) -> Self {
204 self.options = options;
205 self
206 }
207
208 pub fn workspace(&self) -> &CheckedWorkspace {
210 &self.ws
211 }
212
213 pub fn registry(&self) -> &Registry {
215 &self.registry
216 }
217
218 pub fn candidates(&self, sig: &QualifiedName, policy: &Policy) -> Vec<&Implementation> {
224 self.routes(sig, policy)
225 .into_iter()
226 .map(|(implementation, _)| implementation)
227 .collect()
228 }
229
230 fn routes(&self, sig: &QualifiedName, policy: &Policy) -> Vec<(&Implementation, Vec<usize>)> {
234 let mut found: Vec<(&Implementation, Vec<usize>)> = Vec::new();
235 let mut seen = HashSet::new();
236 let arity = self.ws.sig(sig).map_or(0, |s| s.params.len());
237
238 let mut frontier = vec![(sig.clone(), (0..arity).collect::<Vec<usize>>())];
242 while let Some((name, order)) = frontier.pop() {
243 if !seen.insert(name.clone()) {
244 continue;
245 }
246 found.extend(
247 self.registry
248 .proofs_of(&name)
249 .into_iter()
250 .map(|i| (i, order.clone())),
251 );
252 frontier.extend(
253 self.ws
254 .refiners_of(&name)
255 .iter()
256 .map(|r| (r.clone(), order.clone())),
257 );
258 frontier.extend(
259 self.ws
260 .equivalents_of(&name)
261 .iter()
262 .map(|e| (e.sig.clone(), e.apply(&order))),
263 );
264 }
265
266 if let Policy::Pinned(id) = policy {
267 found.retain(|(i, _)| &i.id == id);
268 return found;
269 }
270
271 found.sort_by_key(|(i, _)| self.rank(i, policy));
272 found
273 }
274
275 fn rank(&self, implementation: &Implementation, policy: &Policy) -> (u8, u8, u8, u8, String) {
277 let overhead = self
278 .registry
279 .environment(&implementation.environment)
280 .map(|e| e.reach.overhead())
281 .unwrap_or(u8::MAX);
282 let (time, space, _) = implementation.cost_key();
283 let id = implementation.id.to_string();
284
285 match policy {
286 Policy::Default => (0, overhead, time, space, id),
292 Policy::Fastest => (0, time, space, overhead, id),
293 Policy::MinMemory => (0, space, time, overhead, id),
294 Policy::PreferEnvironment(wanted) => (
295 u8::from(&implementation.environment != wanted),
296 time,
297 space,
298 overhead,
299 id,
300 ),
301 Policy::Pinned(_) => (0, time, space, overhead, id),
302 }
303 }
304
305 pub fn call<'a>(
311 &'a self,
312 sig: &'a QualifiedName,
313 args: Vec<Value>,
314 policy: &'a Policy,
315 ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
316 Box::pin(async move { self.dispatch(sig, &[], args, policy).await })
317 }
318
319 pub fn call_at<'a>(
328 &'a self,
329 sig: &'a QualifiedName,
330 type_args: &'a [Type],
331 args: Vec<Value>,
332 policy: &'a Policy,
333 ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
334 Box::pin(async move { self.dispatch(sig, type_args, args, policy).await })
335 }
336
337 async fn dispatch(
338 &self,
339 name: &QualifiedName,
340 type_args: &[Type],
341 args: Vec<Value>,
342 policy: &Policy,
343 ) -> Result<Invocation, DispatchError> {
344 let Some(declared) = self.ws.sig(name) else {
345 return Err(DispatchError::UnknownSignature(name.clone()));
346 };
347
348 if declared.params_decl.len() != type_args.len() {
349 return Err(DispatchError::TypeArity {
350 sig: name.clone(),
351 expected: declared.params_decl.len(),
352 got: type_args.len(),
353 });
354 }
355 let subst = unitype_core::check::bind(&declared.params_decl, type_args);
358 for (param, arg) in declared.params_decl.iter().zip(type_args) {
359 for bound in ¶m.bounds {
360 let required = Type::Ref(unitype_core::check::substitute_ref(bound, &subst));
361 if !self.ws.is_subtype(arg, &required) {
362 return Err(DispatchError::BoundNotMet {
363 sig: name.clone(),
364 param: param.name.clone(),
365 arg: arg.to_string(),
366 bound: required.to_string(),
367 });
368 }
369 }
370 }
371 let instantiated;
374 let sig = if type_args.is_empty() {
375 declared
376 } else {
377 instantiated = declared.instantiate(type_args);
378 &instantiated
379 };
380
381 if sig.params.len() != args.len() {
382 return Err(DispatchError::Arity {
383 sig: name.clone(),
384 expected: sig.params.len(),
385 got: args.len(),
386 });
387 }
388 if self.options.check_arguments {
389 for (index, (param, arg)) in sig.params.iter().zip(&args).enumerate() {
390 if let Err(errors) = self.ws.validate(arg, ¶m.ty) {
391 return Err(DispatchError::BadArgument {
392 sig: name.clone(),
393 index,
394 errors,
395 });
396 }
397 }
398 }
399
400 let candidates = self.routes(name, policy);
401 if candidates.is_empty() {
402 return match policy {
403 Policy::Pinned(id) => Err(DispatchError::Unusable {
404 id: id.to_string(),
405 reason: format!("nothing registered under that name proves `{name}`"),
406 }),
407 _ => Err(DispatchError::NoImplementation(name.clone())),
408 };
409 }
410
411 let expected = sig
414 .ret
415 .future_of()
416 .cloned()
417 .unwrap_or_else(|| sig.ret.clone());
418 let window = match &sig.ret {
422 Type::Bounded { wait, .. } => *wait,
423 _ => None,
424 };
425
426 let mut considered = Vec::with_capacity(candidates.len());
427 for (implementation, order) in candidates {
428 let cost = implementation.cost.to_string();
429 let environment = implementation.environment.clone();
430
431 if let Err(reason) = self.reachable(implementation) {
432 considered.push(Considered {
433 id: implementation.id.clone(),
434 environment,
435 cost,
436 outcome: Outcome::Unavailable(reason),
437 });
438 continue;
439 }
440
441 if let Some(reason) = over_budget(sig, &implementation.cost) {
444 considered.push(Considered {
445 id: implementation.id.clone(),
446 environment,
447 cost,
448 outcome: Outcome::Unavailable(reason),
449 });
450 continue;
451 }
452
453 let started = Instant::now();
454 let handed: Vec<Value> = order.iter().map(|&i| args[i].clone()).collect();
457 let types: Vec<Type> = order.iter().map(|&i| sig.params[i].ty.clone()).collect();
460 let call = self.invoke(implementation, handed, &types, &expected, policy);
461 let outcome = match window.and_then(|w| w.max) {
462 Some(max) => {
465 match tokio::time::timeout(millis(max.saturating_add(1)), call).await {
466 Ok(outcome) => outcome,
467 Err(_) => {
468 considered.push(Considered {
469 id: implementation.id.clone(),
470 environment: environment.clone(),
471 cost: cost.clone(),
472 outcome: Outcome::Failed(format!(
473 "did not answer within {max} ms, the window's end"
474 )),
475 });
476 continue;
477 }
478 }
479 }
480 None => call.await,
481 };
482 let elapsed = started.elapsed();
483 if let Some(w) = window {
486 let ms = i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX);
489 let early = w.min.is_some_and(|min| ms < min);
490 let late = w.max.is_some_and(|max| ms > max);
491 if early || late {
492 let why = if early {
493 format!(
494 "answered after {} ms, before the window opens at {} ms",
495 elapsed.as_millis(),
496 w.min.unwrap_or_default()
497 )
498 } else {
499 format!(
500 "answered after {} ms, after the window closes at {} ms",
501 elapsed.as_millis(),
502 w.max.unwrap_or_default()
503 )
504 };
505 considered.push(Considered {
506 id: implementation.id.clone(),
507 environment: environment.clone(),
508 cost: cost.clone(),
509 outcome: Outcome::Failed(why),
510 });
511 continue;
512 }
513 }
514
515 match outcome {
516 Ok(value) => {
517 if self.options.check_result {
518 if let Err(errors) = self.ws.validate(&value, &expected) {
519 return Err(DispatchError::BadResult {
523 id: implementation.id.to_string(),
524 sig: name.clone(),
525 errors,
526 });
527 }
528 }
529 considered.push(Considered {
530 id: implementation.id.clone(),
531 environment: environment.clone(),
532 cost,
533 outcome: Outcome::Answered,
534 });
535 return Ok(Invocation {
536 value,
537 implementation: implementation.id.clone(),
538 environment,
539 elapsed,
540 considered,
541 });
542 }
543 Err(error) => {
544 let recoverable = self.options.fall_back && error.is_environmental();
545 considered.push(Considered {
546 id: implementation.id.clone(),
547 environment,
548 cost,
549 outcome: Outcome::Failed(error.to_string()),
550 });
551 if !recoverable {
552 return Err(DispatchError::Exec {
553 id: implementation.id.to_string(),
554 source: error,
555 });
556 }
557 }
558 }
559 }
560
561 Err(DispatchError::NoneAvailable {
562 sig: name.clone(),
563 skipped: considered
564 .iter()
565 .map(|c| match &c.outcome {
566 Outcome::Unavailable(why) | Outcome::Failed(why) => {
567 format!("{}: {why}", c.id)
568 }
569 other => format!("{}: {other:?}", c.id),
570 })
571 .collect(),
572 })
573 }
574
575 fn reachable(&self, implementation: &Implementation) -> Result<(), String> {
577 let Some(environment) = self.registry.environment(&implementation.environment) else {
578 return Err(format!(
579 "environment `{}` is not registered",
580 implementation.environment
581 ));
582 };
583 match &environment.reach {
584 Reach::Here => {
585 if implementation.entry == INTRINSIC_ENTRY
586 || self.registry.native(&implementation.entry).is_some()
587 {
588 Ok(())
589 } else {
590 Err(format!(
591 "nothing is registered in this process under `{}`",
592 implementation.entry
593 ))
594 }
595 }
596 Reach::Subprocess { .. } => Ok(()),
600 #[cfg(feature = "wasm")]
601 Reach::Wasm { .. } => Ok(()),
602 other => Err(format!(
603 "reaching a `{}` environment is not built into this binary",
604 other.kind()
605 )),
606 }
607 }
608
609 async fn invoke(
615 &self,
616 implementation: &Implementation,
617 args: Vec<Value>,
618 params: &[Type],
619 expected: &Type,
620 policy: &Policy,
621 ) -> Result<Value, ExecError> {
622 let Some(environment) = self.registry.environment(&implementation.environment) else {
623 return Err(ExecError::Unreachable {
624 environment: implementation.environment.to_string(),
625 detail: "not registered".into(),
626 });
627 };
628
629 match &environment.reach {
630 Reach::Here => {
631 if implementation.entry == INTRINSIC_ENTRY {
635 let calls = Through {
636 dispatcher: self,
637 policy,
638 };
639 return eval_signature(&self.ws, &implementation.proves, args, &calls).await;
640 }
641 let Some(native) = self.registry.native(&implementation.entry) else {
642 return Err(ExecError::NotRegistered(implementation.entry.clone()));
643 };
644 native(args).await
645 }
646 Reach::Subprocess {
649 persistent: true, ..
650 } => {
651 self.workers
652 .invoke(
653 &self.ws,
654 environment,
655 implementation,
656 args,
657 params,
658 expected,
659 )
660 .await
661 }
662 Reach::Subprocess { .. } => {
663 crate::subprocess::invoke(
664 &self.ws,
665 environment,
666 implementation,
667 args,
668 params,
669 expected,
670 )
671 .await
672 }
673 #[cfg(feature = "wasm")]
674 Reach::Wasm { .. } => {
675 self.wasm
676 .get_or_init(crate::wasm::WasmHost::new)
677 .invoke(
678 &self.ws,
679 environment,
680 implementation,
681 args,
682 params,
683 expected,
684 )
685 .await
686 }
687 other => Err(ExecError::Unreachable {
688 environment: environment.id.to_string(),
689 detail: format!(
690 "reaching a `{}` environment is not built into this binary",
691 other.kind()
692 ),
693 }),
694 }
695 }
696}
697
698struct Through<'a> {
700 dispatcher: &'a Dispatcher,
701 policy: &'a Policy,
702}
703
704impl Calls for Through<'_> {
705 fn call<'a>(
706 &'a self,
707 sig: &'a QualifiedName,
708 args: Vec<Value>,
709 ) -> BoxFuture<'a, Result<Value, ExecError>> {
710 Box::pin(async move {
711 let policy = match self.policy {
714 Policy::Pinned(_) => &Policy::Default,
715 other => other,
716 };
717 self.dispatcher
718 .call(sig, args, policy)
719 .await
720 .map(|i| i.value)
721 .map_err(|e| ExecError::Failed {
722 id: sig.to_string(),
723 message: e.to_string(),
724 })
725 })
726 }
727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732 use unitype_core::check::check_workspace;
733 use unitype_core::{BigO, ImplProfile, Workspace};
734
735 use crate::environment::Environment;
736 use crate::implementation::Implementation;
737
738 fn q(s: &str) -> QualifiedName {
739 s.parse().unwrap()
740 }
741
742 fn here() -> Ident {
743 Ident::new("here").unwrap()
744 }
745
746 const SORT_WS: &str = r#"{"universes":[{"name":"demo","functions":[
747 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
748 {"name":"mergesort","refines":"demo::sort",
749 "params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#;
750
751 fn bubble(mut items: Vec<i64>) -> Vec<i64> {
753 for i in 0..items.len() {
754 for j in 0..items.len().saturating_sub(i + 1) {
755 if items[j] > items[j + 1] {
756 items.swap(j, j + 1);
757 }
758 }
759 }
760 items
761 }
762
763 fn ints(value: &Value) -> Vec<i64> {
764 let Value::List(items) = value else {
765 return Vec::new();
766 };
767 items.iter().filter_map(Value::as_int).collect()
768 }
769
770 fn sorting_dispatcher() -> Dispatcher {
772 let ws = Arc::new(
773 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
774 );
775 let mut registry = Registry::new();
776
777 registry.register_native_sync("merge_sort", |args| {
778 let mut items = ints(args.first().unwrap_or(&Value::Null));
779 items.sort_unstable();
780 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
781 });
782 registry.register_native_sync("bubble_sort", |args| {
783 let items = bubble(ints(args.first().unwrap_or(&Value::Null)));
784 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
785 });
786
787 registry
788 .register(Implementation::new(
789 "sort.merge",
790 q("demo::sort"),
791 here(),
792 "merge_sort",
793 ImplProfile::new(BigO::ONLogN, BigO::ON),
794 ))
795 .unwrap();
796 registry
797 .register(Implementation::new(
798 "sort.bubble",
799 q("demo::sort"),
800 here(),
801 "bubble_sort",
802 ImplProfile::new(BigO::ON2, BigO::O1),
803 ))
804 .unwrap();
805
806 Dispatcher::new(ws, Arc::new(registry))
807 }
808
809 async fn sort_with(policy: Policy) -> Invocation {
810 sorting_dispatcher()
811 .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &policy)
812 .await
813 .expect("answers")
814 }
815
816 fn list(items: &[i64]) -> Value {
817 Value::List(items.iter().copied().map(Value::Int).collect())
818 }
819
820 fn request_dispatcher() -> Dispatcher {
823 let ws = Arc::new(
824 check_workspace(
825 Workspace::from_json(
826 r#"{"universes":[
827 {"name":"node","functions":[{"name":"fetch","ret":"str","params":[
828 {"name":"url","ty":"str"},{"name":"retries","ty":"i64"}]}]},
829 {"name":"browser","functions":[{"name":"get","ret":"str","params":[
830 {"name":"attempts","ty":"i64"},{"name":"getUrl","ty":"str"}]}]}],
831 "links":[{"name":"fetch_is_get","from":"node::fetch","to":"browser::get",
832 "kind":{"k":"equivalent"}}]}"#,
833 )
834 .expect("reads"),
835 )
836 .expect("checks"),
837 );
838 let mut registry = Registry::new();
839 registry.register_native_sync("node_fetch", |args| {
841 let url = args.first().and_then(Value::as_str).unwrap_or("?");
842 let retries = args.get(1).and_then(Value::as_int).unwrap_or(-1);
843 Ok(Value::Str(format!("{url} x{retries}")))
844 });
845 registry
846 .register(Implementation::new(
847 "fetch.node",
848 q("node::fetch"),
849 here(),
850 "node_fetch",
851 ImplProfile::new(BigO::O1, BigO::O1),
852 ))
853 .unwrap();
854 Dispatcher::new(ws, Arc::new(registry))
855 }
856
857 #[tokio::test]
858 async fn a_proof_of_an_equivalent_proposition_gets_the_arguments_its_own_way_round() {
859 let dispatcher = request_dispatcher();
860
861 let answered = dispatcher
862 .call(
863 &q("browser::get"),
864 vec![Value::Int(3), Value::Str("https://x".into())],
865 &Policy::Default,
866 )
867 .await
868 .expect("the node proof answers the browser's call");
869 assert_eq!(answered.implementation.as_str(), "fetch.node");
870 assert_eq!(
871 answered.value,
872 Value::Str("https://x x3".into()),
873 "the URL went where the proof reads it"
874 );
875
876 let direct = dispatcher
877 .call(
878 &q("node::fetch"),
879 vec![Value::Str("https://x".into()), Value::Int(3)],
880 &Policy::Default,
881 )
882 .await
883 .expect("answers its own proposition");
884 assert_eq!(direct.value, answered.value, "and the same call either way");
885 }
886
887 #[tokio::test]
888 async fn pinning_a_proof_of_an_equivalent_proposition_still_reorders() {
889 let answered = request_dispatcher()
890 .call(
891 &q("browser::get"),
892 vec![Value::Int(1), Value::Str("https://y".into())],
893 &Policy::Pinned(ImplId::new("fetch.node")),
894 )
895 .await
896 .expect("answers");
897 assert_eq!(answered.value, Value::Str("https://y x1".into()));
898 }
899
900 #[tokio::test]
901 async fn a_generic_proposition_is_answered_by_a_proof_of_its_equivalent() {
902 let ws = Arc::new(
905 check_workspace(
906 Workspace::from_json(
907 r#"{"universes":[
908 {"name":"py","functions":[{"name":"konst",
909 "params_decl":[{"name":"A"},{"name":"B"}],
910 "params":[{"name":"x","ty":{"k":"param","name":"A"}},
911 {"name":"y","ty":{"k":"param","name":"B"}}],
912 "ret":{"k":"param","name":"A"}}]},
913 {"name":"js","functions":[{"name":"always",
914 "params_decl":[{"name":"Y"},{"name":"X"}],
915 "params":[{"name":"ignored","ty":{"k":"param","name":"Y"}},
916 {"name":"kept","ty":{"k":"param","name":"X"}}],
917 "ret":{"k":"param","name":"X"}}]}],
918 "links":[{"name":"konst_is_always","from":"py::konst","to":"js::always",
919 "kind":{"k":"equivalent"}}]}"#,
920 )
921 .expect("reads"),
922 )
923 .expect("checks"),
924 );
925 let mut registry = Registry::new();
926 registry.register_native_sync("py_konst", |args| Ok(args[0].clone()));
928 registry
929 .register(Implementation::new(
930 "konst.py",
931 q("py::konst"),
932 here(),
933 "py_konst",
934 ImplProfile::new(BigO::O1, BigO::O1),
935 ))
936 .unwrap();
937 let dispatcher = Dispatcher::new(ws, Arc::new(registry));
938
939 let answered = dispatcher
941 .call_at(
942 &q("js::always"),
943 &[Type::String, Type::I64],
944 vec![Value::Str("dropped".into()), Value::Int(7)],
945 &Policy::Default,
946 )
947 .await
948 .expect("the proof of konst answers, checked against always<str, i64>");
949 assert_eq!(answered.implementation.as_str(), "konst.py");
950 assert_eq!(answered.value, Value::Int(7));
951 }
952
953 #[tokio::test]
954 async fn asking_for_speed_and_asking_for_memory_choose_differently() {
955 let fast = sort_with(Policy::Fastest).await;
956 let frugal = sort_with(Policy::MinMemory).await;
957
958 assert_eq!(fast.implementation.as_str(), "sort.merge");
959 assert_eq!(frugal.implementation.as_str(), "sort.bubble");
960 }
961
962 #[tokio::test]
963 async fn and_both_give_the_same_answer() {
964 let fast = sort_with(Policy::Fastest).await;
965 let frugal = sort_with(Policy::MinMemory).await;
966 assert_eq!(fast.value, list(&[1, 2, 3]));
967 assert_eq!(
968 fast.value, frugal.value,
969 "which proof ran should not change what is true"
970 );
971 }
972
973 #[tokio::test]
974 async fn a_caller_can_see_what_was_considered_and_why() {
975 let chosen = sort_with(Policy::Fastest).await;
976 assert_eq!(chosen.considered.len(), 1, "the first one worked");
977 assert_eq!(chosen.considered[0].outcome, Outcome::Answered);
978 assert_eq!(chosen.environment, here());
979
980 let ranked: Vec<String> = sorting_dispatcher()
981 .candidates(&q("demo::sort"), &Policy::MinMemory)
982 .iter()
983 .map(|i| i.id.to_string())
984 .collect();
985 assert_eq!(ranked, ["sort.bubble", "sort.merge"]);
986 }
987
988 #[tokio::test]
989 async fn the_default_stays_in_the_process_where_it_can() {
990 let ws = Arc::new(
991 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
992 );
993 let mut registry = Registry::new();
994 registry.register_native_sync("bubble_sort", |args| {
995 Ok(Value::List(
996 bubble(ints(&args[0])).into_iter().map(Value::Int).collect(),
997 ))
998 });
999 registry
1000 .add_environment(Environment::subprocess("py", "python", "python3", &[]))
1001 .unwrap();
1002 registry
1004 .register(Implementation::new(
1005 "sort.py_merge",
1006 q("demo::sort"),
1007 Ident::new("py").unwrap(),
1008 "merge_sort",
1009 ImplProfile::new(BigO::ONLogN, BigO::ON),
1010 ))
1011 .unwrap();
1012 registry
1013 .register(Implementation::new(
1014 "sort.here_bubble",
1015 q("demo::sort"),
1016 here(),
1017 "bubble_sort",
1018 ImplProfile::new(BigO::ON2, BigO::O1),
1019 ))
1020 .unwrap();
1021
1022 let dispatcher = Dispatcher::new(ws, Arc::new(registry));
1023 let ranked: Vec<String> = dispatcher
1024 .candidates(&q("demo::sort"), &Policy::Default)
1025 .iter()
1026 .map(|i| i.id.to_string())
1027 .collect();
1028 assert_eq!(
1029 ranked[0], "sort.here_bubble",
1030 "starting a process costs more than the difference in complexity, \
1031 for the sizes most calls carry"
1032 );
1033
1034 let ranked: Vec<String> = dispatcher
1035 .candidates(&q("demo::sort"), &Policy::Fastest)
1036 .iter()
1037 .map(|i| i.id.to_string())
1038 .collect();
1039 assert_eq!(
1040 ranked[0], "sort.py_merge",
1041 "asked for speed, the better algorithm wins wherever it lives"
1042 );
1043 }
1044
1045 #[tokio::test]
1046 async fn a_pinned_proof_is_the_one_that_runs() {
1047 let pinned = sorting_dispatcher()
1048 .call(
1049 &q("demo::sort"),
1050 vec![list(&[2, 1])],
1051 &Policy::Pinned(ImplId::new("sort.bubble")),
1052 )
1053 .await
1054 .expect("answers");
1055 assert_eq!(pinned.implementation.as_str(), "sort.bubble");
1056 }
1057
1058 #[tokio::test]
1059 async fn pinning_something_that_proves_nothing_fails_rather_than_substituting() {
1060 let err = sorting_dispatcher()
1061 .call(
1062 &q("demo::sort"),
1063 vec![list(&[1])],
1064 &Policy::Pinned(ImplId::new("sort.nonexistent")),
1065 )
1066 .await
1067 .unwrap_err();
1068 assert!(
1069 matches!(err, DispatchError::Unusable { .. }),
1070 "asking for one thing and getting another would be worse: {err}"
1071 );
1072 }
1073
1074 #[tokio::test]
1075 async fn a_proposition_nobody_proves_says_so() {
1076 let ws = Arc::new(
1077 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1078 );
1079 let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
1080 assert!(matches!(
1081 dispatcher
1082 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
1083 .await,
1084 Err(DispatchError::NoImplementation(_))
1085 ));
1086 }
1087
1088 #[tokio::test]
1089 async fn arguments_are_checked_before_anything_runs() {
1090 let err = sorting_dispatcher()
1091 .call(
1092 &q("demo::sort"),
1093 vec![Value::Str("not a list".into())],
1094 &Policy::Default,
1095 )
1096 .await
1097 .unwrap_err();
1098 assert!(
1099 matches!(err, DispatchError::BadArgument { index: 0, .. }),
1100 "{err}"
1101 );
1102 }
1103
1104 #[tokio::test]
1105 async fn the_wrong_number_of_arguments_is_caught() {
1106 let err = sorting_dispatcher()
1107 .call(&q("demo::sort"), vec![], &Policy::Default)
1108 .await
1109 .unwrap_err();
1110 assert!(matches!(
1111 err,
1112 DispatchError::Arity {
1113 expected: 1,
1114 got: 0,
1115 ..
1116 }
1117 ));
1118 }
1119
1120 const BUDGET_WS: &str = r#"{"universes":[{"name":"demo","functions":[
1122 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
1123 "time":"o_n_log_n","space":"o1"}]}]}"#;
1124
1125 fn budget_dispatcher(registry: Registry) -> Dispatcher {
1126 let ws = Arc::new(
1127 check_workspace(Workspace::from_json(BUDGET_WS).expect("reads")).expect("checks"),
1128 );
1129 Dispatcher::new(ws, Arc::new(registry))
1130 }
1131
1132 fn sorting_proof(registry: &mut Registry, id: &str, profile: ImplProfile) {
1133 registry.register_native_sync(id, |args| Ok(args[0].clone()));
1134 registry
1135 .register(Implementation::new(
1136 format!("sort.{id}").as_str(),
1137 q("demo::sort"),
1138 here(),
1139 id,
1140 profile,
1141 ))
1142 .unwrap();
1143 }
1144
1145 #[tokio::test]
1146 async fn a_proof_that_claims_more_than_the_proposition_allows_is_not_asked() {
1147 let mut registry = Registry::new();
1148 sorting_proof(
1149 &mut registry,
1150 "bubble",
1151 ImplProfile::new(BigO::ON2, BigO::O1),
1152 );
1153 let err = budget_dispatcher(registry)
1154 .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
1155 .await
1156 .unwrap_err();
1157 let DispatchError::NoneAvailable { skipped, .. } = err else {
1158 panic!("expected the claim to be ruled out");
1159 };
1160 assert!(
1161 skipped
1162 .iter()
1163 .any(|s| s.contains("allows at most O(n log n)")),
1164 "{skipped:?}"
1165 );
1166 }
1167
1168 #[tokio::test]
1169 async fn a_proof_within_the_budget_answers_and_an_unnamed_claim_does_not() {
1170 let mut registry = Registry::new();
1171 sorting_proof(
1172 &mut registry,
1173 "merge",
1174 ImplProfile::new(BigO::ONLogN, BigO::O1),
1175 );
1176 let done = budget_dispatcher(registry)
1177 .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
1178 .await
1179 .expect("the claim fits the budget");
1180 assert_eq!(done.implementation.to_string(), "sort.merge");
1181
1182 let mut registry = Registry::new();
1183 sorting_proof(
1184 &mut registry,
1185 "vague",
1186 ImplProfile::new(BigO::Custom("usually fast".into()), BigO::O1),
1187 );
1188 assert!(
1189 budget_dispatcher(registry)
1190 .call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
1191 .await
1192 .is_err(),
1193 "a claim with no rank cannot be shown to fit a bound"
1194 );
1195 }
1196
1197 const WINDOW_WS: &str = r#"{"universes":[{"name":"demo","functions":[
1200 {"name":"fetch","params":[{"name":"url","ty":"str"}],
1201 "ret":{"k":"bounded","of":{"k":"future","of":"str"},"wait":{"min":20,"max":200}}}]}]}"#;
1202
1203 fn window_dispatcher(registry: Registry) -> Dispatcher {
1204 let ws = Arc::new(
1205 check_workspace(Workspace::from_json(WINDOW_WS).expect("reads")).expect("checks"),
1206 );
1207 Dispatcher::new(ws, Arc::new(registry))
1208 }
1209
1210 #[tokio::test]
1211 async fn a_proof_that_delivers_inside_its_window_answers() {
1212 let mut registry = Registry::new();
1213 registry.register_native_sync("steady", |_| {
1214 std::thread::sleep(Duration::from_millis(60));
1215 Ok(Value::Str("page".into()))
1216 });
1217 registry
1218 .register(Implementation::new(
1219 "fetch.steady",
1220 q("demo::fetch"),
1221 here(),
1222 "steady",
1223 ImplProfile::new(BigO::O1, BigO::O1),
1224 ))
1225 .unwrap();
1226
1227 let done = window_dispatcher(registry)
1228 .call(
1229 &q("demo::fetch"),
1230 vec![Value::Str("https://example.com".into())],
1231 &Policy::Default,
1232 )
1233 .await
1234 .expect("it delivers inside the window");
1235 assert!(matches!(done.value, Value::Str(ref s) if s == "page"));
1236 }
1237
1238 #[tokio::test]
1239 async fn a_proof_that_misses_the_window_is_passed_over_for_one_that_meets_it() {
1240 let mut registry = Registry::new();
1241 registry.register_native_sync("late", |_| {
1242 std::thread::sleep(Duration::from_millis(300));
1243 Ok(Value::Str("late".into()))
1244 });
1245 registry.register_native_sync("prompt", |_| {
1246 std::thread::sleep(Duration::from_millis(50));
1247 Ok(Value::Str("prompt".into()))
1248 });
1249 registry
1250 .register(Implementation::new(
1251 "fetch.late",
1252 q("demo::fetch"),
1253 here(),
1254 "late",
1255 ImplProfile::new(BigO::O1, BigO::O1),
1256 ))
1257 .unwrap();
1258 registry
1259 .register(Implementation::new(
1260 "fetch.prompt",
1261 q("demo::fetch"),
1262 here(),
1263 "prompt",
1264 ImplProfile::new(BigO::ON, BigO::ON),
1265 ))
1266 .unwrap();
1267
1268 let done = window_dispatcher(registry)
1270 .call(
1271 &q("demo::fetch"),
1272 vec![Value::Str("https://example.com".into())],
1273 &Policy::Fastest,
1274 )
1275 .await
1276 .expect("the prompt one meets the window");
1277 assert_eq!(done.implementation.to_string(), "fetch.prompt");
1278 assert!(
1279 done.considered.iter().any(|c| matches!(
1280 &c.outcome,
1281 Outcome::Failed(why) if why.contains("after the window closes")
1282 )),
1283 "the late answer is recorded, not hidden"
1284 );
1285 }
1286
1287 #[tokio::test]
1288 async fn a_window_nothing_meets_says_which_end_it_missed() {
1289 let mut registry = Registry::new();
1290 registry.register_native_sync("instant", |_| Ok(Value::Str("too soon".into())));
1291 registry
1292 .register(Implementation::new(
1293 "fetch.instant",
1294 q("demo::fetch"),
1295 here(),
1296 "instant",
1297 ImplProfile::new(BigO::O1, BigO::O1),
1298 ))
1299 .unwrap();
1300
1301 let err = window_dispatcher(registry)
1302 .call(
1303 &q("demo::fetch"),
1304 vec![Value::Str("https://example.com".into())],
1305 &Policy::Default,
1306 )
1307 .await
1308 .unwrap_err();
1309 let DispatchError::NoneAvailable { skipped, .. } = err else {
1310 panic!("expected no proof to meet the window, got {err}");
1311 };
1312 assert!(
1313 skipped
1314 .iter()
1315 .any(|s| s.contains("before the window opens")),
1316 "{skipped:?}"
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn a_proof_that_returns_the_wrong_thing_is_caught_and_never_excused() {
1322 let ws = Arc::new(
1323 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1324 );
1325 let mut registry = Registry::new();
1326 registry.register_native_sync("liar", |_| Ok(Value::Str("not a list at all".into())));
1327 registry.register_native_sync("honest", |args| Ok(args[0].clone()));
1328 registry
1329 .register(Implementation::new(
1330 "sort.liar",
1331 q("demo::sort"),
1332 here(),
1333 "liar",
1334 ImplProfile::new(BigO::O1, BigO::O1),
1335 ))
1336 .unwrap();
1337 registry
1338 .register(Implementation::new(
1339 "sort.honest",
1340 q("demo::sort"),
1341 here(),
1342 "honest",
1343 ImplProfile::new(BigO::ON, BigO::ON),
1344 ))
1345 .unwrap();
1346
1347 let dispatcher = Dispatcher::new(ws, Arc::new(registry)).with_options(Options {
1348 fall_back: true,
1349 ..Options::default()
1350 });
1351
1352 let err = dispatcher
1353 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Fastest)
1354 .await
1355 .unwrap_err();
1356
1357 assert!(
1358 matches!(err, DispatchError::BadResult { .. }),
1359 "even with fallback on, a broken proof must not be quietly replaced: {err}"
1360 );
1361 }
1362
1363 #[tokio::test]
1364 async fn a_proof_of_a_stronger_claim_answers_the_weaker_one() {
1365 let ws = Arc::new(
1366 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1367 );
1368 let mut registry = Registry::new();
1369 registry.register_native_sync("merge_sort", |args| {
1370 let mut items = ints(&args[0]);
1371 items.sort_unstable();
1372 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
1373 });
1374 registry
1377 .register(Implementation::new(
1378 "mergesort.rust",
1379 q("demo::mergesort"),
1380 here(),
1381 "merge_sort",
1382 ImplProfile::new(BigO::ONLogN, BigO::ON),
1383 ))
1384 .unwrap();
1385
1386 let answer = Dispatcher::new(ws, Arc::new(registry))
1387 .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &Policy::Default)
1388 .await
1389 .expect("a proof of the stronger claim proves this one");
1390
1391 assert_eq!(answer.implementation.as_str(), "mergesort.rust");
1392 assert_eq!(answer.value, list(&[1, 2, 3]));
1393 }
1394
1395 #[tokio::test]
1396 async fn an_environment_that_cannot_be_reached_is_reported_with_the_reason() {
1397 let ws = Arc::new(
1398 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1399 );
1400 let mut registry = Registry::new();
1401 registry
1402 .add_environment(Environment::subprocess(
1403 "missing",
1404 "python",
1405 "unitype_no_such_interpreter",
1406 &[],
1407 ))
1408 .unwrap();
1409 registry
1410 .register(Implementation::new(
1411 "sort.elsewhere",
1412 q("demo::sort"),
1413 Ident::new("missing").unwrap(),
1414 "bubble_sort",
1415 ImplProfile::new(BigO::ON2, BigO::O1),
1416 ))
1417 .unwrap();
1418
1419 let err = Dispatcher::new(ws, Arc::new(registry))
1420 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
1421 .await
1422 .unwrap_err();
1423
1424 let message = err.to_string();
1425 assert!(message.contains("sort.elsewhere"), "{message}");
1426 assert!(
1427 message.contains("could not start"),
1428 "the reason should be the actual one: {message}"
1429 );
1430 }
1431
1432 #[tokio::test]
1433 async fn a_body_that_calls_out_is_answered_by_the_dispatcher() {
1434 let ws = Arc::new(
1435 check_workspace(
1436 Workspace::from_json(
1437 r#"{"universes":[{"name":"demo","functions":[
1438 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
1439 {"name":"sorted_twice","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
1440 "body":{"k":"call","sig":"demo::sort","args":[
1441 {"k":"call","sig":"demo::sort","args":[{"k":"var","name":"xs"}]}]}}]}]}"#,
1442 )
1443 .expect("reads"),
1444 )
1445 .expect("checks"),
1446 );
1447
1448 let mut registry = Registry::new();
1449 registry.register_bodies(&ws).unwrap();
1450 registry.register_native_sync("merge_sort", |args| {
1451 let mut items = ints(&args[0]);
1452 items.sort_unstable();
1453 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
1454 });
1455 registry
1456 .register(Implementation::new(
1457 "sort.merge",
1458 q("demo::sort"),
1459 here(),
1460 "merge_sort",
1461 ImplProfile::new(BigO::ONLogN, BigO::ON),
1462 ))
1463 .unwrap();
1464
1465 let answer = Dispatcher::new(ws, Arc::new(registry))
1466 .call(
1467 &q("demo::sorted_twice"),
1468 vec![list(&[3, 1, 2])],
1469 &Policy::Default,
1470 )
1471 .await
1472 .expect("answers");
1473
1474 assert_eq!(answer.value, list(&[1, 2, 3]));
1475 assert!(
1476 answer.implementation.as_str().ends_with("#body"),
1477 "the body proved it, and the dispatcher answered what the body asked"
1478 );
1479 }
1480
1481 const GENERIC_WS: &str = r#"{"universes":[{"name":"demo","functions":[
1482 {"name":"reverse","params_decl":[{"name":"T"}],
1483 "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
1484 "ret":{"k":"list","of":{"k":"param","name":"T"}}}]}]}"#;
1485
1486 fn reversing_dispatcher() -> Dispatcher {
1488 let ws = Arc::new(
1489 check_workspace(Workspace::from_json(GENERIC_WS).expect("reads")).expect("checks"),
1490 );
1491 let mut registry = Registry::new();
1492 registry.register_native_sync("reverse", |mut args| {
1493 let Value::List(items) = args.remove(0) else {
1494 return Err(ExecError::Untyped("expected a list".into()));
1495 };
1496 Ok(Value::List(items.into_iter().rev().collect()))
1497 });
1498 registry
1499 .register(Implementation::new(
1500 "reverse.here",
1501 q("demo::reverse"),
1502 here(),
1503 "reverse",
1504 ImplProfile::new(BigO::ON, BigO::ON),
1505 ))
1506 .unwrap();
1507 Dispatcher::new(ws, Arc::new(registry))
1508 }
1509
1510 #[tokio::test]
1511 async fn a_generic_proposition_is_called_at_a_type() {
1512 let dispatcher = reversing_dispatcher();
1513 let words = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())]);
1514
1515 let at_strings = dispatcher
1516 .call_at(
1517 &q("demo::reverse"),
1518 &[Type::String],
1519 vec![words],
1520 &Policy::Default,
1521 )
1522 .await
1523 .expect("answers");
1524 assert_eq!(
1525 at_strings.value,
1526 Value::List(vec![Value::Str("b".into()), Value::Str("a".into())])
1527 );
1528
1529 let at_ints = dispatcher
1530 .call_at(
1531 &q("demo::reverse"),
1532 &[Type::I64],
1533 vec![list(&[1, 2])],
1534 &Policy::Default,
1535 )
1536 .await
1537 .expect("answers");
1538 assert_eq!(at_ints.value, list(&[2, 1]));
1539 }
1540
1541 #[tokio::test]
1542 async fn a_generic_proposition_called_without_its_type_says_what_is_missing() {
1543 let err = reversing_dispatcher()
1546 .call(&q("demo::reverse"), vec![list(&[1, 2])], &Policy::Default)
1547 .await
1548 .unwrap_err();
1549 assert!(
1550 matches!(
1551 err,
1552 DispatchError::TypeArity {
1553 expected: 1,
1554 got: 0,
1555 ..
1556 }
1557 ),
1558 "{err}"
1559 );
1560 }
1561
1562 #[tokio::test]
1563 async fn a_generic_proposition_is_not_asked_at_a_type_its_bound_rules_out() {
1564 let ws = Arc::new(
1565 check_workspace(
1566 Workspace::from_json(
1567 r#"{"universes":[{"name":"demo",
1568 "types":[{"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
1569 {"k":"struct","name":"Person","implements":["Named"],
1570 "fields":[{"name":"name","ty":"str"}]}],
1571 "functions":[{"name":"first_named",
1572 "params_decl":[{"name":"T","bounds":["Named"]}],
1573 "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
1574 "ret":{"k":"optional","of":{"k":"param","name":"T"}}}]}]}"#,
1575 )
1576 .expect("reads"),
1577 )
1578 .expect("checks"),
1579 );
1580 let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
1581 let person = Type::Ref(unitype_core::ir::TypeRef::qualified(
1582 Ident::new("demo").unwrap(),
1583 Ident::new("Person").unwrap(),
1584 ));
1585
1586 let err = dispatcher
1587 .call_at(
1588 &q("demo::first_named"),
1589 &[Type::I64],
1590 vec![list(&[1])],
1591 &Policy::Default,
1592 )
1593 .await
1594 .unwrap_err();
1595 assert!(
1596 matches!(&err, DispatchError::BoundNotMet { param, .. } if param.as_str() == "T"),
1597 "an integer has no name: {err}"
1598 );
1599
1600 let err = dispatcher
1603 .call_at(
1604 &q("demo::first_named"),
1605 &[person],
1606 vec![Value::List(vec![])],
1607 &Policy::Default,
1608 )
1609 .await
1610 .unwrap_err();
1611 assert!(matches!(err, DispatchError::NoImplementation(_)), "{err}");
1612 }
1613
1614 #[tokio::test]
1615 async fn the_boundary_is_checked_at_the_type_the_call_named() {
1616 let err = reversing_dispatcher()
1619 .call_at(
1620 &q("demo::reverse"),
1621 &[Type::String],
1622 vec![list(&[1, 2])],
1623 &Policy::Default,
1624 )
1625 .await
1626 .unwrap_err();
1627 assert!(
1628 matches!(err, DispatchError::BadArgument { index: 0, .. }),
1629 "{err}"
1630 );
1631 }
1632}