rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Bounded execution for the inline `_rift.script` (`respond(ctx)`) path (issue #308).
//!
//! The imposter `_rift.script` path has no script pool, so a runaway script (e.g. an
//! infinite Rhai `loop {}`) ran unbounded on the async worker and wedged the whole engine.
//! This module runs the script off the async worker via `spawn_blocking` and interrupts it
//! at a wall-clock deadline using the same abort-flag mechanism as the pooled path (#172):
//! Rhai's `on_progress` callback.

use super::{
    FaultDecision, ScriptCtxExtras, ScriptEngine, ScriptRequest, ScriptTraceEntry,
    capture_script_logs, render_decision,
};
use crate::extensions::flow_state::FlowStore;
use crate::imposter::ImposterConfig;
use anyhow::Result;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tracing::warn;

/// A script hook exceeded its wall-clock deadline (issue #499).
///
/// A timeout is a transient load condition, not a broken script — the handler recovers this via
/// `downcast_ref` and maps it to a distinct 504 + `x-rift-script-timeout` response, so monitoring
/// and clients can tell a retry-worthy deadline miss from a permanent config error. Deliberately
/// not feature-gated: the `_rift.script` and predicate-matching deadlines exist regardless of the
/// `javascript` feature, so both paths return the same type.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{hook} timed out after {timeout_ms}ms")]
pub struct ScriptTimeoutError {
    /// Which hook hit the deadline: `"inject"`, `"predicate inject"`, `"decorate"` or `"_rift.script"`.
    pub hook: &'static str,
    pub timeout_ms: u64,
}

/// A wasm script named only by its code: no knobs, the `rift` export, default limits. For the
/// string-typed entry points, which carry no `_rift.script` config.
fn default_wasm_script(code: &str) -> super::WasmScript<'_> {
    super::WasmScript {
        code,
        export: None,
        knobs: None,
        limits: crate::imposter::WasmLimits::default(),
        clock: None,
        instance: None,
        instances: None,
    }
}

/// Default script timeout when `_rift.scriptEngine.timeoutMs` is not configured.
pub const DEFAULT_SCRIPT_TIMEOUT_MS: u64 = 5000;

/// The `_rift.script` wall-clock deadline for an imposter: `_rift.scriptEngine.timeoutMs`
/// if configured, else [`DEFAULT_SCRIPT_TIMEOUT_MS`] (issue #308).
pub fn resolve_script_timeout_ms(config: &ImposterConfig) -> u64 {
    config
        .rift
        .as_ref()
        .and_then(|r| r.script_engine.as_ref())
        .map(|se| se.timeout_ms)
        .unwrap_or(DEFAULT_SCRIPT_TIMEOUT_MS)
}

/// Run a `_rift.script` `respond(ctx)` off the async worker with a wall-clock deadline
/// (issue #308). Execution happens in `spawn_blocking` so a non-yielding script cannot
/// starve the Tokio runtime, and at `timeout` the abort flag is set so the script self-
/// interrupts. Rhai (`on_progress`) is truly interrupted and frees its thread promptly.
/// JavaScript can't observe the deadline flag mid-run (Boa has no per-instruction interrupt),
/// but its context caps loop iterations (issue #327), so a runaway loop terminates by throwing
/// instead of leaking its blocking thread forever. Returns `Err` on timeout, a compile/exec
/// error, or a panic.
pub async fn should_inject_bounded(
    engine_type: String,
    code: String,
    rule_id: String,
    request: ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    timeout: Duration,
) -> Result<FaultDecision> {
    should_inject_bounded_with_ctx(
        engine_type,
        code,
        rule_id,
        request,
        flow_store,
        timeout,
        ScriptCtxExtras::default(),
    )
    .await
}

