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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::{sync::Arc, time::Duration};

use anyhow::{Context, Result};
use isola::{
    host::{BoxError, LogContext, LogLevel, NoopOutputSink, OutputSink},
    sandbox::{
        Arg, CallOutput, DirPerms, Error as IsolaError, FilePerms, Sandbox, SandboxOptions, args,
    },
};
use parking_lot::Mutex;
use tempfile::tempdir;

use super::common::{TestHost, build_module, build_module_with_max_memory};

const CAP_NEIGHBORHOOD_BYTES: usize = 1024 * 1024;
const MEMORY_CAP_BYTES: usize = 64 * 1024 * 1024;
const LARGE_STDOUT_BYTES: usize = 256 * 1024;

struct CollectLogsSink {
    logs: Arc<Mutex<Vec<(String, String)>>>,
}

impl CollectLogsSink {
    const fn new(logs: Arc<Mutex<Vec<(String, String)>>>) -> Self {
        Self { logs }
    }
}

#[async_trait::async_trait]
impl OutputSink for CollectLogsSink {
    async fn on_item(&self, _value: isola::value::Value) -> std::result::Result<(), BoxError> {
        Ok(())
    }

    async fn on_complete(
        &self,
        _value: Option<isola::value::Value>,
    ) -> std::result::Result<(), BoxError> {
        Ok(())
    }

    async fn on_log(
        &self,
        level: LogLevel,
        _log_context: LogContext<'_>,
        message: &str,
    ) -> std::result::Result<(), BoxError> {
        self.logs
            .lock()
            .push((level.as_str().to_string(), message.to_string()));
        Ok(())
    }
}

