diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
//! A subprocess kernel that can misbehave without importing a language runtime.

use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;

use jupyter_protocol::{
    ConnectionInfo, ExecuteReply, InterruptReply, JupyterMessage, JupyterMessageContent,
    KernelInfoReply, ReplyStatus, ShutdownReply, Status,
};
use jupyter_zmq_client::{
    KernelIoPubConnection, KernelShellConnection, KernelStdinConnection,
    create_kernel_control_connection, create_kernel_heartbeat_connection,
    create_kernel_iopub_connection, create_kernel_shell_connection, create_kernel_stdin_connection,
};
use serde_json::json;

fn event(path: &Path, text: &str) {
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path.with_file_name("events"))
        .unwrap();
    writeln!(file, "{text}").unwrap();
}

#[test]
fn kernel_process() {
    let Ok(mode) = std::env::var("DIPLODOCUS_KERNEL_FIXTURE") else {
        return;
    };
    let observation = std::env::var_os("DIPLODOCUS_FIXTURE_OBSERVATIONS").unwrap();
    let observation = Path::new(&observation);
    let connection = std::env::args()
        .find_map(|arg| arg.strip_prefix("--skip=").map(str::to_owned))
        .unwrap();
    let connection_path = Path::new(&connection);
    let mut info: ConnectionInfo =
        serde_json::from_slice(&std::fs::read(connection_path).unwrap()).unwrap();
    let record = json!({
        "pid": std::process::id(), "connection_file": connection,
        "working_directory": std::env::current_dir().unwrap(),
        "file_mode": std::fs::metadata(connection_path).unwrap().permissions().mode() & 0o777,
        "directory_mode": std::fs::metadata(connection_path.parent().unwrap()).unwrap().permissions().mode() & 0o777,
        "literal": std::env::var("DIPLODOCUS_LITERAL").unwrap(), "connection": info
    });
    let temporary = observation.with_extension("tmp");
    std::fs::write(&temporary, serde_json::to_vec(&record).unwrap()).unwrap();
    std::fs::rename(temporary, observation).unwrap();
    if mode == "exit" {
        return;
    }
    if mode == "wrong-key" {
        info.key = "wrong-key".into();
    }
    tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
        let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()).unwrap();
        let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
        let mut descendant = if mode == "descendant" {
            let child = tokio::process::Command::new(std::env::current_exe().unwrap())
                .args(["--exact", "execution::jupyter::tests::fixture::descendant_process"])
                .env("DIPLODOCUS_DESCENDANT", "1").spawn().unwrap();
            event(observation, &format!("descendant:{}", child.id().unwrap()));
            Some(child)
        } else { None };
        let mut shell = create_kernel_shell_connection(&info, "fixture").await.unwrap();
        let mut iopub = create_kernel_iopub_connection(&info, "fixture").await.unwrap();
        let mut control = create_kernel_control_connection(&info, "fixture").await.unwrap();
        let mut stdin = create_kernel_stdin_connection(&info, "fixture").await.unwrap();
        let mut heartbeat = create_kernel_heartbeat_connection(&info).await.unwrap();
        let mut probes = 0;
        let mut executions = 0;
        let mut active_request = None;
        let mut activity = tokio::time::interval(std::time::Duration::from_millis(10));
        loop {
            tokio::select! {
                _ = activity.tick(), if mode.starts_with("execute-chatty-") && active_request.is_some() => {
                    let request = active_request.as_ref().unwrap();
                    iopub.send(jupyter_protocol::StreamContent::stdout("still running\n").as_child_of(request)).await.unwrap();
                    event(observation, "activity");
                }
                message = shell.read() => {
                    let Ok(message) = message else {
                        if mode == "wrong-key" {
                            // An independently signed broadcast exposes the authentication mismatch.
                            iopub.send(Status::idle().into()).await.unwrap();
                            continue;
                        }
                        break;
                    };
                    if matches!(message.content, JupyterMessageContent::ExecuteRequest(_)) && mode.starts_with("execute-") {
                        executions += 1;
                        active_request = Some(message.clone());
                        if !execute(&mode, observation, executions, &message, &mut shell, &mut iopub, &mut stdin).await {
                            break;
                        }
                        continue;
                    }
                    if !matches!(message.content, JupyterMessageContent::KernelInfoRequest(_)) {
                        event(observation, "execute");
                        panic!("Startup must never submit code");
                    }
                    event(observation, "info");
                    probes += 1;
                    if mode == "stdin" {
                        stdin.send(jupyter_protocol::InputRequest { prompt: "unexpected input".into(), password: false }.as_child_of(&message)).await.unwrap();
                        continue;
                    }
                    let mut reply: KernelInfoReply = serde_json::from_value(json!({
                        "status": "ok", "protocol_version": "5.3", "implementation": "fixture",
                        "implementation_version": "1.0", "language_info": {"name": "Python3", "version": "3.0"},
                        "banner": "", "help_links": []
                    })).unwrap();
                    if let Ok(version) = std::fs::read_to_string(observation.with_file_name("runtime-version")) {
                        reply.language_info.version = version;
                    }
                    match mode.as_str() {
                        "wrong-major" => reply.protocol_version = "6.0".into(),
                        "wrong-language" => reply.language_info.name = "R".into(),
                        "empty-version" => reply.implementation_version.clear(),
                        "error-info" => reply.status = ReplyStatus::Error,
                        _ => {}
                    }
                    // Unrelated replies must not satisfy the startup handshake.
                    let mut unrelated = reply.clone().as_child_of(&message);
                    unrelated.parent_header = None;
                    shell.send(unrelated).await.unwrap();
                    if mode == "idle-first" {
                        iopub.send(Status::idle().as_child_of(&message)).await.unwrap();
                        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                    }
                    shell.send(reply.as_child_of(&message)).await.unwrap();
                    if mode != "no-iopub" && (mode != "delayed-iopub" || probes > 1) {
                        iopub.send(Status::busy().as_child_of(&message)).await.unwrap();
                        iopub.send(Status::idle().as_child_of(&message)).await.unwrap();
                    }
                }
                message = control.read() => {
                    let Ok(message) = message else { continue; };
                    match message.content {
                        JupyterMessageContent::InterruptRequest(_) => {
                            event(observation, "interrupt");
                            control.send(InterruptReply { status: ReplyStatus::Ok, error: None }.as_child_of(&message)).await.unwrap();
                            iopub.send(Status::idle().as_child_of(&message)).await.unwrap();
                        }
                        JupyterMessageContent::ShutdownRequest(_) => {
                            event(observation, "shutdown");
                            if let Ok(change) = std::fs::read_to_string(observation.with_file_name("mutate-include-on-shutdown")) {
                                let partial = observation.with_file_name("parts").join("cells.qmd");
                                match change.as_str() {
                                    "edit" => std::fs::write(partial, "Changed during cleanup.\n").unwrap(),
                                    "delete" => std::fs::remove_file(partial).unwrap(),
                                    "retarget" => {
                                        std::fs::remove_file(&partial).unwrap();
                                        std::os::unix::fs::symlink("replacement.qmd", partial).unwrap();
                                    }
                                    _ => panic!("unknown include mutation"),
                                }
                            }
                            if observation.with_file_name("mutate-on-shutdown").exists() {
                                let page = observation.with_file_name("guide").join("example.qmd");
                                let mut file = std::fs::OpenOptions::new().append(true).open(page).unwrap();
                                writeln!(file, "Changed during cleanup.").unwrap();
                            }
                            if matches!(mode.as_str(), "ignore-shutdown" | "ignore-term" | "execute-ignore-shutdown") { continue; }
                            if mode == "execute-slow-shutdown" {
                                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                            }
                            control.send(ShutdownReply { status: ReplyStatus::Ok, restart: false, error: None }.as_child_of(&message)).await.unwrap();
                            if let Some(child) = descendant.as_mut() { child.wait().await.unwrap(); }
                            break;
                        }
                        _ => panic!("unexpected control request"),
                    }
                }
                result = heartbeat.single_heartbeat() => { result.unwrap(); }
                _ = sigint.recv() => {
                    event(observation, "signal-interrupt");
                    iopub.send(Status::idle().into()).await.unwrap();
                }
                _ = sigterm.recv() => {
                    event(observation, "terminate");
                    if mode != "ignore-term" { break; }
                }
            }
        }
    });
}