/// As [`should_inject_bounded`], but threading real `ctx.flowId`/`ctx.stub` context (issue #357
/// Item 1) through to the v2 `ctx` object — used by the imposter `_rift.script` hook, which knows
/// the resolved flow id and matched stub.
pub async fn should_inject_bounded_with_ctx(
    engine_type: String,
    code: String,
    rule_id: String,
    request: ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    timeout: Duration,
    ctx_extra: ScriptCtxExtras,
) -> Result<FaultDecision> {
    if super::ScriptEngineKind::is_wasm(&engine_type) {
        return should_inject_wasm(
            default_wasm_script(&code),
            &rule_id,
            &request,
            flow_store,
            timeout,
            &ctx_extra,
        )
        .await
        .and_then(|answer| answer.into_fault_decision(&rule_id));
    }
    let abort = Arc::new(AtomicBool::new(false));
    let run_abort = Arc::clone(&abort);
    // A script's `ctx.state` reaches the flow store, and a failing backend annotates the op it
    // failed on — on a pool thread with no task-local unless the closure carries its own scope
    // (issue #987). This is the path `docs/embedding/spi.md` uses as its worked example.
    let handle = crate::extensions::decorate::spawn_blocking_annotated(move || {
        run_should_inject_with_abort(
            &engine_type,
            &code,
            &rule_id,
            &request,
            flow_store,
            &run_abort,
            &ctx_extra,
        )
    });

    match tokio::time::timeout(timeout, handle).await {
        Ok(Ok((result, annotations))) => {
            crate::extensions::decorate::replay_annotations(annotations);
            result
        }
        Ok(Err(join_err)) => Err(anyhow::anyhow!("script task panicked: {join_err}")),
        Err(_elapsed) => {
            // Signal the deadline: Rhai self-interrupts and frees its thread promptly; for
            // other engines this is a best-effort flag they never observe.
            abort.store(true, Ordering::Relaxed);
            warn!(
                "_rift.script execution timed out after {}ms",
                timeout.as_millis()
            );
            Err(ScriptTimeoutError {
                hook: "_rift.script",
                timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
            }
            .into())
        }
    }
}

/// As [`should_inject_bounded_with_ctx`], but also builds a debug-mode script trace (issue #360
/// Item 3): the rendered decision, wall-clock duration, and any `ctx.logger` lines this run
/// emitted. Only called when debug mode is on — [`should_inject_bounded_with_ctx`] above is
/// unchanged and stays the zero-cost default the rest of the time (no capturing subscriber, no
/// extra `Instant`/allocation).
pub async fn should_inject_bounded_with_ctx_traced(
    engine_type: String,
    code: String,
    rule_id: String,
    request: ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    timeout: Duration,
    ctx_extra: ScriptCtxExtras,
) -> (Result<FaultDecision>, ScriptTraceEntry) {
    if super::ScriptEngineKind::is_wasm(&engine_type) {
        let (answer, entry) = should_inject_wasm_traced(
            default_wasm_script(&code),
            &rule_id,
            &request,
            flow_store,
            timeout,
            &ctx_extra,
        )
        .await;
        return (
            answer.and_then(|answer| answer.into_fault_decision(&rule_id)),
            entry,
        );
    }
    let abort = Arc::new(AtomicBool::new(false));
    let run_abort = Arc::clone(&abort);
    let start = Instant::now();
    // Same store reach as the untraced path above (issue #987).
    let handle = crate::extensions::decorate::spawn_blocking_annotated(move || {
        capture_script_logs(|| {
            run_should_inject_with_abort(
                &engine_type,
                &code,
                &rule_id,
                &request,
                flow_store,
                &run_abort,
                &ctx_extra,
            )
        })
    });

    let (result, logs) = match tokio::time::timeout(timeout, handle).await {
        Ok(Ok(((result, logs), annotations))) => {
            crate::extensions::decorate::replay_annotations(annotations);
            (result, logs)
        }
        Ok(Err(join_err)) => (
            Err(anyhow::anyhow!("script task panicked: {join_err}")),
            Vec::new(),
        ),
        Err(_elapsed) => {
            abort.store(true, Ordering::Relaxed);
            warn!(
                "_rift.script execution timed out after {}ms",
                timeout.as_millis()
            );
            (
                Err(ScriptTimeoutError {
                    hook: "_rift.script",
                    timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
                }
                .into()),
                Vec::new(),
            )
        }
    };
    let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
    let decision = match &result {
        Ok(d) => render_decision(d),
        Err(e) => format!("error: {e}"),
    };
    // Raw (uncapped) logs here: `rift script run` prints them all to the terminal. The
    // header-bound debug trace caps them at its own serialization site (issue #360) — a
    // response header, unlike a terminal dump, must stay bounded.
    let entry = ScriptTraceEntry {
        hook: "respond".to_string(),
        decision,
        duration_ms,
        logs,
        fuel_used: None,
        trap: None,
    };
    (result, entry)
}