async fn call_with_timeout<I>(
    sandbox: &mut Sandbox<TestHost>,
    function: &str,
    args: I,
    timeout: Duration,
) -> std::result::Result<CallOutput, IsolaError>
where
    I: IntoIterator<Item = Arg>,
{
    tokio::time::timeout(timeout, sandbox.call(function, args))
        .await
        .unwrap_or_else(|_| {
            Err(IsolaError::Other(
                anyhow::anyhow!("sandbox call timed out after {}ms", timeout.as_millis()).into(),
            ))
        })
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_eval_and_call_roundtrip() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main():\n\tprint('trace-print')\n\treturn 42",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate script")?;

    let output = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
        .await
        .context("failed to call function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");
    let value: i64 = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode end output")?;
    assert_eq!(value, 42);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_call_with_sink_does_not_retain_refs() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script("def main():\n\treturn 42", NoopOutputSink::shared())
        .await
        .context("failed to evaluate script")?;

    let sink: Arc<dyn OutputSink> = Arc::new(NoopOutputSink);
    let initial = Arc::strong_count(&sink);
    assert_eq!(initial, 1, "unexpected initial sink refcount");

    sandbox
        .call_with_sink("main", [], Arc::clone(&sink))
        .await
        .context("failed to call function with sink")?;
    assert_eq!(
        Arc::strong_count(&sink),
        initial,
        "sink refcount changed after call_with_sink",
    );

    sandbox
        .call_with_sink("main", [], Arc::clone(&sink))
        .await
        .context("failed to call function with sink on second call")?;
    assert_eq!(
        Arc::strong_count(&sink),
        initial,
        "sink refcount changed after repeated call_with_sink",
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_streaming_output() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main():\n\tfor i in range(3):\n\t\tyield i",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate streaming script")?;

    let output = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
        .await
        .context("failed to call streaming function")?;

    assert_eq!(output.items.len(), 3, "expected three partial outputs");
    let mut values = Vec::with_capacity(output.items.len());
    for item in &output.items {
        values.push(
            item.to_serde::<i64>()
                .context("failed to decode partial output")?,
        );
    }
    assert_eq!(values, vec![0, 1, 2]);

    assert!(output.result.is_none(), "expected null end output");

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_eval_script_logs_to_sink() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let logs = Arc::new(Mutex::new(Vec::new()));
    let sink = CollectLogsSink::new(logs.clone());
    match tokio::time::timeout(
        Duration::from_secs(2),
        sandbox.eval_script(
            "print('eval-stdout')\nimport sandbox.logging\nsandbox.logging.info('eval-log')",
            Arc::new(sink),
        ),
    )
    .await
    {
        Ok(result) => result.context("failed to evaluate script")?,
        Err(_) => {
            return Err(anyhow::anyhow!("sandbox eval timed out after {}ms", 2_000));
        }
    }
    {
        let logs = logs.lock();

        assert!(
            logs.iter()
                .any(|(context, message)| context == "stdout" && message.contains("eval-stdout")),
            "expected eval stdout log in sink, logs: {:?}",
            *logs
        );
        assert!(
            logs.iter()
                .any(|(context, message)| context == "info" && message.contains("eval-log")),
            "expected eval logging event in sink, logs: {:?}",
            *logs
        );
        drop(logs);
    }

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_large_stdout_output_is_not_truncated() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            format!(
                "def main():\n\
                 \tpayload = 'x' * {LARGE_STDOUT_BYTES}\n\
                 \tprint(payload, end='')\n\
                 \treturn len(payload)"
            ),
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate large stdout script")?;

    let output = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(10))
        .await
        .context("failed to call large stdout function")?;

    let emitted_len: usize = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode end output")?;
    assert_eq!(emitted_len, LARGE_STDOUT_BYTES);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_argument_cbor_path() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main(i, s):\n\treturn (i + 1, s.upper())",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate argument script")?;

    let args = args![41_i64, s = "hello"]?;
    let output = call_with_timeout(&mut sandbox, "main", args, Duration::from_secs(2))
        .await
        .context("failed to call argument function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");
    let value: (i64, String) = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode argument result")?;
    assert_eq!(value, (42, "HELLO".to_string()));
    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_reinstantiate_smoke() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    for expected in [7_i64, 11_i64] {
        let mut sandbox = module
            .instantiate(TestHost::default(), SandboxOptions::default())
            .await
            .context("failed to instantiate sandbox")?;

        sandbox
            .eval_script(
                format!("def main():\n\treturn {expected}"),
                NoopOutputSink::shared(),
            )
            .await
            .context("failed to evaluate script")?;

        let output = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
            .await
            .context("failed to call function")?;
        let value: i64 = output
            .result
            .as_ref()
            .context("expected exactly one end output")?
            .to_serde()
            .context("failed to decode roundtrip output")?;
        assert_eq!(value, expected);
    }

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_guest_exception_surface() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main():\n\traise RuntimeError(\"boom\")",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate exception script")?;

    let err = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
        .await
        .expect_err("expected exception from guest function");
    let IsolaError::UserCode { message } = err else {
        panic!("expected guest error, got {err:?}");
    };
    assert!(
        message.contains("boom"),
        "unexpected error message: {message}",
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_state_persists_within_sandbox() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "counter = 0\n\
             def main():\n\
             \tglobal counter\n\
             \tcounter += 1\n\
             \treturn counter",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate stateful script")?;

    let first = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
        .await
        .context("failed first stateful call")?;
    let second = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(2))
        .await
        .context("failed second stateful call")?;

    let first_v: i64 = first
        .result
        .as_ref()
        .context("expected exactly one first end output")?
        .to_serde()
        .context("failed to decode first value")?;
    let second_v: i64 = second
        .result
        .as_ref()
        .context("expected exactly one second end output")?
        .to_serde()
        .context("failed to decode second value")?;
    assert_eq!(first_v, 1);
    assert_eq!(second_v, 2);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_call_timeout() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main():\n\twhile True:\n\t\tpass",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate timeout script")?;

    let err = call_with_timeout(&mut sandbox, "main", [], Duration::from_millis(1))
        .await
        .expect_err("expected timeout while executing guest function");
    let IsolaError::Other(cause) = err else {
        panic!("expected runtime timeout error, got {err:?}");
    };
    let message = cause.to_string().to_ascii_lowercase();
    assert!(
        message.contains("timeout") || message.contains("timed out"),
        "unexpected timeout error message: {cause}"
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_memory_limiter_is_enforced() -> Result<()> {
    let Some(module) = build_module_with_max_memory(MEMORY_CAP_BYTES).await? else {
        return Ok(());
    };
    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main():\n\
             \tchunks = []\n\
             \tfor _ in range(1024):\n\
             \t\tchunks.append(bytes(1024 * 1024))\n\
             \treturn len(chunks)",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate memory pressure script")?;

    let memory_before = sandbox.memory_usage();
    let err = call_with_timeout(&mut sandbox, "main", [], Duration::from_secs(10))
        .await
        .expect_err("expected memory limit error while allocating guest memory");
    let memory_after = sandbox.memory_usage();

    let message = match err {
        IsolaError::UserCode { message } => message.to_ascii_lowercase(),
        IsolaError::Wasm(cause) => cause.to_string().to_ascii_lowercase(),
        IsolaError::Io(cause) => cause.to_string().to_ascii_lowercase(),
        IsolaError::Other(cause) => cause.to_string().to_ascii_lowercase(),
    };
    assert!(
        message.contains("memory")
            || message.contains("grow")
            || message.contains("alloc")
            || message.contains("oom"),
        "unexpected memory limit error message: {message}",
    );

    assert!(
        memory_after >= memory_before,
        "expected memory usage to grow during allocation, before={memory_before}, after={memory_after}",
    );
    assert!(
        memory_after <= MEMORY_CAP_BYTES,
        "memory usage exceeded configured cap: used={memory_after}, cap={MEMORY_CAP_BYTES}",
    );
    assert!(
        memory_after >= MEMORY_CAP_BYTES.saturating_sub(CAP_NEIGHBORHOOD_BYTES),
        "expected usage to reach memory cap neighborhood, used={memory_after}, cap={MEMORY_CAP_BYTES}",
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_python_writable_directory_mapping_filesystem_roundtrip() -> Result<()> {
    let temp = tempdir().context("failed to create temp directory")?;
    let mapped_dir = temp.path().to_path_buf();

    let Some(module) = build_module().await? else {
        return Ok(());
    };
    let mut options = SandboxOptions::default();
    options.mount(
        &mapped_dir,
        "/fs",
        DirPerms::READ | DirPerms::MUTATE,
        FilePerms::READ | FilePerms::WRITE,
    );
    let mut sandbox = module
        .instantiate(TestHost::default(), options)
        .await
        .context("failed to instantiate sandbox")?;

    sandbox
        .eval_script(
            "def main(text):\n\
             \tpath = '/fs/output.txt'\n\
             \twith open(path, 'w', encoding='utf-8') as fh:\n\
             \t\tfh.write(text)\n\
             \twith open(path, 'r', encoding='utf-8') as fh:\n\
             \t\treturn fh.read()",
            NoopOutputSink::shared(),
        )
        .await
        .context("failed to evaluate filesystem script")?;

    let args = args!["hello-fs"]?;
    let output = call_with_timeout(&mut sandbox, "main", args, Duration::from_secs(2))
        .await
        .context("failed to call filesystem function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");
    let result: String = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode filesystem result")?;
    assert_eq!(result, "hello-fs");

    let host_file = mapped_dir.join("output.txt");
    let host_contents = std::fs::read_to_string(&host_file).with_context(|| {
        format!(
            "failed to read mapped host file after guest write: {}",
            host_file.display()
        )
    })?;
    assert_eq!(host_contents, "hello-fs");

    Ok(())
}