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
//! Generate, register, dispatch — with nothing written by hand in between.
//!
//! The claim that generated code is *reachable* is easy to make and easy to
//! leave untested, because the pieces sit in different crates and each one
//! passes its own tests. So this walks the whole path: ask unitype for a
//! harness, write a proof module that uses it, point a manifest at that module,
//! and call the proposition through the dispatcher.
//!
//! If a backend ever emits a harness that does not speak the protocol, this is
//! where it shows up rather than in somebody's project.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use unitype_codegen::{Backend, GenOptions, haskell, python, typescript};
use unitype_core::check::{CheckedWorkspace, check_workspace};
use unitype_core::value::Value;
use unitype_core::{BigO, ImplProfile, QualifiedName, Workspace};
use unitype_runtime::environment::Reach;
use unitype_runtime::implementation::Implementation;
use unitype_runtime::{Dispatcher, Environment, Policy, Registry};

const WS: &str = r#"{"universes":[{"name":"demo","types":[
    {"k":"struct","name":"Tally","fields":[
        {"name":"total","ty":"i64"},{"name":"seen","ty":"[str]"}]}],
  "functions":[
    {"name":"tally","params":[{"name":"words","ty":"[str]"}],"ret":"Tally"}]}]}"#;

fn workspace() -> CheckedWorkspace {
    check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks")
}

fn have_python() -> bool {
    std::process::Command::new("python3")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// Writes the generated Python out, plus a module that uses its harness.
fn generated_module(name: &str) -> PathBuf {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("makes a directory");

    for file in python::Python
        .generate(&workspace(), &GenOptions::default())
        .expect("generates")
    {
        let at = dir.join(file.path.file_name().expect("a file name"));
        std::fs::write(at, file.contents).expect("writes");
    }

    // The only thing written by hand: the proof itself, and the line saying
    // which proposition it proves.
    std::fs::write(
        dir.join("proof.py"),
        r#"from unitype_harness import unitype_main
from demo import Tally
import dataclasses


def tally(words):
    counted = Tally(total=len(words), seen=sorted(set(words)))
    return dataclasses.asdict(counted)


if __name__ == "__main__":
    unitype_main({"tally": tally})
"#,
    )
    .expect("writes the proof");
    dir
}

/// Whether this Node runs TypeScript as it is, by dropping the types.
fn have_node() -> bool {
    let Ok(output) = std::process::Command::new("node").arg("--version").output() else {
        return false;
    };
    String::from_utf8_lossy(&output.stdout)
        .trim()
        .trim_start_matches('v')
        .split('.')
        .next()
        .and_then(|major| major.parse::<u32>().ok())
        .is_some_and(|major| major >= 24)
}

/// Writes the generated TypeScript out, plus a module that uses its harness.
fn generated_node_module(name: &str) -> PathBuf {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("makes a directory");

    for file in typescript::TypeScript
        .generate(&workspace(), &GenOptions::default())
        .expect("generates")
    {
        let at = dir.join(file.path.file_name().expect("a file name"));
        std::fs::write(at, file.contents).expect("writes");
    }

    // Says the directory holds modules, so Node does not have to work it out.
    std::fs::write(dir.join("package.json"), "{\"type\": \"module\"}\n").expect("writes");

    // Again the only thing written by hand, and written against the generated
    // `Tally` so that the declaration is loaded rather than merely present.
    std::fs::write(
        dir.join("proof.ts"),
        r#"import { unitypeMain } from "./unitype_harness.ts";
import type { Tally } from "./demo.ts";

function tally(words: string[]): Tally {
  return { total: words.length, seen: [...new Set(words)].sort() };
}

unitypeMain({ tally });
"#,
    )
    .expect("writes the proof");
    dir
}

/// A dispatcher pointed at the Python module, kept alive or not.
fn dispatcher(dir: &Path, persistent: bool) -> Dispatcher {
    dispatcher_for(
        Environment::subprocess("py", "python", "python3", &["proof.py"]),
        dir,
        persistent,
    )
}

/// A dispatcher pointed at the Node module, kept alive or not.
fn node_dispatcher(dir: &Path, persistent: bool) -> Dispatcher {
    dispatcher_for(
        Environment::subprocess("node", "typescript", "node", &["proof.ts"]),
        dir,
        persistent,
    )
}

fn dispatcher_for(mut environment: Environment, dir: &Path, persistent: bool) -> Dispatcher {
    let reached = environment.id.clone();
    if let Reach::Subprocess {
        cwd,
        persistent: keep,
        timeout_ms,
        ..
    } = &mut environment.reach
    {
        *cwd = Some(dir.to_path_buf());
        *keep = persistent;
        *timeout_ms = 30_000;
    }

    let mut registry = Registry::new();
    registry.add_environment(environment).expect("registers");
    registry
        .register(Implementation::new(
            "tally.py",
            "demo::tally".parse::<QualifiedName>().unwrap(),
            reached,
            "tally",
            ImplProfile::new(BigO::ON, BigO::ON),
        ))
        .expect("registers");

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

fn words(items: &[&str]) -> Value {
    Value::List(items.iter().map(|w| Value::Str((*w).into())).collect())
}

#[tokio::test]
async fn a_generated_harness_is_reachable_as_a_proof() {
    if !have_python() {
        eprintln!("no python3 on this machine; skipping");
        return;
    }

    let dir = generated_module("generated_oneshot");
    let answer = dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a", "b", "a"])],
            &Policy::Default,
        )
        .await
        .expect("answers");

    // Checked against the signature on the way back, so this really is a Tally
    // rather than something Tally-shaped.
    assert_eq!(answer.value.get("total"), Some(&Value::Int(3)));
    assert_eq!(
        answer.value.get("seen"),
        Some(&words(&["a", "b"])),
        "{:?}",
        answer.value
    );
}

#[tokio::test]
async fn the_same_generated_harness_serves_a_worker_without_changing() {
    if !have_python() {
        return;
    }

    // Nothing about the module differs. Reading lines was always going to work
    // for one message or many, which is why there is no mode to get wrong.
    let dir = generated_module("generated_worker");
    let dispatcher = dispatcher(&dir, true);

    for (input, total) in [
        (&["a"][..], 1),
        (&["a", "b"][..], 2),
        (&["a", "b", "c"][..], 3),
    ] {
        let answer = dispatcher
            .call(
                &"demo::tally".parse().unwrap(),
                vec![words(input)],
                &Policy::Default,
            )
            .await
            .expect("answers");
        assert_eq!(answer.value.get("total"), Some(&Value::Int(total)));
    }

    assert_eq!(
        dispatcher.workers().running().await,
        1,
        "three calls, one interpreter"
    );
}

#[tokio::test]
async fn a_generated_proof_is_held_to_the_signature_like_any_other() {
    if !have_python() {
        return;
    }

    let dir = generated_module("generated_wrong");
    // Replace the proof with one that returns the wrong shape. The generated
    // dataclass would have stopped this; going around it should not get past
    // the boundary check.
    std::fs::write(
        dir.join("proof.py"),
        r#"from unitype_harness import unitype_main

if __name__ == "__main__":
    unitype_main({"tally": lambda words: {"total": "not a number"}})
"#,
    )
    .expect("writes");

    let failed = dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a"])],
            &Policy::Default,
        )
        .await;

    assert!(
        failed
            .as_ref()
            .is_err_and(|e| e.to_string().contains("not a")),
        "{failed:?}"
    );
}

