rill-runtime 0.9.0

Signed-model local runtime and IPC server for RillML.
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
//! Integration tests for the sandboxed WASM InvokeHandler.
//!
//! These tests require a pre-built echo-handler WASM component. Set the
//! `ECHO_HANDLER_WASM` environment variable to the component path, or place
//! the component at `handlers/echo-handler/target/wasm32-unknown-unknown/release/echo-handler.wasm`
//! relative to the workspace root.
//!
//! In CI, the `wasm-handler` job builds the component before running these
//! tests. Local developers can build it manually:
//!
//! ```bash
//! cd handlers/echo-handler
//! cargo build --release --target wasm32-unknown-unknown
//! wasm-tools component new target/wasm32-unknown-unknown/release/echo-handler.wasm \
//!   -o echo-handler.wasm
//! export ECHO_HANDLER_WASM="$PWD/echo-handler.wasm"
//! ```
//!
//! The sandbox attack tests (R-020) also require the malicious test handler
//! component, built from `handlers/test-malicious-handler/`:
//!
//! ```bash
//! cd handlers/test-malicious-handler
//! cargo build --release --target wasm32-unknown-unknown
//! wasm-tools component new target/wasm32-unknown-unknown/release/test-malicious-handler.wasm \
//!   -o ../../target/test-malicious-handler.wasm
//! ```

#![cfg(feature = "wasm")]

use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;

use ed25519_dalek::SigningKey;
use ed25519_dalek::VerifyingKey;
use rill_runtime::{
    InvokeErrorKind, InvokeHandler, LoadedHandlerPack, TrustStore, WasmInvokeHandler,
    build_signed_handler_pack, load_handler_pack,
};
use rill_runtime_protocol::{
    HANDLER_API_VERSION, HANDLER_PACKAGE_FORMAT_VERSION, HandlerPackManifest,
};
use sha2::{Digest, Sha256};

/// Returns the echo handler WASM component path, or `None` if not available.
fn echo_handler_component() -> Option<PathBuf> {
    if let Ok(path) = std::env::var("ECHO_HANDLER_WASM") {
        let path = PathBuf::from(path);
        if path.exists() {
            return Some(path);
        }
    }
    // Try default paths relative to CARGO_MANIFEST_DIR (crates/rill-runtime).
    // 1. Component built by CI / `wasm-tools component new` at workspace target.
    // 2. Component built locally next to the echo-handler Cargo.toml.
    let workspace_target =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/echo-handler.wasm");
    if workspace_target.exists() {
        return Some(workspace_target);
    }
    let local_component = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../handlers/echo-handler/echo-handler.wasm");
    if local_component.exists() {
        return Some(local_component);
    }
    None
}

/// Builds a signed `.rillhandler` pack from the echo handler component.
fn build_echo_pack(module: &[u8], signing: &SigningKey) -> Vec<u8> {
    let manifest = HandlerPackManifest {
        format_version: HANDLER_PACKAGE_FORMAT_VERSION,
        id: "rillml.echo.handler".into(),
        version: env!("CARGO_PKG_VERSION").into(),
        handler_api_version: HANDLER_API_VERSION,
        min_runtime_version: env!("CARGO_PKG_VERSION").into(),
        publisher_key_id: "wasm-test-key".into(),
        capabilities: vec!["rillml.linearRegression.predict".into()],
        module_sha256: hex::encode(Sha256::digest(module)),
        module_size: module.len() as u64,
    };
    build_signed_handler_pack(&manifest, module, signing).unwrap()
}

fn load_echo_pack(
    pack_bytes: &[u8],
    verifying: &VerifyingKey,
) -> (LoadedHandlerPack, rill_runtime::HandlerPackInspection) {
    let trust = TrustStore(BTreeMap::from([("wasm-test-key".into(), *verifying)]));
    load_handler_pack(std::io::Cursor::new(pack_bytes), &trust).unwrap()
}

#[test]
fn echo_handler_invoke_returns_input() {
    let component = match echo_handler_component() {
        Some(path) => fs::read(&path).unwrap(),
        None => {
            eprintln!("skipping: echo handler component not built (set ECHO_HANDLER_WASM)");
            return;
        }
    };

    let signing = SigningKey::from_bytes(&[7; 32]);
    let pack_bytes = build_echo_pack(&component, &signing);
    let (loaded, inspection) = load_echo_pack(&pack_bytes, &signing.verifying_key());
    assert_eq!(inspection.id, "rillml.echo.handler");
    assert!(inspection.signature_verified);

    let model = serde_json::json!({"kind": "linearRegression", "weights": [0.5], "intercept": 0.0});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let input = serde_json::json!({"features": [1.0, 2.0]});
    let output = handler
        .invoke("rillml.linearRegression.predict", &input)
        .unwrap();
    // Echo handler returns the input as output.
    assert_eq!(output, input);
}

