Skip to main content

unitype_runtime/
subprocess.rs

1//! Reaching an environment by starting a program.
2//!
3//! The simplest way to let another language prove something: run it, hand it
4//! one JSON message, and read one back. No linking, no bindings, no foreign
5//! function interface — a program that can read standard input and write
6//! standard output can participate, which is every language worth naming.
7//!
8//! # The exchange
9//!
10//! One request in, one response out, and the process exits:
11//!
12//! ```text
13//! → {"unitype":"1","kind":"invoke","signature":"demo::sort",
14//!    "entry":"bubble_sort","args":[[3,1,2]]}
15//! ← {"ok":true,"value":[1,2,3]}
16//! ```
17//!
18//! Each message is one line, and end of input ends the stream, so a child that
19//! reads lines and a child that reads to the end are both correct here. Nothing
20//! has to agree on a length prefix, and a child written in ten lines of Python
21//! works by construction.
22//!
23//! Starting a process per call is real overhead — around twenty milliseconds
24//! for Python, against microseconds of work — which is why the default policy
25//! prefers to stay in this one. A program calling repeatedly should ask for a
26//! worker instead; see [`crate::worker`]. This is the version that cannot get
27//! stuck holding state it should not have, which is why it stays the default.
28
29use std::process::Stdio;
30use std::time::Duration;
31
32use serde::{Deserialize, Serialize};
33use tokio::io::AsyncWriteExt;
34use tokio::process::Command;
35use unitype_core::check::CheckedWorkspace;
36use unitype_core::ir::Type;
37use unitype_core::value::Value;
38
39use crate::environment::{Environment, Reach};
40use crate::error::ExecError;
41use crate::implementation::Implementation;
42
43/// The wire protocol version this build speaks.
44pub const PROTOCOL_VERSION: &str = "1";
45
46/// How much of what a failing child said is worth keeping.
47const STDERR_KEPT: usize = 8 * 1024;
48
49/// What the parent sends.
50#[derive(Debug, Serialize, Deserialize)]
51pub struct Request {
52    /// The protocol version.
53    pub unitype: String,
54    /// What is being asked for. Only `invoke` for now, but a child that checks
55    /// it will keep working when there is more.
56    pub kind: String,
57    /// The proposition being proved, so a child can log something useful.
58    pub signature: String,
59    /// Which of the child's functions to call.
60    pub entry: String,
61    /// The arguments, in declaration order.
62    pub args: Vec<serde_json::Value>,
63}
64
65/// What the child sends back.
66#[derive(Debug, Serialize, Deserialize)]
67pub struct Response {
68    /// Whether it worked.
69    pub ok: bool,
70    /// What it produced.
71    ///
72    /// `null` is an answer — a proposition returning `T?` answering nothing —
73    /// and is kept apart from the member being left out, which is no answer
74    /// at all.
75    #[serde(default, deserialize_with = "present_value")]
76    pub value: Option<serde_json::Value>,
77    /// What went wrong.
78    #[serde(default)]
79    pub error: Option<ResponseError>,
80}
81
82/// Keeps a `value` that is written as `null`, which serde would otherwise read
83/// as the member being absent.
84fn present_value<'de, D: serde::Deserializer<'de>>(
85    d: D,
86) -> Result<Option<serde_json::Value>, D::Error> {
87    serde_json::Value::deserialize(d).map(Some)
88}
89
90/// A failure the child reported for itself.
91#[derive(Debug, Serialize, Deserialize)]
92pub struct ResponseError {
93    /// A short machine-readable tag.
94    #[serde(default)]
95    pub code: String,
96    /// What happened, for a person.
97    pub message: String,
98}
99
100/// Runs an implementation by starting a program and exchanging one message.
101///
102/// `params` is the type each argument is written against, in the same order.
103pub async fn invoke(
104    ws: &CheckedWorkspace,
105    environment: &Environment,
106    implementation: &Implementation,
107    args: Vec<Value>,
108    params: &[Type],
109    expected: &Type,
110) -> Result<Value, ExecError> {
111    let Reach::Subprocess {
112        command,
113        args: argv,
114        cwd,
115        env,
116        timeout_ms,
117        ..
118    } = &environment.reach
119    else {
120        return Err(ExecError::Unreachable {
121            environment: environment.id.to_string(),
122            detail: "this is not a subprocess environment".into(),
123        });
124    };
125
126    // A trailing newline costs nothing here — JSON ignores it — and means the
127    // same bytes work for a child that reads lines, which is what a worker
128    // needs. One message, framed two ways at once.
129    let mut body = request_line(ws, implementation, &args, params)?;
130    body.push(b'\n');
131
132    let mut process = Command::new(command);
133    process
134        .args(argv)
135        .envs(env)
136        .stdin(Stdio::piped())
137        .stdout(Stdio::piped())
138        .stderr(Stdio::piped())
139        // If this call is abandoned — a timeout, a cancelled caller — the child
140        // goes with it rather than being left behind.
141        .kill_on_drop(true);
142    if let Some(dir) = cwd {
143        process.current_dir(dir);
144    }
145
146    let mut child = crate::spawn::spawn(&mut process).map_err(|source| ExecError::Unreachable {
147        environment: environment.id.to_string(),
148        detail: format!("could not start `{command}`: {source}"),
149    })?;
150
151    let mut stdin = child.stdin.take().expect("stdin was piped");
152    stdin
153        .write_all(&body)
154        .await
155        .map_err(|source| ExecError::Protocol {
156            id: implementation.id.to_string(),
157            detail: format!("could not send the request: {source}"),
158        })?;
159    // Closing this is the end of the message. Without it the child waits.
160    drop(stdin);
161
162    let output = tokio::time::timeout(Duration::from_millis(*timeout_ms), child.wait_with_output())
163        .await
164        .map_err(|_| ExecError::Timeout {
165            id: implementation.id.to_string(),
166            millis: *timeout_ms,
167        })?
168        .map_err(|source| ExecError::Unreachable {
169            environment: environment.id.to_string(),
170            detail: format!("could not read from `{command}`: {source}"),
171        })?;
172
173    if !output.status.success() {
174        return Err(ExecError::Failed {
175            id: implementation.id.to_string(),
176            message: format!(
177                "exited with {}{}",
178                output
179                    .status
180                    .code()
181                    .map(|c| c.to_string())
182                    .unwrap_or_else(|| "a signal".into()),
183                tail(&output.stderr),
184            ),
185        });
186    }
187
188    let text = String::from_utf8_lossy(&output.stdout);
189    read_answer_with(ws, implementation, &text, expected, &tail(&output.stderr))
190}
191
192/// The bytes of one request, ready to send.
193///
194/// Shared by every way of reaching a child, so a worker, a one-shot process
195/// and a sandbox are sent exactly the same thing. Each argument is written
196/// against its parameter's type, in the typed form: a tuple arrives as the
197/// array the child's own code expects, not as an escape it would have to
198/// know about. An argument with no type given is written as it would be with
199/// no type at all.
200pub(crate) fn request_line(
201    ws: &CheckedWorkspace,
202    implementation: &Implementation,
203    args: &[Value],
204    params: &[Type],
205) -> Result<Vec<u8>, ExecError> {
206    let encoded: Vec<serde_json::Value> = args
207        .iter()
208        .enumerate()
209        .map(|(i, a)| match params.get(i) {
210            Some(ty) => ws.typed_json(a, ty),
211            None => a.to_json(),
212        })
213        .collect::<Result<_, _>>()
214        .map_err(|e| ExecError::Protocol {
215            id: implementation.id.to_string(),
216            detail: format!("an argument could not be encoded: {e}"),
217        })?;
218
219    let request = Request {
220        unitype: PROTOCOL_VERSION.to_string(),
221        kind: "invoke".to_string(),
222        signature: implementation.proves.to_string(),
223        entry: implementation.entry.clone(),
224        args: encoded,
225    };
226    Ok(serde_json::to_vec(&request).expect("a request serializes"))
227}
228
229/// Reads what a child sent back, against the type its signature promises.
230pub(crate) fn read_answer(
231    ws: &CheckedWorkspace,
232    implementation: &Implementation,
233    text: &str,
234    expected: &Type,
235) -> Result<Value, ExecError> {
236    read_answer_with(ws, implementation, text, expected, "")
237}
238
239/// The same, with whatever the child said on its error stream to add if the
240/// response turns out to be unreadable — which is usually where the reason is.
241fn read_answer_with(
242    ws: &CheckedWorkspace,
243    implementation: &Implementation,
244    text: &str,
245    expected: &Type,
246    context: &str,
247) -> Result<Value, ExecError> {
248    let response: Response = serde_json::from_str(text).map_err(|source| ExecError::Protocol {
249        id: implementation.id.to_string(),
250        detail: format!("could not read the response: {source}{context}"),
251    })?;
252
253    if !response.ok {
254        let reported = response
255            .error
256            .map(|e| e.message)
257            .unwrap_or_else(|| "it said it failed but did not say why".to_string());
258        return Err(ExecError::Failed {
259            id: implementation.id.to_string(),
260            message: reported,
261        });
262    }
263
264    let Some(json) = response.value else {
265        return Err(ExecError::Protocol {
266            id: implementation.id.to_string(),
267            detail: "it said it worked but sent nothing back".into(),
268        });
269    };
270
271    // Read against the type the signature promises, so that what comes back is
272    // interpreted the same way as anything else entering the system.
273    ws.read(&json, expected)
274        .map_err(|source| ExecError::Protocol {
275            id: implementation.id.to_string(),
276            detail: format!(
277                "what it sent back is not a `{}`: {source}",
278                describe(expected)
279            ),
280        })
281}
282
283fn describe(ty: &Type) -> String {
284    unitype_core::canon::canonical_string(ty)
285}
286
287/// The end of what a failing child said, which is where the reason usually is.
288fn tail(stderr: &[u8]) -> String {
289    let text = String::from_utf8_lossy(stderr);
290    let trimmed = text.trim();
291    if trimmed.is_empty() {
292        return String::new();
293    }
294    let kept = if trimmed.len() > STDERR_KEPT {
295        &trimmed[trimmed.len() - STDERR_KEPT..]
296    } else {
297        trimmed
298    };
299    format!("; it said: {kept}")
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use std::collections::BTreeMap;
306    use unitype_core::check::check_workspace;
307    use unitype_core::{BigO, Ident, ImplProfile, Workspace};
308
309    fn ws() -> CheckedWorkspace {
310        check_workspace(
311            Workspace::from_json(
312                r#"{"universes":[{"name":"demo","functions":[
313                    {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#,
314            )
315            .expect("reads"),
316        )
317        .expect("checks")
318    }
319
320    /// An environment that runs a shell snippet, so these tests need nothing
321    /// installed beyond a shell.
322    fn shell(script: &str, timeout_ms: u64) -> Environment {
323        Environment {
324            id: Ident::new("shell").unwrap(),
325            language: Ident::new("sh").unwrap(),
326            doc: None,
327            reach: Reach::Subprocess {
328                command: "/bin/sh".into(),
329                args: vec!["-c".into(), script.into()],
330                cwd: None,
331                env: BTreeMap::new(),
332                timeout_ms,
333                persistent: false,
334            },
335            meta: unitype_core::Metadata::default(),
336        }
337    }
338
339    fn implementation() -> Implementation {
340        Implementation::new(
341            "sort.shell",
342            "demo::sort".parse().unwrap(),
343            Ident::new("shell").unwrap(),
344            "bubble_sort",
345            ImplProfile::new(BigO::ON2, BigO::O1),
346        )
347    }
348
349    #[test]
350    fn an_absent_answer_is_an_answer_and_no_answer_is_not() {
351        let ws = ws();
352        let maybe = Type::I64.optional();
353        let absent = read_answer(
354            &ws,
355            &implementation(),
356            r#"{"ok":true,"value":null}"#,
357            &maybe,
358        )
359        .expect("null is what a proposition returning `T?` answers");
360        assert_eq!(absent, Value::Null);
361
362        let none = read_answer(&ws, &implementation(), r#"{"ok":true}"#, &maybe)
363            .expect_err("no value at all is a broken exchange");
364        assert!(none.to_string().contains("sent nothing back"), "{none}");
365    }
366
367    /// Generous on purpose: these tests are about the exchange, not about how
368    /// busy the machine is. Only the test that is *about* giving up sets a
369    /// short limit.
370    const PATIENT: u64 = 30_000;
371
372    async fn run(script: &str) -> Result<Value, ExecError> {
373        run_with(script, PATIENT).await
374    }
375
376    async fn run_with(script: &str, timeout_ms: u64) -> Result<Value, ExecError> {
377        let ws = ws();
378        invoke(
379            &ws,
380            &shell(script, timeout_ms),
381            &implementation(),
382            vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
383            &[Type::I64.list()],
384            &Type::I64.list(),
385        )
386        .await
387    }
388
389    /// Short calls started alongside a child that sticks around.
390    ///
391    /// This is the arrangement that used to hang. Starting a process means
392    /// making pipes and then forking, and where those cannot be one atomic
393    /// step, a fork landing between them inherits a pipe it has no business
394    /// holding. The parent closes its own end to say the request is over, and
395    /// the child keeps waiting, because a stranger is still holding the other
396    /// copy open.
397    ///
398    /// Both halves matter, which is why the test has both. `cat` is the
399    /// victim: a child reading to end of input hangs where one reading a line
400    /// would not notice. The sleeper is the thief, and has to outlive the
401    /// patience of the calls it is stealing from — with only short-lived
402    /// children around, an inherited descriptor is let go again within
403    /// milliseconds and nobody waits long enough to care.
404    ///
405    /// It is a race, so a green run is weak evidence on its own. The value is
406    /// in running it forever after.
407    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
408    async fn a_long_lived_child_does_not_hold_another_call_s_input_open() {
409        // Long enough to outlast the patience below, so a stolen descriptor
410        // shows up as a call that never finishes rather than one that is
411        // merely slow.
412        let thief = tokio::spawn(run_with(
413            r#"cat > /dev/null; sleep 2; echo '{"ok":true,"value":[]}'"#,
414            30_000,
415        ));
416
417        let victims = (0..48).map(|n| async move {
418            run_with(
419                &format!(r#"cat > /dev/null; echo '{{"ok":true,"value":[{n}]}}'"#),
420                900,
421            )
422            .await
423        });
424
425        for (n, got) in futures_join(victims).await.into_iter().enumerate() {
426            assert_eq!(
427                got.unwrap_or_else(|e| panic!("call {n} should have answered: {e}")),
428                Value::List(vec![Value::Int(n as i64)]),
429                "each call got its own answer, not somebody else's"
430            );
431        }
432        thief.await.expect("it did not panic").expect("it answers");
433    }
434
435    /// Runs everything given to it at once and collects the results in order.
436    ///
437    /// Hand-rolled because this crate does not depend on `futures`, and one
438    /// join is not worth one.
439    async fn futures_join<F>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output>
440    where
441        F: std::future::Future + Send + 'static,
442        F::Output: Send + 'static,
443    {
444        let handles: Vec<_> = futures.into_iter().map(tokio::spawn).collect();
445        let mut out = Vec::with_capacity(handles.len());
446        for handle in handles {
447            out.push(handle.await.expect("the call did not panic"));
448        }
449        out
450    }
451
452    #[tokio::test]
453    async fn a_program_that_answers_is_believed() {
454        let out = run(r#"cat > /dev/null; echo '{"ok":true,"value":[1,3]}'"#)
455            .await
456            .expect("answers");
457        assert_eq!(out, Value::List(vec![Value::Int(1), Value::Int(3)]));
458    }
459
460    #[tokio::test]
461    async fn the_request_reaches_the_program_intact() {
462        // The child echoes back what it was sent, as a string, and we check the
463        // parts that matter are in it.
464        let ws = ws();
465        let out = invoke(
466            &ws,
467            &shell(
468                r#"body=$(cat); printf '{"ok":true,"value":%s}' "$(printf '%s' "$body" | sed 's/\\/\\\\/g; s/"/\\"/g; s/^/"/; s/$/"/')""#,
469                PATIENT,
470            ),
471            &implementation(),
472            vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
473            &[Type::I64.list()],
474            &Type::String,
475        )
476        .await
477        .expect("answers");
478
479        let Value::Str(seen) = out else {
480            panic!("expected the request back as a string, got {out:?}");
481        };
482        assert!(seen.contains(r#""unitype":"1""#), "{seen}");
483        assert!(seen.contains(r#""signature":"demo::sort""#), "{seen}");
484        assert!(seen.contains(r#""entry":"bubble_sort""#), "{seen}");
485        assert!(
486            seen.contains("[3,1]"),
487            "the arguments should be there: {seen}"
488        );
489    }
490
491    #[test]
492    fn an_argument_is_sent_written_against_its_type() {
493        // A child reads JSON the way its own language does, and every language
494        // reads a pair as an array. Without the type, the pair would have to
495        // say it is one.
496        let ws = ws();
497        let pair = Value::Tuple(vec![Value::Int(1), Value::Str("a".into())]);
498        let pair_type = Type::Tuple {
499            items: vec![Type::I64, Type::String],
500        };
501        let line = request_line(
502            &ws,
503            &implementation(),
504            std::slice::from_ref(&pair),
505            &[pair_type],
506        )
507        .expect("encodes");
508        let sent: serde_json::Value = serde_json::from_slice(&line).expect("JSON");
509        assert_eq!(sent["args"], serde_json::json!([[1, "a"]]));
510
511        let untyped = request_line(&ws, &implementation(), &[pair], &[]).expect("encodes");
512        let sent: serde_json::Value = serde_json::from_slice(&untyped).expect("JSON");
513        assert_eq!(sent["args"], serde_json::json!([{"$tuple": [1, "a"]}]));
514    }
515
516    #[tokio::test]
517    async fn a_program_that_is_not_there_is_an_environment_problem() {
518        let ws = ws();
519        let err = invoke(
520            &ws,
521            &Environment::subprocess("nope", "sh", "unitype_no_such_program", &[]),
522            &implementation(),
523            vec![Value::List(vec![])],
524            &[Type::I64.list()],
525            &Type::I64.list(),
526        )
527        .await
528        .unwrap_err();
529
530        assert!(
531            err.is_environmental(),
532            "nothing is wrong with the proof; the machine is missing it: {err}"
533        );
534    }
535
536    #[tokio::test]
537    async fn a_program_reporting_its_own_failure_is_quoted() {
538        let err = run(r#"cat > /dev/null; echo '{"ok":false,"error":{"code":"bad","message":"list was too long"}}'"#)
539            .await
540            .unwrap_err();
541        assert!(err.to_string().contains("list was too long"), "{err}");
542        assert!(
543            !err.is_environmental(),
544            "the program worked; what it was asked to do did not"
545        );
546    }
547
548    #[tokio::test]
549    async fn a_program_that_crashes_has_its_last_words_kept() {
550        let err = run(r#"cat > /dev/null; echo "something went badly" >&2; exit 3"#)
551            .await
552            .unwrap_err();
553        let message = err.to_string();
554        assert!(message.contains("exited with 3"), "{message}");
555        assert!(message.contains("something went badly"), "{message}");
556    }
557
558    #[tokio::test]
559    async fn a_program_that_talks_nonsense_is_a_protocol_failure() {
560        let err = run(r#"cat > /dev/null; echo 'not json at all'"#)
561            .await
562            .unwrap_err();
563        assert!(matches!(err, ExecError::Protocol { .. }), "{err}");
564        assert!(
565            !err.is_environmental(),
566            "a program that cannot speak the protocol will not learn by being asked again"
567        );
568    }
569
570    #[tokio::test]
571    async fn a_program_that_answers_with_the_wrong_shape_is_caught_here_too() {
572        let err = run(r#"cat > /dev/null; echo '{"ok":true,"value":"not a list"}'"#)
573            .await
574            .unwrap_err();
575        assert!(err.to_string().contains("is not a"), "{err}");
576    }
577
578    #[tokio::test]
579    async fn a_program_that_never_answers_is_given_up_on() {
580        let err = run_with(r#"cat > /dev/null; sleep 30"#, 150)
581            .await
582            .unwrap_err();
583        assert!(matches!(err, ExecError::Timeout { .. }), "{err}");
584        assert!(
585            err.is_environmental(),
586            "a hung machine is worth trying around"
587        );
588    }
589
590    #[tokio::test]
591    async fn closing_the_input_is_what_tells_the_program_to_get_on_with_it() {
592        // This child reads to the end before answering. If the parent did not
593        // close its writing end, it would wait for ever.
594        let out = run(r#"cat > /dev/null && echo '{"ok":true,"value":[7]}'"#)
595            .await
596            .expect("answers");
597        assert_eq!(out, Value::List(vec![Value::Int(7)]));
598    }
599}