eryx 0.4.7

A Python sandbox with async callbacks powered by WebAssembly
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
//! Integration tests for Python error handling scenarios.
//!
//! These tests verify that Python errors (syntax errors, runtime errors, etc.)
//! are properly propagated and reported through the SessionExecutor.
//!
//! Note: Tests for callback error handling require setting up callback channels
//! and handlers, which is handled by the higher-level Sandbox API. Those tests
//! would be better placed in example code or Sandbox-level integration tests.
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! ## Running Tests
//!
//! Use `mise run test` which automatically handles precompilation:
//! ```sh
//! mise run setup  # One-time: build WASM + precompile
//! mise run test   # Run tests with precompiled WASM (~0.1s)
//! ```

#[cfg(not(feature = "embedded"))]
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use eryx::{PythonExecutor, SessionExecutor};

/// Shared executor to avoid repeated WASM loading across tests.
static SHARED_EXECUTOR: OnceLock<Arc<PythonExecutor>> = OnceLock::new();

fn get_shared_executor() -> Arc<PythonExecutor> {
    SHARED_EXECUTOR
        .get_or_init(|| Arc::new(create_executor()))
        .clone()
}

/// Create a PythonExecutor, using embedded resources if available.
fn create_executor() -> PythonExecutor {
    // When embedded feature is enabled, use it for zero-config setup
    #[cfg(feature = "embedded")]
    {
        let resources =
            eryx::embedded::EmbeddedResources::get().expect("Failed to extract embedded resources");

        #[allow(unsafe_code)]
        unsafe { PythonExecutor::from_precompiled_file(resources.runtime()) }
            .expect("Failed to load embedded runtime")
            .with_python_stdlib(resources.stdlib())
    }

    // Fall back to file-based loading
    #[cfg(not(feature = "embedded"))]
    {
        let stdlib_path = python_stdlib_path();
        let path = runtime_wasm_path();
        PythonExecutor::from_file(&path)
            .unwrap_or_else(|e| panic!("Failed to load runtime.wasm from {:?}: {}", path, e))
            .with_python_stdlib(&stdlib_path)
    }
}

#[cfg(not(feature = "embedded"))]
fn runtime_wasm_path() -> PathBuf {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(manifest_dir)
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .join("eryx-runtime")
        .join("runtime.wasm")
}

#[cfg(not(feature = "embedded"))]
fn python_stdlib_path() -> PathBuf {
    // Check ERYX_PYTHON_STDLIB env var first (used in CI)
    if let Ok(path) = std::env::var("ERYX_PYTHON_STDLIB") {
        let path = PathBuf::from(path);
        if path.exists() {
            return path;
        }
    }

    // Fall back to relative path from crate directory
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(manifest_dir)
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .join("eryx-wasm-runtime")
        .join("tests")
        .join("python-stdlib")
}

/// Helper to create a session for testing.
async fn create_session() -> SessionExecutor {
    let executor = get_shared_executor();

    SessionExecutor::new(executor, &[])
        .await
        .expect("Failed to create session")
}

// =============================================================================
// Python Syntax Error Tests
// =============================================================================

#[tokio::test]
async fn test_python_syntax_error_missing_colon() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
def broken()  # Missing colon
    pass
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with syntax error");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("SyntaxError") || error.contains("syntax"),
        "Error should mention syntax: {}",
        error
    );
}

#[tokio::test]
async fn test_python_syntax_error_unclosed_parenthesis() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
print("hello"
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with syntax error");
}

#[tokio::test]
async fn test_python_syntax_error_invalid_indentation() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
def foo():
pass  # Should be indented
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with indentation error");
}

// =============================================================================
// Python Runtime Error Tests
// =============================================================================

#[tokio::test]
async fn test_python_name_error_undefined_variable() {
    let mut session = create_session().await;

    let result = session.execute("x = undefined_variable + 1").run().await;

    assert!(result.is_err(), "Should fail with NameError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("NameError") || error.contains("undefined"),
        "Error should mention undefined variable: {}",
        error
    );
}