/// Run an `engine: "wasm"` `_rift.script` (issue #1751): one call of the component on the request
/// task, interrupted at `timeout` by wasmtime's epoch deadline, so no blocking thread is held. The
/// answer is a decision (`export: "rift"`) or a whole response (`export: "http"`, issue #1758). The
/// component's stdout and stderr lines are emitted as `ctx.logger` events.
pub async fn should_inject_wasm(
    script: super::WasmScript<'_>,
    rule_id: &str,
    request: &ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    timeout: Duration,
    ctx_extra: &ScriptCtxExtras,
) -> Result<super::WasmAnswer> {
    #[cfg(feature = "wasm")]
    {
        let (result, report) =
            super::wasm::respond(script, rule_id, request, flow_store, timeout, ctx_extra).await;
        super::wasm::emit_logs(&report);
        result
    }
    #[cfg(not(feature = "wasm"))]
    {
        let _ = (script, rule_id, request, flow_store, timeout, ctx_extra);
        Err(anyhow::anyhow!(super::WASM_UNAVAILABLE))
    }
}

/// As [`should_inject_wasm`], and the debug-mode trace entry: the decision, the duration, the
/// component's log lines, the fuel it spent and how it trapped.
pub async fn should_inject_wasm_traced(
    script: super::WasmScript<'_>,
    rule_id: &str,
    request: &ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    timeout: Duration,
    ctx_extra: &ScriptCtxExtras,
) -> (Result<super::WasmAnswer>, ScriptTraceEntry) {
    let start = Instant::now();
    #[cfg(feature = "wasm")]
    let (result, logs, fuel_used, trap) = {
        let (result, report) =
            super::wasm::respond(script, rule_id, request, flow_store, timeout, ctx_extra).await;
        let ((), logs) = capture_script_logs(|| super::wasm::emit_logs(&report));
        (result, logs, report.fuel_used, report.trap_text())
    };
    #[cfg(not(feature = "wasm"))]
    let (result, logs, fuel_used, trap) = {
        let _ = (script, rule_id, request, flow_store, timeout, ctx_extra);
        let result: Result<super::WasmAnswer> = Err(anyhow::anyhow!(super::WASM_UNAVAILABLE));
        (result, Vec::new(), None, None)
    };
    let decision = match &result {
        Ok(super::WasmAnswer::Decision(d)) => render_decision(d),
        Ok(super::WasmAnswer::Response(r)) => render_decision(&FaultDecision::Error {
            status: r.status,
            body: String::from_utf8_lossy(&r.body).into_owned(),
            rule_id: rule_id.to_owned(),
            headers: super::joined_headers(&r.headers),
        }),
        Err(e) => format!("error: {e}"),
    };
    let entry = ScriptTraceEntry {
        hook: "respond".to_string(),
        decision,
        duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
        logs,
        fuel_used,
        trap,
    };
    (result, entry)
}

