pctx_executor 0.3.1

TypeScript execution environment orchestration
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
//! Guards for runtime semantics that depend on `deno_core` / V8 internals.
//!
//! These pin down behavior that an upgrade of the Deno stack could silently
//! change: async op scheduling (tool calls and timers), event loop draining,
//! error propagation, and the ICU / Temporal / WebAssembly builtins.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use pctx_code_execution_runtime::PctxRegistry;
use serde_json::{Value, json};

use super::serial;
use crate::{ExecuteOptions, ExecuteResult, execute};

type CallLog = Arc<Mutex<Vec<String>>>;

/// Registry with a delayed tool, an immediate tool and a failing tool.
/// Every call start/end is recorded in `log`.
fn registry(log: &CallLog) -> PctxRegistry {
    let registry = PctxRegistry::default();

    let l = log.clone();
    registry
        .add_callback(
            "probe.slow",
            Arc::new(move |args: Option<Value>| {
                let l = l.clone();
                Box::pin(async move {
                    let args = args.unwrap_or_default();
                    let tag = args["tag"].as_str().unwrap_or("?").to_string();
                    let ms = args["ms"].as_u64().unwrap_or(0);
                    l.lock().unwrap().push(format!("start:{tag}"));
                    tokio::time::sleep(Duration::from_millis(ms)).await;
                    l.lock().unwrap().push(format!("end:{tag}"));
                    Ok(json!({ "tag": tag }))
                })
            }),
        )
        .expect("callback registration should succeed");

    let l = log.clone();
    registry
        .add_callback(
            "probe.sync",
            Arc::new(move |args: Option<Value>| {
                let l = l.clone();
                Box::pin(async move {
                    let tag = args.unwrap_or_default()["tag"]
                        .as_str()
                        .unwrap_or("?")
                        .to_string();
                    l.lock().unwrap().push(format!("sync:{tag}"));
                    Ok(json!(tag))
                })
            }),
        )
        .expect("callback registration should succeed");

    registry
        .add_callback(
            "probe.fail",
            Arc::new(move |_args: Option<Value>| {
                Box::pin(async move { Err("tool exploded".to_string()) })
            }),
        )
        .expect("callback registration should succeed");

    registry
}

async fn run(code: &str, log: &CallLog) -> ExecuteResult {
    tokio::time::timeout(
        Duration::from_secs(30),
        execute(code, ExecuteOptions::new().with_registry(registry(log))),
    )
    .await
    .expect("execution should not hang")
    .expect("execution should not error internally")
}

fn assert_ok(result: &ExecuteResult) {
    assert!(
        result.success,
        "execution failed: runtime_error={:?} diagnostics={:?}",
        result.runtime_error, result.diagnostics
    );
}

#[serial]
#[tokio::test]
async fn test_tool_call_resolves_after_microtasks() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    const order: string[] = [];
    const p = invokeInternal({ name: "probe.sync", arguments: { tag: "A" } }).then(() => order.push("tool-resolved"));
    order.push("after-call");
    Promise.resolve().then(() => order.push("microtask"));
    queueMicrotask(() => order.push("queueMicrotask"));
    await p;
    order.push("after-await");
    return order;
}
export default await test();
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!([
            "after-call",
            "microtask",
            "queueMicrotask",
            "tool-resolved",
            "after-await"
        ]))
    );
}

#[serial]
#[tokio::test]
async fn test_parallel_tool_calls_run_concurrently() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    const t0 = Date.now();
    const results = await Promise.all([
        invokeInternal({ name: "probe.slow", arguments: { tag: "a", ms: 300 } }),
        invokeInternal({ name: "probe.slow", arguments: { tag: "b", ms: 100 } }),
        invokeInternal({ name: "probe.slow", arguments: { tag: "c", ms: 200 } }),
    ]);
    return { results, elapsed: Date.now() - t0 };
}
export default await test();
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    let output = result.output.expect("should have output");
    assert_eq!(
        output["results"],
        json!([{ "tag": "a" }, { "tag": "b" }, { "tag": "c" }]),
        "Promise.all should keep input order"
    );
    let elapsed = output["elapsed"].as_u64().unwrap();
    assert!(
        elapsed < 550,
        "tool calls should overlap (took {elapsed}ms, sequential would be ~600ms)"
    );

    let calls = log.lock().unwrap().clone();
    assert_eq!(
        calls,
        vec!["start:a", "start:b", "start:c", "end:b", "end:c", "end:a"],
        "all calls should start before any finishes"
    );
}

#[serial]
#[tokio::test]
async fn test_sequential_tool_calls_do_not_overlap() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    const out: unknown[] = [];
    for (const tag of ["x", "y", "z"]) {
        out.push(await invokeInternal({ name: "probe.slow", arguments: { tag, ms: 20 } }));
    }
    return out;
}
export default await test();
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!([{ "tag": "x" }, { "tag": "y" }, { "tag": "z" }]))
    );
    assert_eq!(
        log.lock().unwrap().clone(),
        vec!["start:x", "end:x", "start:y", "end:y", "start:z", "end:z"]
    );
}