#[tokio::test]
async fn test_python_type_error_string_plus_int() {
    let mut session = create_session().await;

    let result = session.execute(r#"result = "hello" + 42"#).run().await;

    assert!(result.is_err(), "Should fail with TypeError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("TypeError") || error.contains("type"),
        "Error should mention type error: {}",
        error
    );
}

#[tokio::test]
async fn test_python_zero_division_error() {
    let mut session = create_session().await;

    let result = session.execute("x = 42 / 0").run().await;

    assert!(result.is_err(), "Should fail with ZeroDivisionError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("ZeroDivisionError") || error.contains("division"),
        "Error should mention division: {}",
        error
    );
}

#[tokio::test]
async fn test_python_index_error() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
items = [1, 2, 3]
x = items[10]
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with IndexError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("IndexError") || error.contains("index"),
        "Error should mention index: {}",
        error
    );
}

#[tokio::test]
async fn test_python_key_error() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
data = {"a": 1}
x = data["nonexistent"]
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with KeyError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("KeyError") || error.contains("key"),
        "Error should mention key: {}",
        error
    );
}

#[tokio::test]
async fn test_python_attribute_error() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
x = 42
x.nonexistent_method()
"#,
        )
        .run()
        .await;

    assert!(result.is_err(), "Should fail with AttributeError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("AttributeError") || error.contains("attribute"),
        "Error should mention attribute: {}",
        error
    );
}

#[tokio::test]
async fn test_python_value_error() {
    let mut session = create_session().await;

    let result = session.execute(r#"x = int("not_a_number")"#).run().await;

    assert!(result.is_err(), "Should fail with ValueError");
    let error = result.unwrap_err().to_string();
    assert!(
        error.contains("ValueError") || error.contains("invalid"),
        "Error should mention value error: {}",
        error
    );
}

// =============================================================================
// Edge Case Tests
// =============================================================================

#[tokio::test]
async fn test_empty_code_executes_successfully() {
    let mut session = create_session().await;

    let result = session.execute("").run().await;

    assert!(result.is_ok(), "Empty code should execute successfully");
    let output = result.unwrap();
    assert!(output.stdout.is_empty(), "Empty code produces no output");
}

#[tokio::test]
async fn test_whitespace_only_code() {
    let mut session = create_session().await;

    let result = session.execute("   \n\n   \t\t\n").run().await;

    assert!(
        result.is_ok(),
        "Whitespace-only code should execute successfully"
    );
}

#[tokio::test]
async fn test_comment_only_code() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
# This is a comment
# Another comment
"#,
        )
        .run()
        .await;

    assert!(result.is_ok(), "Comment-only code should succeed");
}

#[tokio::test]
async fn test_unicode_in_code() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
message = "Hello 世界 🌍 مرحبا"
print(message)
"#,
        )
        .run()
        .await;

    assert!(result.is_ok(), "Unicode should work");
    let output = result.unwrap();
    assert!(output.stdout.contains("世界"), "Should contain Chinese");
    assert!(output.stdout.contains("🌍"), "Should contain emoji");
}

#[tokio::test]
async fn test_exception_in_except_block() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
try:
    x = 1 / 0
except:
    # Another error in the except block
    y = undefined_in_except
"#,
        )
        .run()
        .await;

    assert!(
        result.is_err(),
        "Exception in except block should propagate"
    );
}

#[tokio::test]
async fn test_multiple_errors_in_sequence() {
    let mut session = create_session().await;

    // First error
    let result1 = session.execute("x = 1 / 0").run().await;
    assert!(result1.is_err());

    // Session should still work after error
    let result2 = session.execute("print('recovered')").run().await;
    assert!(result2.is_ok());
    assert!(result2.unwrap().stdout.contains("recovered"));

    // Another error
    let result3 = session.execute("y = undefined_var").run().await;
    assert!(result3.is_err());

    // And recover again
    let result4 = session.execute("print('still working')").run().await;
    assert!(result4.is_ok());
}

