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