#[test]
fn echo_handler_rejects_unsupported_capability() {
    let component = match echo_handler_component() {
        Some(path) => fs::read(&path).unwrap(),
        None => {
            eprintln!("skipping: echo handler component not built (set ECHO_HANDLER_WASM)");
            return;
        }
    };

    let signing = SigningKey::from_bytes(&[7; 32]);
    let pack_bytes = build_echo_pack(&component, &signing);
    let (loaded, _) = load_echo_pack(&pack_bytes, &signing.verifying_key());

    let model = serde_json::json!({"kind": "linearRegression"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let result = handler.invoke("rillml.unknown.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    // Unsupported capability is reported by the guest via the WIT
    // `handler-error` `unsupported-capability` variant, which the host
    // collapses to `ExecutionFailed` with the guest detail kept
    // host-side only.
    assert!(
        matches!(error.kind(), InvokeErrorKind::ExecutionFailed),
        "expected ExecutionFailed, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerInternalError");
    // The guest-supplied detail must not appear in the public message.
    assert!(!error.public_message().contains("UnsupportedCapability"));
    assert!(!error.public_message().contains("unsupported"));
}

#[test]
fn echo_handler_metadata_mismatch_rejected() {
    let component = match echo_handler_component() {
        Some(path) => fs::read(&path).unwrap(),
        None => {
            eprintln!("skipping: echo handler component not built (set ECHO_HANDLER_WASM)");
            return;
        }
    };

    // Build a pack with a different handler id than what the guest reports.
    let signing = SigningKey::from_bytes(&[7; 32]);
    let manifest = HandlerPackManifest {
        format_version: HANDLER_PACKAGE_FORMAT_VERSION,
        id: "wrong.handler.id".into(), // mismatched
        version: env!("CARGO_PKG_VERSION").into(),
        handler_api_version: HANDLER_API_VERSION,
        min_runtime_version: env!("CARGO_PKG_VERSION").into(),
        publisher_key_id: "wasm-test-key".into(),
        capabilities: vec!["rillml.linearRegression.predict".into()],
        module_sha256: hex::encode(Sha256::digest(&component)),
        module_size: component.len() as u64,
    };
    let pack_bytes = build_signed_handler_pack(&manifest, &component, &signing).unwrap();
    let trust = TrustStore(BTreeMap::from([(
        "wasm-test-key".into(),
        signing.verifying_key(),
    )]));
    let (loaded, _) = load_handler_pack(std::io::Cursor::new(&pack_bytes), &trust).unwrap();

    let model = serde_json::json!({});
    let result = WasmInvokeHandler::new(&loaded, &model);
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error, rill_runtime::HandlerLoadError::MetadataMismatch(_)),
        "expected MetadataMismatch, got: {error:?}"
    );
}

/// Verifies the oversized output protection enforced by the WasmInvokeHandler.
///
/// Building a malicious WASM component that produces oversized output is
/// complex, so this test instead documents and verifies the limit constant.
/// The actual check lives in `handler/wasm.rs` around the `invoke`
/// implementation: any `output_bytes` exceeding `MAX_IO_BYTES` produces a
/// `handlerOutputTooLarge` error. `MAX_IO_BYTES` bounds both input and output
/// JSON payloads (the IPC limit is shared).
#[test]
fn wasm_handler_rejects_oversized_output() {
    use rill_runtime::handler::wasm::MAX_IO_BYTES;
    // 1 MiB, matching the IPC limit per HANDLER-RFC §5.
    assert_eq!(MAX_IO_BYTES, 1024 * 1024);
}

/// Verifies all WASM sandbox limits match HANDLER-RFC §5.
///
/// This test documents the expected limits and catches accidental changes that
/// could weaken the sandbox. The limits are enforced by `WasmInvokeHandler`
/// via Wasmtime config (fuel, epoch interruption) and a `ResourceLimiter`
/// (memory/table growth).
#[test]
fn wasm_handler_sandbox_limits_verified() {
    use rill_runtime::handler::wasm::{
        CONFIGURE_FUEL, EPOCH_DEADLINE, EPOCH_TICK_INTERVAL, INVOKE_FUEL, MAX_IO_BYTES,
        MAX_MEMORY_BYTES, MAX_TABLE_ELEMENTS,
    };
    use std::time::Duration;

    // Fuel budgets per call.
    assert_eq!(CONFIGURE_FUEL, 10_000_000);
    assert_eq!(INVOKE_FUEL, 100_000_000);
    // Memory and table caps per instance.
    assert_eq!(MAX_MEMORY_BYTES, 64 * 1024 * 1024);
    assert_eq!(MAX_TABLE_ELEMENTS, 10_000);
    // Input/output JSON payload cap (1 MiB, matches IPC limit).
    assert_eq!(MAX_IO_BYTES, 1024 * 1024);
    // Epoch interruption: 1-second tick, 5-tick deadline (5s wall-clock).
    assert_eq!(EPOCH_TICK_INTERVAL, Duration::from_secs(1));
    assert_eq!(EPOCH_DEADLINE, 5);
}

// ----- R-020: WASM sandbox attack tests -----
//
// These tests use the malicious test handler (`handlers/test-malicious-handler/`)
// which accepts a `"mode"` field in the model JSON to control its behavior.
// Each test loads the handler with a specific mode and verifies that the
// sandbox correctly rejects the malicious behavior with the expected IPC
// error code.

/// Returns the malicious handler WASM component path, or `None` if not available.
fn malicious_handler_component() -> Option<PathBuf> {
    if let Ok(path) = std::env::var("MALICIOUS_HANDLER_WASM") {
        let path = PathBuf::from(path);
        if path.exists() {
            return Some(path);
        }
    }
    let workspace_target =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/test-malicious-handler.wasm");
    if workspace_target.exists() {
        return Some(workspace_target);
    }
    None
}

/// Build a signed `.rillhandler` pack from the malicious handler component.
fn build_malicious_handler_pack(module: &[u8], signing: &SigningKey) -> Vec<u8> {
    let manifest = HandlerPackManifest {
        format_version: HANDLER_PACKAGE_FORMAT_VERSION,
        id: "rillml.test.malicious".into(),
        version: env!("CARGO_PKG_VERSION").into(),
        handler_api_version: HANDLER_API_VERSION,
        min_runtime_version: env!("CARGO_PKG_VERSION").into(),
        publisher_key_id: "wasm-test-key".into(),
        capabilities: vec!["rillml.linearRegression.predict".into()],
        module_sha256: hex::encode(Sha256::digest(module)),
        module_size: module.len() as u64,
    };
    build_signed_handler_pack(&manifest, module, signing).unwrap()
}

fn load_malicious_handler_pack(pack_bytes: &[u8], verifying: &VerifyingKey) -> LoadedHandlerPack {
    let trust = TrustStore(BTreeMap::from([("wasm-test-key".into(), *verifying)]));
    let (loaded, _) = load_handler_pack(std::io::Cursor::new(pack_bytes), &trust).unwrap();
    loaded
}

/// Helper to read the malicious handler component, build a pack, and load it.
/// Returns `(loaded, signing_key)` or skips the test if the component is not
/// available.
fn prepare_malicious_handler() -> Option<(LoadedHandlerPack, SigningKey)> {
    let component = match malicious_handler_component() {
        Some(path) => fs::read(&path).unwrap(),
        None => {
            eprintln!(
                "skipping: malicious handler component not built (set MALICIOUS_HANDLER_WASM)"
            );
            return None;
        }
    };
    let signing = SigningKey::from_bytes(&[8; 32]);
    let pack_bytes = build_malicious_handler_pack(&component, &signing);
    let loaded = load_malicious_handler_pack(&pack_bytes, &signing.verifying_key());
    Some((loaded, signing))
}

#[test]
fn wasm_handler_trap_returns_handler_trap_error() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // Configure the handler to execute `unreachable` on invoke.
    let model = serde_json::json!({"mode": "trap"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::Trap),
        "expected Trap, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerTrap");
    assert_eq!(error.public_message(), "handler trapped");
    // The trap detail (which may include a wasmtime backtrace) must not
    // appear in the public message or stable code.
    assert!(!error.public_message().contains("unreachable"));
    assert!(!error.stable_code().contains("unreachable"));
}