#[tokio::test]
async fn test_large_output() {
    let mut session = create_session().await;

    let result = session
        .execute(
            r#"
for i in range(1000):
    print(f"Line {i}: " + "x" * 100)
"#,
        )
        .run()
        .await;

    assert!(result.is_ok(), "Large output should work");
    let output = result.unwrap();
    assert!(
        output.stdout.len() > 100_000,
        "Should have substantial output"
    );
    assert!(output.stdout.contains("Line 999"), "Should have last line");
}

#[tokio::test]
async fn test_execution_timeout_with_infinite_loop() {
    use std::time::Duration;

    let executor = get_shared_executor();
    let mut session = SessionExecutor::new(executor, &[])
        .await
        .expect("Failed to create session");

    // Set a 500ms timeout (longer to account for Python startup)
    session.set_execution_timeout(Some(Duration::from_millis(500)));

    // This infinite loop should be interrupted by epoch-based timeout
    let start = std::time::Instant::now();
    let result = session.execute("while True: pass").run().await;
    let elapsed = start.elapsed();

    assert!(result.is_err(), "Infinite loop should timeout");
    let error = result.unwrap_err();
    assert!(
        matches!(error, eryx::Error::Timeout(_)),
        "Error should be Timeout variant: {:?}",
        error
    );

    // Should complete in roughly the timeout duration (with some margin)
    assert!(
        elapsed < Duration::from_secs(2),
        "Should timeout quickly, not hang forever. Elapsed: {:?}",
        elapsed
    );
}

#[tokio::test]
async fn test_execution_timeout_allows_fast_code() {
    use std::time::Duration;

    let executor = get_shared_executor();
    let mut session = SessionExecutor::new(executor, &[])
        .await
        .expect("Failed to create session");

    // Set a generous timeout
    session.set_execution_timeout(Some(Duration::from_secs(5)));

    // Fast code should complete successfully
    let result = session
        .execute("x = sum(range(1000))\nprint(x)")
        .run()
        .await;

    assert!(result.is_ok(), "Fast code should succeed: {:?}", result);
    assert!(result.unwrap().stdout.contains("499500"));
}

#[tokio::test]
async fn test_session_recovers_after_timeout() {
    use std::time::Duration;

    let executor = get_shared_executor();
    let mut session = SessionExecutor::new(executor, &[])
        .await
        .expect("Failed to create session");

    // Set a short timeout
    session.set_execution_timeout(Some(Duration::from_millis(100)));

    // First execution times out
    let result = session.execute("while True: pass").run().await;
    assert!(result.is_err(), "Should timeout");

    // Session should still be usable after timeout
    // Need to reset since the store may be in a bad state after trap
    session.reset(&[]).await.expect("Reset should work");
    session.set_execution_timeout(Some(Duration::from_secs(5)));

    let result = session.execute("print('recovered')").run().await;
    assert!(
        result.is_ok(),
        "Session should recover after timeout: {:?}",
        result
    );
    assert!(result.unwrap().stdout.contains("recovered"));
}

#[tokio::test]
async fn test_execution_timeout_interrupts_blocking_sleep() {
    use std::time::Duration;

    let executor = get_shared_executor();
    let mut session = SessionExecutor::new(executor, &[])
        .await
        .expect("Failed to create session");

    // Set a 1s timeout - the sleep(10) should be interrupted well before 10s
    session.set_execution_timeout(Some(Duration::from_secs(1)));

    let start = std::time::Instant::now();
    let result = session.execute("import time\ntime.sleep(10)").run().await;
    let elapsed = start.elapsed();

    assert!(result.is_err(), "Sleep should be interrupted by timeout");
    let error = result.unwrap_err();
    assert!(
        matches!(error, eryx::Error::Timeout(_)),
        "Error should be Timeout variant: {:?}",
        error
    );

    // The key assertion: should complete in ~1s, not 10s
    assert!(
        elapsed < Duration::from_secs(3),
        "Timeout should interrupt blocking sleep promptly. Elapsed: {:?}",
        elapsed
    );
}