/// Execute `respond(ctx)` synchronously with the abort flag wired into the interpreter, so
/// setting `abort` interrupts a runaway script. Rhai gets a real interpreter interrupt
/// (#308/#172); other engines run without an interpreter interrupt but still off the async
/// worker and under the request-level timeout.
fn run_should_inject_with_abort(
    engine_type: &str,
    code: &str,
    rule_id: &str,
    request: &ScriptRequest,
    flow_store: Arc<dyn FlowStore>,
    abort: &Arc<AtomicBool>,
    ctx_extra: &ScriptCtxExtras,
) -> Result<FaultDecision> {
    // Start each execution with a clean last-flow-error slot so `flow_store.last_error()` can't
    // observe a stale error left by a previous script on this reused worker thread (issue #322).
    crate::extensions::flow_state::clear_last_flow_error();
    // Only Rhai takes the abort flag; every other kind, and every bad name, goes through
    // `ScriptEngine::new` for its engine or its error.
    if super::ScriptEngineKind::parse(engine_type) == Ok(super::ScriptEngineKind::Rhai) {
        return super::rhai_engine::run_should_inject_with_abort_rhai(
            code, rule_id, request, flow_store, abort, ctx_extra,
        );
    }
    let engine = ScriptEngine::new(engine_type, code, rule_id)?;
    engine.should_inject_fault_with_ctx(request, flow_store, ctx_extra)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extensions::flow_state::NoOpFlowStore;
    use crate::imposter::ResponseMode;
    #[cfg(feature = "javascript")]
    use crate::scripting::ScriptScope;
    use std::time::Instant;

    fn req() -> ScriptRequest {
        ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "GET".into(),
            path: "/hang".into(),
            headers: Default::default(),
            body: serde_json::Value::Null,
            query: Default::default(),
            path_params: Default::default(),
        }
    }

    fn store() -> Arc<dyn FlowStore> {
        Arc::new(NoOpFlowStore)
    }

    /// Thin wrapper over [`should_inject_bounded`] with the fixed test request/store, to
    /// keep the call sites to just engine/code/timeout.
    fn bounded(
        engine: &'static str,
        code: &'static str,
        timeout_ms: u64,
    ) -> impl std::future::Future<Output = Result<FaultDecision>> {
        should_inject_bounded(
            engine.into(),
            code.into(),
            "t".into(),
            req(),
            store(),
            Duration::from_millis(timeout_ms),
        )
    }

    // A bare-expression script (issue #357 Item 2, no `respond` wrapper needed): the whole body
    // runs as the entrypoint, so this loop actually executes (unlike a function that's merely
    // declared but never called), exercising the real interrupt path.
    const RUNAWAY_RHAI: &str = "let i = 0; loop { i += 1; }";

    /// Run the sync interrupt path on a child thread, flip the abort flag after 200ms, and
    /// require the interpreter to unwind within 5s. Running off the test thread with a
    /// `recv_timeout` makes a regression that fails to interrupt FAIL the test (the channel
    /// times out) rather than hang the whole suite.
    fn assert_interrupts(engine: &'static str, code: &'static str) {
        let abort = Arc::new(AtomicBool::new(false));
        let a2 = Arc::clone(&abort);
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(200));
            a2.store(true, Ordering::Relaxed);
        });
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let res = run_should_inject_with_abort(
                engine,
                code,
                "t",
                &req(),
                store(),
                &abort,
                &ScriptCtxExtras::default(),
            );
            let _ = tx.send(res.is_err());
        });
        match rx.recv_timeout(Duration::from_secs(5)) {
            Ok(is_err) => assert!(is_err, "an interrupted script returns an error"),
            Err(_) => panic!("runaway {engine} was NOT interrupted by the abort flag within 5s"),
        }
    }

    // AC1/AC5: a runaway Rhai script is TRULY interrupted (the interpreter unwinds) once the
    // abort flag is set — not merely abandoned.
    #[test]
    fn runaway_rhai_interrupted_by_abort() {
        assert_interrupts("rhai", RUNAWAY_RHAI);
    }

    // The non-rhai dispatch branch: an unknown engine returns an error promptly.
    #[tokio::test]
    async fn unknown_engine_returns_error() {
        let res = bounded("no-such-engine", "whatever", 500).await;
        assert!(
            res.is_err(),
            "an unknown engine is a fast error, not a hang"
        );
    }

    // AC4: the None and Latency decisions pass through the bounded path unchanged.
    #[tokio::test]
    async fn normal_rhai_returns_none_and_latency() {
        let none = bounded("rhai", "fn respond(ctx) { pass() }", 2000)
            .await
            .expect("fast script");
        assert!(matches!(none, FaultDecision::None), "got {none:?}");

        let latency = bounded("rhai", "fn respond(ctx) { delay(7) }", 2000)
            .await
            .expect("fast script");
        match latency {
            FaultDecision::Latency { duration_ms, .. } => assert_eq!(duration_ms, 7),
            other => panic!("expected Latency, got {other:?}"),
        }
    }

    // AC2: the handler resolves the deadline from `_rift.scriptEngine.timeoutMs`, else the
    // default — proving the config plumbing, not just an explicit Duration.
    #[test]
    fn resolves_configured_and_default_timeout() {
        let with_timeout: ImposterConfig = serde_json::from_value(serde_json::json!({
            "protocol": "http",
            "_rift": { "scriptEngine": { "timeoutMs": 321 } },
            "stubs": []
        }))
        .expect("config");
        assert_eq!(resolve_script_timeout_ms(&with_timeout), 321);

        // scriptEngine present but timeoutMs omitted → serde default (kept in sync).
        let engine_no_timeout: ImposterConfig = serde_json::from_value(serde_json::json!({
            "protocol": "http",
            "_rift": { "scriptEngine": { "defaultEngine": "rhai" } },
            "stubs": []
        }))
        .expect("config");
        assert_eq!(
            resolve_script_timeout_ms(&engine_no_timeout),
            DEFAULT_SCRIPT_TIMEOUT_MS
        );

        // no scriptEngine block at all → the handler fallback default.
        let no_engine: ImposterConfig = serde_json::from_value(serde_json::json!({
            "protocol": "http", "stubs": []
        }))
        .expect("config");
        assert_eq!(
            resolve_script_timeout_ms(&no_engine),
            DEFAULT_SCRIPT_TIMEOUT_MS
        );
    }

    // AC1/AC2: the async entrypoint times out a runaway script and returns an error,
    // instead of hanging.
    #[tokio::test]
    async fn should_inject_bounded_times_out_runaway_rhai() {
        let start = Instant::now();
        let res = bounded("rhai", RUNAWAY_RHAI, 200).await;
        let err = res.expect_err("runaway must yield an error, not hang");
        let timeout = err
            .downcast_ref::<crate::scripting::ScriptTimeoutError>()
            .unwrap_or_else(|| {
                panic!("a runaway _rift.script must yield a ScriptTimeoutError; got: {err}")
            });
        assert_eq!(timeout.hook, "_rift.script");
        assert_eq!(timeout.timeout_ms, 200, "reports the configured deadline");
        assert!(
            start.elapsed() < Duration::from_secs(3),
            "must return near the configured timeout, not hang"
        );
    }

    // AC2: the deadline honors the configured timeout, not a hardcoded larger default.
    #[tokio::test]
    async fn bounded_honors_configured_timeout() {
        let start = Instant::now();
        let _ = bounded("rhai", RUNAWAY_RHAI, 250).await;
        let elapsed = start.elapsed();
        assert!(
            elapsed >= Duration::from_millis(200),
            "must not return before the configured timeout: {elapsed:?}"
        );
        assert!(
            elapsed < Duration::from_secs(2),
            "must return at ~the configured timeout, not a 5s default: {elapsed:?}"
        );
    }

    // AC3: a runaway script must not starve the async runtime — a concurrent tokio timer
    // makes progress and completes well before the script's (much longer) timeout.
    #[tokio::test]
    async fn runaway_does_not_starve_async_runtime() {
        let script = tokio::spawn(bounded("rhai", RUNAWAY_RHAI, 4000));

        // This timer must fire promptly while the script is still running.
        let timer_start = Instant::now();
        tokio::time::sleep(Duration::from_millis(300)).await;
        let timer_elapsed = timer_start.elapsed();
        assert!(
            timer_elapsed < Duration::from_secs(1),
            "async runtime is starved by the runaway script: timer took {timer_elapsed:?}"
        );

        // Let the script's own deadline clean it up.
        let _ = script.await;
    }

    // AC4: a normal (fast) Rhai respond(ctx) still returns the correct decision, unchanged.
    #[tokio::test]
    async fn normal_rhai_returns_error_decision() {
        let code = r#"fn respond(ctx) { http(503, "boom") }"#;
        let res = bounded("rhai", code, 2000)
            .await
            .expect("fast script succeeds");
        match res {
            FaultDecision::Error { status, body, .. } => {
                assert_eq!(status, 503);
                assert_eq!(body, "boom");
            }
            other => panic!("expected Error decision, got {other:?}"),
        }
    }

    // Issue #360 Item 3: the traced variant captures the decision, duration, and ctx.logger
    // lines from a single run, without changing the decision itself.
    #[tokio::test]
    async fn traced_variant_captures_decision_duration_and_logs() {
        let code = r#"
            fn respond(ctx) {
                ctx.logger.info("about to respond");
                http(503, "boom")
            }
        "#;
        let (result, entry) = should_inject_bounded_with_ctx_traced(
            "rhai".into(),
            code.into(),
            "t".into(),
            req(),
            store(),
            Duration::from_millis(2000),
            ScriptCtxExtras::default(),
        )
        .await;
        match result {
            Ok(FaultDecision::Error { status, .. }) => assert_eq!(status, 503),
            other => panic!("expected Error decision, got {other:?}"),
        }
        assert_eq!(entry.hook, "respond");
        assert_eq!(entry.decision, "http(503) body=\"boom\"");
        assert_eq!(entry.logs, vec!["about to respond".to_string()]);
    }

    // A timeout still produces a trace entry (best-effort: no logs, an error decision string),
    // instead of panicking or losing the timeout error.
    #[tokio::test]
    async fn traced_variant_reports_timeout() {
        let (result, entry) = should_inject_bounded_with_ctx_traced(
            "rhai".into(),
            RUNAWAY_RHAI.into(),
            "t".into(),
            req(),
            store(),
            Duration::from_millis(150),
            ScriptCtxExtras::default(),
        )
        .await;
        assert!(result.is_err(), "runaway must time out, not hang");
        assert!(
            entry.decision.starts_with("error:"),
            "got {}",
            entry.decision
        );
    }

    // =====================================================================================
    // Issue #476: Mountebank response-inject hook runs off the async worker with a
    // wall-clock deadline, through the same spawn_blocking + timeout shape as `_rift.script`.
    // =====================================================================================
    #[cfg(feature = "javascript")]
    mod mb_inject {
        use super::*;
        use crate::scripting::{MountebankRequest, execute_mountebank_inject_bounded};
        use std::sync::atomic::AtomicU32;

        // Fresh port per test, range disjoint from js_engine.rs and imposter/response.rs test
        // ranges; each test's state is its own `ScriptScope`.
        fn test_port() -> u16 {
            static NEXT: AtomicU32 = AtomicU32::new(42_500);
            NEXT.fetch_add(1, Ordering::Relaxed) as u16
        }

        fn mb_req(path: &str) -> MountebankRequest {
            MountebankRequest {
                method: "GET".to_string(),
                path: path.to_string(),
                query: Default::default(),
                headers: crate::util::OrderedMap::default(),
                body: None,
                mode: Some(ResponseMode::Text),
                ..Default::default()
            }
        }

        // Busy-loops long enough that a small wall-clock deadline always fires first; the
        // loop-iteration cap (#327) later frees the blocking thread.
        const SLOW_INJECT: &str = "function (config) { var i = 0; while (i < 100000000) { i += 1; } return { statusCode: 200 }; }";

        // AC1 (happy): a fast inject returns its response through the bounded path.
        #[tokio::test]
        async fn mb_inject_bounded_returns_response() {
            let resp = execute_mountebank_inject_bounded(
                "function (config) { return { statusCode: 201, body: 'from-inject' }; }".into(),
                mb_req("/a"),
                ScriptScope::detached(test_port()),
                None,
                std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
                Duration::from_millis(60_000),
            )
            .await
            .expect("fast inject");
            assert_eq!(
                resp.status_code,
                Some(crate::behaviors::ResponseStatus::Code(201))
            );
            assert_eq!(resp.body_text(), "from-inject");
        }

        // AC1: a runaway inject yields a timeout error near the deadline instead of blocking
        // a runtime worker for its full duration.
        #[tokio::test]
        async fn mb_inject_bounded_times_out() {
            let start = Instant::now();
            let res = execute_mountebank_inject_bounded(
                SLOW_INJECT.into(),
                mb_req("/hang"),
                ScriptScope::detached(test_port()),
                None,
                std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
                Duration::from_millis(25),
            )
            .await;
            let Err(err) = res else {
                panic!("runaway inject must yield an error, not a response")
            };
            let timeout = err
                .downcast_ref::<crate::scripting::ScriptTimeoutError>()
                .unwrap_or_else(|| {
                    panic!("a runaway inject must yield a ScriptTimeoutError; got: {err}")
                });
            assert_eq!(timeout.hook, "inject");
            assert_eq!(timeout.timeout_ms, 25, "reports the configured deadline");
            assert!(
                start.elapsed() < Duration::from_secs(3),
                "must return near the configured deadline, not after the loop cap"
            );
        }

        // AC4: per-imposter script state persists across bounded runs — the get→run→save
        // plumbing (issue #477 locking included) follows execution to the blocking thread.
        #[tokio::test]
        async fn mb_inject_bounded_state_persists_across_calls() {
            let port = test_port();
            let scope = ScriptScope::detached(port);
            let incr = "function (config) { config.state.count = (config.state.count || 0) + 1; return { statusCode: 200, body: String(config.state.count) }; }";
            let first = execute_mountebank_inject_bounded(
                incr.into(),
                mb_req("/count"),
                scope.clone(),
                None,
                std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
                Duration::from_millis(60_000),
            )
            .await
            .expect("first run");
            let second = execute_mountebank_inject_bounded(
                incr.into(),
                mb_req("/count"),
                scope.clone(),
                None,
                std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
                Duration::from_millis(60_000),
            )
            .await
            .expect("second run");
            assert_eq!(first.body_text(), "1");
            assert_eq!(
                second.body_text(),
                "2",
                "imposter state must persist across pool-thread runs"
            );
        }
    }
}