eryx 0.4.9

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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Integration test for SessionExecutor state persistence.
//!
//! This test verifies that Python state (variables, functions, etc.) persists
//! between execute() calls when using SessionExecutor.
#![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)
//! ```
//!
//! Or manually with cargo:
//! ```sh
//! cargo nextest run --workspace --features precompiled
//! ```

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

use eryx::{PythonExecutor, PythonStateSnapshot, SessionExecutor};

/// Shared executor to avoid repeated WASM loading across tests.
/// With precompiled WASM (the default), loading takes ~50ms.
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 available, use it (more reliable)
    #[cfg(feature = "embedded")]
    {
        use eryx::embedded::EmbeddedResources;
        let resources = EmbeddedResources::get().expect("Failed to extract embedded resources");
        // SAFETY: We trust the embedded precompiled runtime
        #[allow(unsafe_code)]
        return unsafe {
            PythonExecutor::from_precompiled_file(&resources.runtime_path)
                .expect("Failed to load embedded runtime")
                .with_python_stdlib(&resources.stdlib_path)
        };
    }

    // Fallback for when embedded feature is not available
    #[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)
    }
}

/// Get the path to runtime.wasm relative to the workspace root.
#[cfg(not(feature = "embedded"))]
fn runtime_wasm_path() -> PathBuf {
    // CARGO_MANIFEST_DIR points to crates/eryx
    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 executor for tests.
/// Uses a shared PythonExecutor to avoid repeated WASM compilation.
async fn create_session() -> SessionExecutor {
    let executor = get_shared_executor();

    SessionExecutor::new(executor, &[])
        .await
        .unwrap_or_else(|e| panic!("Failed to create session: {}", e))
}

/// Test that variables persist between execute() calls.
#[tokio::test]
async fn test_variable_persistence() {
    let mut session = create_session().await;

    // Define a variable
    let output = session
        .execute("x = 42")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to execute x = 42: {}", e));
    assert_eq!(output.stdout, "", "Assignment should produce no output");

    // Access the variable in a subsequent call
    let output = session
        .execute("print(x)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to execute print(x): {}", e));
    assert_eq!(
        output.stdout, "42",
        "Variable x should persist and equal 42"
    );

    // Modify the variable
    let output = session
        .execute("x = x + 1")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to execute x = x + 1: {}", e));
    assert_eq!(output.stdout, "", "Assignment should produce no output");

    // Verify the modification persisted
    let output = session
        .execute("print(x)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to execute print(x) after modification: {}", e));
    assert_eq!(
        output.stdout, "43",
        "Variable x should be 43 after increment"
    );
}

/// Test that functions persist between execute() calls.
#[tokio::test]
async fn test_function_persistence() {
    let mut session = create_session().await;

    // Define a function
    let output = session
        .execute(
            r#"
def greet(name):
    return f"Hello, {name}!"
"#,
        )
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to define function: {}", e));
    assert_eq!(
        output.stdout, "",
        "Function definition should produce no output"
    );

    // Call the function in a subsequent execution
    let output = session
        .execute("print(greet('World'))")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call greet function: {}", e));
    assert_eq!(
        output.stdout, "Hello, World!",
        "Function should be callable"
    );
}

/// Test that classes persist between execute() calls.
#[tokio::test]
async fn test_class_persistence() {
    let mut session = create_session().await;

    // Define a class (use MyCounter to avoid conflict with collections.Counter)
    let output = session
        .execute(
            r#"
class MyCounter:
    def __init__(self, start=0):
        self.value = start

    def increment(self):
        self.value += 1
        return self.value
"#,
        )
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to define class: {}", e));
    assert_eq!(
        output.stdout, "",
        "Class definition should produce no output"
    );

    // Create an instance
    let output = session
        .execute("counter = MyCounter(10)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to create instance: {}", e));
    assert_eq!(
        output.stdout, "",
        "Instance creation should produce no output"
    );

    // Call methods on the instance
    let output = session
        .execute("print(counter.increment())")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call increment: {}", e));
    assert_eq!(output.stdout, "11", "First increment should return 11");

    let output = session
        .execute("print(counter.increment())")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call second increment: {}", e));
    assert_eq!(output.stdout, "12", "Second increment should return 12");
}