#[test]
fn wasm_handler_oversized_output_returns_output_too_large() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // Configure the handler to return >1 MiB JSON output.
    let model = serde_json::json!({"mode": "oversized-output"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::OutputTooLarge),
        "expected OutputTooLarge, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerOutputTooLarge");
}

#[test]
fn wasm_handler_invalid_json_output_returns_invalid_output() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // Configure the handler to return invalid JSON bytes.
    let model = serde_json::json!({"mode": "invalid-json"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::InvalidOutput),
        "expected InvalidOutput, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerInvalidOutput");
}

#[test]
fn wasm_handler_infinite_loop_returns_timeout() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // Configure the handler to loop forever. The epoch interruption (5s
    // deadline) must terminate the call and return handlerTimeout.
    let model = serde_json::json!({"mode": "infinite-loop"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let start = std::time::Instant::now();
    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    let elapsed = start.elapsed();

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::Timeout),
        "expected Timeout, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerTimeout");
    assert!(error.retryable());
    // The epoch deadline is 5 seconds; the call must be interrupted within
    // a reasonable window after that (allow 10s for CI overhead).
    assert!(
        elapsed.as_secs() < 15,
        "infinite loop took too long to interrupt: {elapsed:?}"
    );
}

#[test]
fn wasm_handler_echo_mode_works_as_baseline() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // Verify the malicious handler in "echo" mode behaves correctly.
    // This confirms the test fixture itself is valid before testing attacks.
    let model = serde_json::json!({"mode": "echo"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let input = serde_json::json!({"features": [1.0, 2.0]});
    let output = handler
        .invoke("rillml.linearRegression.predict", &input)
        .unwrap();
    assert_eq!(output, input);
}

/// Verifies the WASM store remains usable after a non-trap error.
///
/// After `OutputTooLarge` (host-side size check on the returned bytes), the
/// underlying Wasmtime `Store` is in a clean state and the same handler
/// instance can be invoked again. The malicious handler's `oversized-output`
/// mode caches the oversized buffer in a `thread_local` and consumes it on
/// the first `invoke` call, so the second call returns `ExecutionFailed`
/// (because the cache is empty). The important assertion is that the second
/// call returns a typed error rather than panicking, hanging, or returning
/// a permanent `Trap`.
#[test]
fn wasm_handler_remains_usable_after_output_too_large() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    let model = serde_json::json!({"mode": "oversized-output"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    // First invoke: oversized output → OutputTooLarge.
    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(matches!(error.kind(), InvokeErrorKind::OutputTooLarge));

    // Second invoke: the thread_local cache is now empty, so the guest
    // returns `ExecutionFailed`. The store is still usable — the call
    // completes and returns a typed error rather than hanging or trapping.
    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::ExecutionFailed),
        "expected ExecutionFailed on second call, got: {:?}",
        error.kind()
    );
}