async fn execute(
    mode: &str,
    observation: &Path,
    ordinal: usize,
    message: &JupyterMessage,
    shell: &mut KernelShellConnection,
    iopub: &mut KernelIoPubConnection,
    stdin: &mut KernelStdinConnection,
) -> bool {
    let JupyterMessageContent::ExecuteRequest(request) = &message.content else {
        unreachable!()
    };
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(observation.with_file_name("requests"))
        .unwrap();
    writeln!(file, "{}", serde_json::to_string(request).unwrap()).unwrap();
    if observation.with_file_name("fail-execution").exists() {
        return false;
    }
    assert_eq!(
        request.code.trim() == "define",
        ordinal == 1,
        "State must belong to one page session"
    );
    event(observation, "execute");
    if mode == "execute-exit" {
        return false;
    }
    iopub
        .send(Status::busy().as_child_of(message))
        .await
        .unwrap();
    if mode == "execute-stdin" {
        stdin
            .send(
                jupyter_protocol::InputRequest {
                    prompt: "unexpected input".into(),
                    password: false,
                }
                .as_child_of(message),
            )
            .await
            .unwrap();
        return true;
    }
    if ordinal == 2 && matches!(mode, "execute-ledger-timeout" | "execute-image-then-hang") {
        iopub
            .send(jupyter_protocol::StreamContent::stdout("unrelated").into())
            .await
            .unwrap();
        return true;
    }
    if matches!(mode, "execute-no-terminal" | "execute-chatty-no-terminal") {
        return true;
    }
    if mode == "execute-streams" {
        for stream in [
            jupyter_protocol::StreamContent::stdout("# ordinary stdout\n"),
            jupyter_protocol::StreamContent::stderr("stderr\n"),
        ] {
            iopub.send(stream.as_child_of(message)).await.unwrap();
        }
    }
    if mode == "execute-unsupported-mime" {
        for data in [
            json!({"application/javascript": "rejected payload"}),
            json!({"application/javascript": "rejected payload", "text/plain": "safe fallback"}),
        ] {
            let display: jupyter_protocol::DisplayData =
                serde_json::from_value(json!({"data": data, "metadata": {}})).unwrap();
            iopub.send(display.as_child_of(message)).await.unwrap();
        }
    }
    if mode == "execute-markdown" {
        for stream in [
            jupyter_protocol::StreamContent::stdout("# Gener"),
            jupyter_protocol::StreamContent::stdout("ated\n"),
            jupyter_protocol::StreamContent::stderr("<stderr>&literal\n"),
        ] {
            iopub.send(stream.as_child_of(message)).await.unwrap();
        }
        let display: jupyter_protocol::DisplayData = serde_json::from_value(json!({
            "data": {
                "text/markdown": "```{python}\nraise RuntimeError('inert')\n```\n",
                "text/plain": "literal fallback"
            },
            "metadata": {}
        }))
        .unwrap();
        iopub.send(display.as_child_of(message)).await.unwrap();
    }
    if matches!(
        mode,
        "execute-images"
            | "execute-source-change"
            | "execute-environment-change"
            | "execute-image-then-hang"
    ) {
        let display: jupyter_protocol::DisplayData = serde_json::from_value(json!({
            "data": {"image/svg+xml": "<svg xmlns='http://www.w3.org/2000/svg'><rect width='10' height='10'/></svg>", "text/plain": "a figure"},
            "metadata": {"filename": "../../ignored.svg"}
        })).unwrap();
        iopub.send(display.as_child_of(message)).await.unwrap();
    }
    if mode.starts_with("execute-ledger") {
        for data in [
            json!({"text/html":"<script>unsafe()</script>", "text/plain":"fallback"}),
            json!({"text/markdown":"<div>inert</div>"}),
        ] {
            iopub
                .send(jupyter_protocol::StreamContent::stdout("unrelated").into())
                .await
                .unwrap();
            let display: jupyter_protocol::DisplayData =
                serde_json::from_value(json!({"data":data,"metadata":{}})).unwrap();
            iopub.send(display.as_child_of(message)).await.unwrap();
        }
        if mode == "execute-ledger-fatal" {
            let display: jupyter_protocol::DisplayData = serde_json::from_value(json!({
                "data":{"text/markdown":"![missing](absent.png)"},"metadata":{}
            }))
            .unwrap();
            iopub.send(display.as_child_of(message)).await.unwrap();
        }
        iopub
            .send(jupyter_protocol::StreamContent::stdout("unrelated tail").into())
            .await
            .unwrap();
    }
    if ordinal == 2 && mode == "execute-source-change" {
        std::fs::write("example.qmd", "Changed while the kernel was running.\n").unwrap();
    }
    if ordinal == 2 && mode == "execute-environment-change" {
        std::fs::write(observation.with_file_name("environment.txt"), "changed").unwrap();
    }
    if matches!(
        mode,
        "execute-generated-html-image" | "execute-generated-markdown-image"
    ) {
        let mut data = json!({
            "image/svg+xml": "<svg xmlns='http://www.w3.org/2000/svg'><rect width='10' height='10'/></svg>",
            "text/plain": "a safe fallback"
        });
        if mode == "execute-generated-html-image" {
            data["text/html"] = json!("<p><img src='missing.png'></p>");
        } else {
            data["text/markdown"] = json!("> ![nested](missing.png)\n");
        }
        let display: jupyter_protocol::DisplayData =
            serde_json::from_value(json!({"data": data, "metadata": {}})).unwrap();
        iopub.send(display.as_child_of(message)).await.unwrap();
    }
    let error = jupyter_protocol::ReplyError {
        ename: "FixtureError".into(),
        evalue: "expected".into(),
        traceback: Vec::new(),
    };
    let mut reply = ExecuteReply::default();
    if ordinal == 1 {
        match mode {
            "execute-error" | "execute-both-errors" => {
                reply.status = ReplyStatus::Error;
                reply.error = Some(Box::new(error.clone()));
            }
            "execute-iopub-error" => {
                iopub
                    .send(
                        jupyter_protocol::ErrorOutput {
                            ename: error.ename,
                            evalue: error.evalue,
                            traceback: error.traceback,
                        }
                        .as_child_of(message),
                    )
                    .await
                    .unwrap();
            }
            "execute-aborted" => reply.status = ReplyStatus::Aborted,
            "execute-malformed-reply" => reply.status = ReplyStatus::Error,
            _ => {}
        }
        if mode == "execute-both-errors" {
            iopub
                .send(
                    jupyter_protocol::ErrorOutput {
                        ename: "FixtureError".into(),
                        evalue: "expected".into(),
                        traceback: Vec::new(),
                    }
                    .as_child_of(message),
                )
                .await
                .unwrap();
        }
    }
    if mode == "execute-wrong-reply" {
        shell
            .send(Status::idle().as_child_of(message))
            .await
            .unwrap();
        return true;
    }
    // A terminal event for another request must never advance this page.
    let mut unrelated = message.clone();
    unrelated.header.msg_id = "unrelated-request".into();
    if !mode.starts_with("execute-ledger") && mode != "execute-unsupported-mime" {
        shell
            .send(reply.clone().as_child_of(&unrelated))
            .await
            .unwrap();
        iopub
            .send(Status::idle().as_child_of(&unrelated))
            .await
            .unwrap();
    }
    let idle_first = matches!(
        mode,
        "execute-idle-first" | "execute-no-reply" | "execute-chatty-no-reply"
    );
    if idle_first {
        iopub
            .send(Status::idle().as_child_of(message))
            .await
            .unwrap();
    } else {
        shell
            .send(reply.clone().as_child_of(message))
            .await
            .unwrap();
    }
    let _ = tokio::time::timeout(std::time::Duration::from_millis(60), async {
        loop {
            let next = shell.read().await.unwrap();
            // Startup may have queued another metadata probe before readiness.
            assert!(
                matches!(next.content, JupyterMessageContent::KernelInfoRequest(_)),
                "The next cell arrived before both terminal events"
            );
        }
    })
    .await;
    if matches!(
        mode,
        "execute-no-idle"
            | "execute-no-reply"
            | "execute-chatty-no-idle"
            | "execute-chatty-no-reply"
    ) {
        return true;
    }
    if idle_first {
        shell.send(reply.as_child_of(message)).await.unwrap();
    } else {
        iopub
            .send(Status::idle().as_child_of(message))
            .await
            .unwrap();
    }
    true
}

#[test]
fn descendant_process() {
    if std::env::var_os("DIPLODOCUS_DESCENDANT").is_none() {
        return;
    }
    loop {
        std::thread::park();
    }
}