#[tokio::test]
async fn the_generated_node_harness_is_reachable_as_a_proof_too() {
    if !have_node() {
        eprintln!("no node that reads TypeScript on this machine; skipping");
        return;
    }

    let dir = generated_node_module("generated_node_oneshot");
    let answer = node_dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a", "b", "a"])],
            &Policy::Default,
        )
        .await
        .expect("answers");

    assert_eq!(answer.value.get("total"), Some(&Value::Int(3)));
    assert_eq!(
        answer.value.get("seen"),
        Some(&words(&["a", "b"])),
        "{:?}",
        answer.value
    );
}

#[tokio::test]
async fn the_generated_node_harness_serves_a_worker_without_changing() {
    if !have_node() {
        return;
    }

    let dir = generated_node_module("generated_node_worker");
    let dispatcher = node_dispatcher(&dir, true);

    for (input, total) in [(&["a"][..], 1), (&["a", "b"][..], 2)] {
        let answer = dispatcher
            .call(
                &"demo::tally".parse().unwrap(),
                vec![words(input)],
                &Policy::Default,
            )
            .await
            .expect("answers");
        assert_eq!(answer.value.get("total"), Some(&Value::Int(total)));
    }

    assert_eq!(
        dispatcher.workers().running().await,
        1,
        "two calls, one interpreter"
    );
}