#[serial]
#[tokio::test]
async fn test_tool_errors_are_catchable_rejections() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    const settled = await Promise.allSettled([
        invokeInternal({ name: "probe.slow", arguments: { tag: "ok", ms: 10 } }),
        invokeInternal({ name: "probe.fail", arguments: {} }),
    ]);
    let caught: string | null = null;
    try {
        await invokeInternal({ name: "probe.fail", arguments: {} });
    } catch (e) {
        caught = e instanceof Error ? e.message : String(e);
    }
    const winner = await Promise.race([
        invokeInternal({ name: "probe.slow", arguments: { tag: "slow", ms: 200 } }),
        invokeInternal({ name: "probe.slow", arguments: { tag: "fast", ms: 10 } }),
    ]);
    return { settled: settled.map((s) => s.status), caught, winner };
}
export default await test();
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    let output = result.output.expect("should have output");
    assert_eq!(output["settled"], json!(["fulfilled", "rejected"]));
    assert!(
        output["caught"].as_str().unwrap().contains("tool exploded"),
        "unexpected error message: {}",
        output["caught"]
    );
    assert_eq!(output["winner"], json!({ "tag": "fast" }));
}

#[serial]
#[tokio::test]
async fn test_uncaught_tool_error_fails_execution() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    return await invokeInternal({ name: "probe.fail", arguments: {} });
}
export default await test();
"#,
        &log,
    )
    .await;

    assert!(!result.success);
    let error = result.runtime_error.expect("should have runtime error");
    assert!(
        error.message.contains("tool exploded"),
        "unexpected error message: {}",
        error.message
    );
}

#[serial]
#[tokio::test]
async fn test_timer_ordering() {
    let log = CallLog::default();
    let result = run(
        r#"
async function test() {
    const order: string[] = [];
    setTimeout(() => order.push("t0"), 0);
    queueMicrotask(() => order.push("micro"));
    Promise.resolve().then(() => order.push("then"));
    order.push("sync");
    await new Promise((r) => setTimeout(r, 20));
    setTimeout(() => order.push("t30"), 30);
    setTimeout(() => order.push("t10"), 10);
    setTimeout(() => order.push("t20"), 20);
    await new Promise((r) => setTimeout(r, 80));
    return order;
}
export default await test();
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!(["sync", "micro", "then", "t0", "t10", "t20", "t30"]))
    );
}