/// Verifies that one handler instance's failure does not affect another.
///
/// Each `WasmInvokeHandler` owns its own `Engine`, `Store`, and epoch
/// ticker thread, so a malicious handler that traps or loops forever
/// cannot poison the runtime for other handlers. This test creates a
/// trap-mode handler, confirms it returns `Trap`, then creates a fresh
/// echo-mode handler and confirms it works.
#[test]
fn wasm_handler_failure_does_not_affect_other_instances() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    // First handler: traps on every invoke.
    let trap_model = serde_json::json!({"mode": "trap"});
    let trap_handler = WasmInvokeHandler::new(&loaded, &trap_model).unwrap();
    let result = trap_handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(matches!(result.unwrap_err().kind(), InvokeErrorKind::Trap));

    // Second handler: echo mode. Must work despite the first handler's trap.
    let echo_model = serde_json::json!({"mode": "echo"});
    let echo_handler = WasmInvokeHandler::new(&loaded, &echo_model).unwrap();
    let input = serde_json::json!({"features": [3.0, 4.0]});
    let output = echo_handler
        .invoke("rillml.linearRegression.predict", &input)
        .unwrap();
    assert_eq!(output, input);
}

/// Verifies that an infinite loop in `configure()` is bounded by the
/// epoch deadline and returns a load error (instead of hanging forever).
///
/// The malicious handler's `configure-infinite-loop` mode calls
/// `burn_forever()` inside `configure()`. The host sets an independent
/// fuel budget and epoch deadline on the `configure()` stage (see
/// `handler/wasm.rs` stage 3), so the call must be interrupted within a
/// reasonable window of the 5-second deadline. Because `configure()`
/// runs inside `WasmInvokeHandler::new`, the failure surfaces as a
/// `HandlerLoadError::Init` rather than an `InvokeError`.
#[test]
fn wasm_handler_configure_infinite_loop_returns_timeout() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    let model = serde_json::json!({"mode": "configure-infinite-loop"});
    let start = std::time::Instant::now();
    let result = WasmInvokeHandler::new(&loaded, &model);
    let elapsed = start.elapsed();

    assert!(
        result.is_err(),
        "configure-infinite-loop must fail handler load"
    );
    let err = result.unwrap_err();
    assert!(
        matches!(err, rill_runtime::HandlerLoadError::Init(ref msg)
            if msg.contains("configure trap")),
        "expected HandlerLoadError::Init mentioning configure trap, got: {err:?}"
    );
    // The epoch deadline is 5 seconds; the load must fail within a
    // reasonable window of that (allow 15s for CI overhead).
    assert!(
        elapsed.as_secs() < 15,
        "configure infinite loop took too long to interrupt: {elapsed:?}"
    );
}