fn have_ghc() -> bool {
    std::process::Command::new("ghc")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// Compiles a Haskell proof that sits beside the generated modules.
///
/// Built once and run as a program, which is how a Haskell proof is meant to
/// be reached: starting `runghc` for every call would read the sources again
/// each time.
fn compile_haskell(dir: &Path) {
    let built = std::process::Command::new("ghc")
        .args(["-v0", "-O0", "-outputdir", "obj", "-o", "proof", "Proof.hs"])
        .current_dir(dir)
        .output()
        .expect("runs ghc");
    assert!(
        built.status.success(),
        "the proof did not build:\n{}",
        String::from_utf8_lossy(&built.stderr)
    );
}

/// Writes the generated Haskell out, plus a program that uses its harness.
fn generated_haskell_module(name: &str) -> PathBuf {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("makes a directory");

    for file in haskell::Haskell
        .generate(&workspace(), &GenOptions::default())
        .expect("generates")
    {
        let at = dir.join(file.path.file_name().expect("a file name"));
        std::fs::write(at, file.contents).expect("writes");
    }

    // The only thing written by hand: the proof itself, and the line saying
    // which proposition it proves. Written against the generated `Tally` so
    // that the declaration is loaded rather than merely present.
    std::fs::write(
        dir.join("Proof.hs"),
        r#"{-# LANGUAGE OverloadedStrings #-}
module Main (main) where

import qualified Data.Set as Set
import Data.Text (Text)
import Demo (Tally (..))
import UnitypeHarness (proves, unitypeMain)

tally :: [Text] -> Tally
tally words =
  Tally {tallyTotal = fromIntegral (length words), tallySeen = Set.toList (Set.fromList words)}

main :: IO ()
main = unitypeMain [("tally", proves tally)]
"#,
    )
    .expect("writes the proof");
    compile_haskell(&dir);
    dir
}

/// A dispatcher pointed at the compiled Haskell proof, kept alive or not.
fn haskell_dispatcher(dir: &Path, persistent: bool) -> Dispatcher {
    let program = dir.join("proof");
    dispatcher_for(
        Environment::subprocess("hs", "haskell", program.to_str().expect("a path"), &[]),
        dir,
        persistent,
    )
}

#[tokio::test]
async fn the_generated_haskell_harness_is_reachable_as_a_proof_too() {
    if !have_ghc() {
        eprintln!("no ghc on this machine; skipping");
        return;
    }

    let dir = generated_haskell_module("generated_haskell_oneshot");
    let answer = haskell_dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a", "b", "a"])],
            &Policy::Default,
        )
        .await
        .expect("answers");

    // Checked against the signature on the way back, so this really is a Tally
    // rather than something Tally-shaped.
    assert_eq!(answer.value.get("total"), Some(&Value::Int(3)));
    assert_eq!(
        answer.value.get("seen"),
        Some(&words(&["a", "b"])),
        "{:?}",
        answer.value
    );
}

#[tokio::test]
async fn the_generated_haskell_harness_serves_a_worker_without_changing() {
    if !have_ghc() {
        return;
    }

    let dir = generated_haskell_module("generated_haskell_worker");
    let dispatcher = haskell_dispatcher(&dir, true);

    for (input, total) in [(&["a"][..], 1), (&["a", "b"][..], 2), (&["é", "é"][..], 2)] {
        let answer = dispatcher
            .call(
                &"demo::tally".parse().unwrap(),
                vec![words(input)],
                &Policy::Default,
            )
            .await
            .expect("answers");
        assert_eq!(answer.value.get("total"), Some(&Value::Int(total)));
    }

    assert_eq!(
        dispatcher.workers().running().await,
        1,
        "three calls, one process"
    );
}

#[tokio::test]
async fn a_haskell_proof_that_throws_is_reported_as_failing_not_as_a_broken_environment() {
    if !have_ghc() {
        return;
    }

    let dir = generated_haskell_module("generated_haskell_throws");
    std::fs::write(
        dir.join("Proof.hs"),
        r#"module Main (main) where

import Data.Text (Text)
import Demo (Tally (..))
import UnitypeHarness (proves, unitypeMain)

tally :: [Text] -> Tally
tally _ = error "the tally went wrong"

main :: IO ()
main = unitypeMain [("tally", proves tally)]
"#,
    )
    .expect("writes");
    compile_haskell(&dir);

    let failed = haskell_dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a"])],
            &Policy::Default,
        )
        .await;

    assert!(
        failed
            .as_ref()
            .is_err_and(|e| e.to_string().contains("the tally went wrong")),
        "{failed:?}"
    );
}

#[tokio::test]
async fn a_generated_haskell_proof_is_held_to_the_signature_like_any_other() {
    if !have_ghc() {
        return;
    }

    let dir = generated_haskell_module("generated_haskell_wrong");
    // Replace the proof with one that returns the wrong shape. The generated
    // record would have stopped this; going around it by answering with parsed
    // JSON should not get past the boundary check.
    std::fs::write(
        dir.join("Proof.hs"),
        r#"{-# LANGUAGE OverloadedStrings #-}
module Main (main) where

import qualified Data.Map.Strict as Map
import Data.Text (Text)
import UnitypeHarness (proves, unitypeMain)
import UnitypeSupport (Json (..))

wrong :: [Text] -> Json
wrong _ = JObject (Map.fromList [("total", JString "not a number")])

main :: IO ()
main = unitypeMain [("tally", proves wrong)]
"#,
    )
    .expect("writes");
    compile_haskell(&dir);

    let failed = haskell_dispatcher(&dir, false)
        .call(
            &"demo::tally".parse().unwrap(),
            vec![words(&["a"])],
            &Policy::Default,
        )
        .await;

    assert!(
        failed
            .as_ref()
            .is_err_and(|e| e.to_string().contains("not a")),
        "{failed:?}"
    );
}