#[serial]
#[tokio::test]
async fn test_set_interval_and_clear() {
    let log = CallLog::default();
    let result = run(
        r"
async function test() {
    let n = 0;
    await new Promise<void>((resolve) => {
        const id = setInterval(() => {
            n++;
            if (n === 5) {
                clearInterval(id);
                resolve();
            }
        }, 5);
    });
    return n;
}
export default await test();
",
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(result.output, Some(json!(5)));
}

#[serial]
#[tokio::test]
async fn test_event_loop_drains_work_scheduled_after_export() {
    let log = CallLog::default();
    let result = run(
        r#"
setTimeout(() => console.log("late timer fired"), 50);
invokeInternal({ name: "probe.slow", arguments: { tag: "late", ms: 50 } }).then((v) => console.log("late tool", JSON.stringify(v)));
export default 1;
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert!(
        result.stdout.contains("late timer fired"),
        "stdout: {}",
        result.stdout
    );
    assert!(
        result.stdout.contains(r#"late tool {"tag":"late"}"#),
        "stdout: {}",
        result.stdout
    );
    assert_eq!(log.lock().unwrap().clone(), vec!["start:late", "end:late"]);
}

#[serial]
#[tokio::test]
async fn test_unhandled_rejection_fails_execution() {
    let log = CallLog::default();
    let result = run(
        r#"
Promise.reject(new Error("boom"));
export default 1;
"#,
        &log,
    )
    .await;

    assert!(!result.success);
    let error = result.runtime_error.expect("should have runtime error");
    assert!(error.message.contains("boom"), "{}", error.message);
}

#[serial]
#[tokio::test]
async fn test_runtime_error_includes_stack() {
    let log = CallLog::default();
    let result = run(
        r#"
function inner() { throw new TypeError("bad thing"); }
function outer() { inner(); }
outer();
"#,
        &log,
    )
    .await;

    assert!(!result.success);
    let error = result.runtime_error.expect("should have runtime error");
    assert!(
        error.message.starts_with("TypeError: bad thing"),
        "{}",
        error.message
    );
    assert!(error.message.contains("at inner"), "{}", error.message);
    assert!(error.message.contains("at outer"), "{}", error.message);
}

#[serial]
#[tokio::test]
async fn test_stack_overflow_is_catchable() {
    let log = CallLog::default();
    let result = run(
        r"
function recurse(n: number): number { return recurse(n + 1) + 1; }
let msg = '';
try { recurse(0); } catch (e) { msg = (e as Error).constructor.name + ': ' + (e as Error).message; }
export default msg;
",
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!("RangeError: Maximum call stack size exceeded"))
    );
}

#[serial]
#[tokio::test]
async fn test_intl_uses_bundled_icu_data() {
    let log = CallLog::default();
    let result = run(
        r#"
const d = new Date(Date.UTC(2026, 9, 5, 12));
export default {
    nyHour: new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", hour: "numeric", hour12: false }).format(d),
    tokyoHour: new Intl.DateTimeFormat("en-US", { timeZone: "Asia/Tokyo", hour: "numeric", hour12: false }).format(d),
    plural: new Intl.PluralRules("ar").select(3),
    relative: new Intl.RelativeTimeFormat("fr").format(-2, "day"),
    sorted: ["ä", "a", "z"].sort(new Intl.Collator("de").compare),
    turkishUpper: "i".toLocaleUpperCase("tr"),
    japaneseEra: new Intl.DateTimeFormat("ja-JP-u-ca-japanese", { era: "long", year: "numeric", timeZone: "UTC" }).format(d),
};
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!({
            "nyHour": "08",
            "tokyoHour": "21",
            "plural": "few",
            "relative": "il y a 2 jours",
            "sorted": ["a", "ä", "z"],
            "turkishUpper": "İ",
            "japaneseEra": "令和8年",
        }))
    );
}

#[serial]
#[tokio::test]
async fn test_temporal_available() {
    let log = CallLog::default();
    let result = run(
        r#"
const T = (globalThis as any).Temporal;
export default {
    plain: T.PlainDate.from("2026-10-05").add({ months: 1 }).toString(),
    dstGap: T.ZonedDateTime.from("2026-03-08T01:30[America/New_York]").add({ hours: 1 }).toString(),
    until: T.PlainDate.from("2026-01-31").until("2026-03-01", { largestUnit: "month" }).toString(),
    now: typeof T.Now.instant().epochMilliseconds,
};
"#,
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!({
            "plain": "2026-11-05",
            "dstGap": "2026-03-08T03:30:00-04:00[America/New_York]",
            "until": "P1M1D",
            "now": "number",
        }))
    );
}

/// Async WebAssembly compilation relies on V8 platform tasks being pumped by
/// the event loop.
#[serial]
#[tokio::test]
async fn test_webassembly_sync_and_async() {
    let log = CallLog::default();
    let result = run(
        r"
// (module (func (export \x22add\x22) (param i32 i32) (result i32) local.get 0 local.get 1 i32.add))
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
async function test() {
    const W = (globalThis as any).WebAssembly;
    const sync = new W.Instance(new W.Module(bytes)).exports.add(2, 3);
    const { instance } = await W.instantiate(bytes);
    const compiled = await W.compile(bytes);
    return { sync, instantiate: instance.exports.add(4, 5), compile: new W.Instance(compiled).exports.add(1, 1) };
}
export default await test();
",
        &log,
    )
    .await;

    assert_ok(&result);
    assert_eq!(
        result.output,
        Some(json!({ "sync": 5, "instantiate": 9, "compile": 2 }))
    );
}

/// Like `concurrent_v8_stress`, but each execution also exercises async ops
/// (tool calls, timers) and async WebAssembly compilation.
#[test]
fn test_concurrent_executions_with_async_ops() {
    let handles: Vec<_> = (0..4)
        .map(|i| {
            std::thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                rt.block_on(async {
                    for j in 0..3 {
                        let log = CallLog::default();
                        let code = format!(
                            r#"
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
async function test() {{
    const {{ instance }} = await (globalThis as any).WebAssembly.instantiate(bytes);
    await new Promise((r) => setTimeout(r, 5));
    const [a, b] = await Promise.all([
        invokeInternal({{ name: "probe.slow", arguments: {{ tag: "{i}-{j}", ms: 10 }} }}),
        invokeInternal({{ name: "probe.sync", arguments: {{ tag: "{i}-{j}" }} }}),
    ]);
    return {{ sum: instance.exports.add({i}, {j}), a, b }};
}}
export default await test();
"#
                        );
                        let result = run(&code, &log).await;
                        assert_ok(&result);
                        assert_eq!(
                            result.output,
                            Some(json!({
                                "sum": i + j,
                                "a": { "tag": format!("{i}-{j}") },
                                "b": format!("{i}-{j}"),
                            })),
                            "iteration {i}_{j}"
                        );
                    }
                });
            })
        })
        .collect();

    for h in handles {
        h.join().unwrap();
    }
}