/// Test that clear_state() clears persistent variables.
#[tokio::test]
async fn test_clear_state() {
    let mut session = create_session().await;

    // Define a variable
    session
        .execute("x = 100")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set x: {}", e));

    // Verify it exists
    let output = session
        .execute("print(x)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to print x: {}", e));
    assert_eq!(output.stdout, "100");

    // Clear the state
    session
        .clear_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to clear state: {}", e));

    // Variable should no longer exist
    let result = session.execute("print(x)").run().await;
    assert!(
        result.is_err(),
        "After clear_state, x should not be defined: {:?}",
        result
    );
}

/// Test that reset() clears state by creating a new WASM instance.
#[tokio::test]
async fn test_reset_clears_state() {
    let mut session = create_session().await;

    // Define a variable
    session
        .execute("x = 100")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set x: {}", e));

    // Verify it exists
    let output = session
        .execute("print(x)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to print x: {}", e));
    assert_eq!(output.stdout, "100");

    // Reset the session
    session
        .reset(&[])
        .await
        .unwrap_or_else(|e| panic!("Failed to reset session: {}", e));

    // Variable should no longer exist
    let result = session.execute("print(x)").run().await;
    assert!(
        result.is_err(),
        "After reset, x should not be defined: {:?}",
        result
    );
}

/// Test multiple variables and complex state.
#[tokio::test]
async fn test_complex_state_persistence() {
    let mut session = create_session().await;

    // Build up complex state across multiple calls
    session
        .execute("data = []")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to create list: {}", e));

    session
        .execute("data.append(1)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to append 1: {}", e));

    session
        .execute("data.append(2)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to append 2: {}", e));

    session
        .execute("data.append(3)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to append 3: {}", e));

    // Verify the accumulated state
    let output = session
        .execute("print(sum(data))")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to sum data: {}", e));
    assert_eq!(output.stdout, "6", "Sum of [1, 2, 3] should be 6");

    let output = session
        .execute("print(len(data))")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to get len: {}", e));
    assert_eq!(output.stdout, "3", "Length should be 3");
}

/// Test execution count tracking.
#[tokio::test]
async fn test_execution_count() {
    let mut session = create_session().await;

    assert_eq!(session.execution_count(), 0, "Initial count should be 0");

    session
        .execute("x = 1")
        .run()
        .await
        .unwrap_or_else(|e| panic!("exec 1 failed: {}", e));
    assert_eq!(session.execution_count(), 1);

    session
        .execute("x = 2")
        .run()
        .await
        .unwrap_or_else(|e| panic!("exec 2 failed: {}", e));
    assert_eq!(session.execution_count(), 2);

    session
        .execute("x = 3")
        .run()
        .await
        .unwrap_or_else(|e| panic!("exec 3 failed: {}", e));
    assert_eq!(session.execution_count(), 3);

    // Reset should clear count
    session
        .reset(&[])
        .await
        .unwrap_or_else(|e| panic!("reset failed: {}", e));
    assert_eq!(
        session.execution_count(),
        0,
        "Count should be 0 after reset"
    );
}

/// Test state snapshot and restore.
#[tokio::test]
async fn test_snapshot_and_restore() {
    let mut session = create_session().await;

    // Build up some state
    session
        .execute("x = 10")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set x: {}", e));
    session
        .execute("y = 20")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set y: {}", e));
    session
        .execute("data = [1, 2, 3]")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set data: {}", e));

    // Take a snapshot
    let snapshot = session
        .snapshot_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to snapshot: {}", e));

    assert!(snapshot.size() > 0, "Snapshot should have data");

    // Modify the state
    session
        .execute("x = 999")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to modify x: {}", e));

    // Verify modification
    let output = session
        .execute("print(x)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to print x: {}", e));
    assert_eq!(output.stdout, "999");

    // Restore the snapshot
    session
        .restore_state(&snapshot)
        .await
        .unwrap_or_else(|e| panic!("Failed to restore: {}", e));

    // Verify original values are back
    let output = session
        .execute("print(x)")
        .run()
        .await
        .expect("Failed to read x");
    assert_eq!(output.stdout, "10", "x should be restored to 10");

    let output = session
        .execute("print(y)")
        .run()
        .await
        .expect("Failed to read y");
    assert_eq!(output.stdout, "20", "y should be restored to 20");

    let output = session
        .execute("print(data)")
        .run()
        .await
        .expect("Failed to read data");
    assert_eq!(output.stdout, "[1, 2, 3]", "data should be restored");
}