/// Verifies that a guest-supplied oversized error detail string is
/// truncated by the host before being stored on `InvokeError`.
///
/// The malicious handler's `long-error-string` mode returns
/// `HandlerError::ExecutionFailed` with a 16 KiB detail payload. The
/// host's `InvokeError::with_detail` truncates the detail to
/// `MAX_DETAIL_BYTES` (4 KiB) on a UTF-8 char boundary, bounding host
/// memory and stderr noise. The stored detail must not exceed the limit.
#[test]
fn wasm_handler_long_error_string_is_truncated() {
    use rill_runtime::InvokeError;
    use rill_runtime::MAX_DETAIL_BYTES;

    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    let model = serde_json::json!({"mode": "long-error-string"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    assert!(result.is_err());
    let error: InvokeError = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::ExecutionFailed),
        "expected ExecutionFailed, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerInternalError");
    // The guest attempted to exfiltrate 16 KiB; the host must have
    // truncated the stored detail to <= MAX_DETAIL_BYTES.
    let detail = error
        .detail()
        .expect("ExecutionFailed with detail must store host-only detail");
    assert!(
        detail.len() <= MAX_DETAIL_BYTES,
        "detail length {} must not exceed MAX_DETAIL_BYTES {}",
        detail.len(),
        MAX_DETAIL_BYTES
    );
    // The host stores the guest error using its `Debug` representation
    // (`HandlerError::ExecutionFailed("XXXX...")`). After truncation the
    // detail must still start with the variant prefix and contain a large
    // run of 'X' characters from the original 16 KiB payload, proving the
    // guest-controlled string was captured but bounded. The truncation
    // must land on a UTF-8 char boundary (all-'X' is ASCII, so any byte
    // offset is a valid char boundary).
    assert!(
        detail.starts_with("HandlerError::ExecutionFailed(\""),
        "detail must start with the Debug prefix, got: {detail:?}"
    );
    let x_count = detail.chars().filter(|c| *c == 'X').count();
    assert!(
        x_count >= MAX_DETAIL_BYTES - 64,
        "expected at least {} 'X' characters from the guest payload, got {x_count}",
        MAX_DETAIL_BYTES - 64
    );
    // The public message must be the fixed constant, not the payload.
    assert_eq!(error.public_message(), "handler execution failed");
    assert!(!error.public_message().contains("X"));
}

/// Verifies that a handler performing dense floating-point work that
/// exhausts the invoke fuel budget is interrupted and returns a
/// `Timeout` error.
///
/// The malicious handler's `fuel-exhaustion` mode performs real
/// arithmetic in a tight loop (rather than an empty `wrapping_add`
/// loop), exercising fuel accounting for numeric instructions. The
/// epoch deadline remains the authoritative wall-clock guard, but fuel
/// exhaustion alone (without an explicit `loop {}`) must also terminate
/// the call.
#[test]
fn wasm_handler_fuel_exhaustion_returns_timeout() {
    let (loaded, _) = match prepare_malicious_handler() {
        Some(v) => v,
        None => return,
    };

    let model = serde_json::json!({"mode": "fuel-exhaustion"});
    let handler = WasmInvokeHandler::new(&loaded, &model).unwrap();

    let start = std::time::Instant::now();
    let result = handler.invoke("rillml.linearRegression.predict", &serde_json::json!({}));
    let elapsed = start.elapsed();

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(
        matches!(error.kind(), InvokeErrorKind::Timeout),
        "expected Timeout for fuel exhaustion, got: {:?}",
        error.kind()
    );
    assert_eq!(error.stable_code(), "handlerTimeout");
    assert!(error.retryable());
    assert!(
        elapsed.as_secs() < 15,
        "fuel exhaustion took too long to interrupt: {elapsed:?}"
    );
}