/// Test snapshot serialization roundtrip.
#[tokio::test]
async fn test_snapshot_serialization() {
    let mut session = create_session().await;

    // Set up state
    session
        .execute("value = 42")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set value: {}", e));

    // Take a snapshot
    let snapshot = session
        .snapshot_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to snapshot: {}", e));

    // Serialize to bytes
    let bytes = snapshot.to_bytes();
    assert!(
        bytes.len() > 8,
        "Serialized bytes should include header + data"
    );

    // Deserialize
    let restored_snapshot = PythonStateSnapshot::from_bytes(&bytes)
        .unwrap_or_else(|e| panic!("Failed to deserialize: {}", e));

    assert_eq!(restored_snapshot.size(), snapshot.size());
    assert_eq!(
        restored_snapshot.metadata().timestamp_ms,
        snapshot.metadata().timestamp_ms
    );

    // Clear state and restore from deserialized snapshot
    session
        .clear_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to clear: {}", e));

    session
        .restore_state(&restored_snapshot)
        .await
        .unwrap_or_else(|e| panic!("Failed to restore from deserialized: {}", e));

    // Verify the value is back
    let output = session
        .execute("print(value)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to print value: {}", e));
    assert_eq!(output.stdout, "42");
}

/// Test that unserializable objects (e.g. modules) are skipped gracefully.
#[tokio::test]
async fn test_snapshot_with_unserializable() {
    let mut session = create_session().await;

    // Import a module (not serializable)
    session
        .execute("import sys")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to import sys: {}", e));

    // Also create a serializable variable
    session
        .execute("num = 100")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to set num: {}", e));

    // Snapshot should succeed, skipping the module
    let snapshot = session
        .snapshot_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to snapshot: {}", e));

    session.clear_state().await.unwrap();
    session.restore_state(&snapshot).await.unwrap();

    let output = session
        .execute("print(num)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to print num: {}", e));
    assert_eq!(output.stdout, "100", "num should be restored");
}

/// Test that user-defined functions survive snapshot/restore.
#[tokio::test]
async fn test_snapshot_with_functions() {
    let mut session = create_session().await;

    session
        .execute("def greet(name): return f'Hello, {name}!'")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to define function: {}", e));

    session
        .execute("fn = lambda x: x * 2")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to define lambda: {}", e));

    let snapshot = session
        .snapshot_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to snapshot: {}", e));
    assert!(
        snapshot.size() > 10,
        "Snapshot should contain serialized data"
    );

    session.clear_state().await.unwrap();

    session
        .restore_state(&snapshot)
        .await
        .unwrap_or_else(|e| panic!("Failed to restore: {}", e));

    let output = session
        .execute("print(greet('World'))")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call greet: {}", e));
    assert_eq!(output.stdout, "Hello, World!");

    let output = session
        .execute("print(fn(21))")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call lambda: {}", e));
    assert_eq!(output.stdout, "42");
}

/// Test that user-defined classes and instances survive snapshot/restore.
#[tokio::test]
async fn test_snapshot_with_classes() {
    let mut session = create_session().await;

    session
        .execute(
            r#"
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self):
        return (self.x**2 + self.y**2) ** 0.5
"#,
        )
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to define class: {}", e));

    session
        .execute("p = Point(3, 4)")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to create instance: {}", e));

    let snapshot = session
        .snapshot_state()
        .await
        .unwrap_or_else(|e| panic!("Failed to snapshot: {}", e));

    session.clear_state().await.unwrap();

    session
        .restore_state(&snapshot)
        .await
        .unwrap_or_else(|e| panic!("Failed to restore: {}", e));

    // Instance should work
    let output = session
        .execute("print(p.distance())")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to call method: {}", e));
    assert_eq!(output.stdout, "5.0");

    // Can create new instances of the restored class
    let output = session
        .execute("print(Point(5, 12).distance())")
        .run()
        .await
        .unwrap_or_else(|e| panic!("Failed to create new instance: {}", e));
    assert_eq!(output.stdout, "13.0");
}