rill-runtime 1.0.0-rc.3

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
use std::{
    fs,
    io::Write,
    process::{Command, Stdio},
};

use ed25519_dalek::SigningKey;
use rill_runtime::{LINEAR_REGRESSION_CAPABILITY, build_signed_model_pack};
use rill_runtime_protocol::{
    MODEL_PACK_FORMAT_VERSION, ModelPackManifest, RUNTIME_API_VERSION, RuntimeRequest,
    RuntimeResponse, RuntimeResponseV2,
};

// Imports only needed by the `wasm`-gated cross-process WASM handler test.
#[cfg(feature = "wasm")]
use rill_runtime::build_signed_handler_pack;
#[cfg(feature = "wasm")]
use rill_runtime_protocol::{
    HANDLER_API_VERSION, HANDLER_PACKAGE_FORMAT_VERSION, HandlerPackManifest,
};
#[cfg(feature = "wasm")]
use sha2::{Digest, Sha256};
#[cfg(feature = "wasm")]
use std::path::PathBuf;

#[test]
fn signed_pack_handshake_and_invoke_work_across_the_real_process_boundary() {
    let signing = SigningKey::from_bytes(&[5; 32]);
    let manifest = ModelPackManifest {
        format_version: MODEL_PACK_FORMAT_VERSION,
        id: "rillml.example.default".into(),
        version: "0.7.0".into(),
        runtime_api_version: RUNTIME_API_VERSION,
        min_runtime_version: "0.7.0".into(),
        publisher_key_id: "process-test".into(),
        capabilities: vec![LINEAR_REGRESSION_CAPABILITY.into()],
    };
    let model = serde_json::json!({
        "kind": "linearRegression",
        "weights": [0.5, -0.25],
        "intercept": 1.0
    });
    let pack = build_signed_model_pack(&manifest, &model, &signing).unwrap();
    let temporary = tempfile::tempdir().unwrap();
    let pack_path = temporary.path().join("example.rillpack");
    fs::write(&pack_path, pack).unwrap();

    let trust = format!(
        "process-test={}",
        hex::encode(signing.verifying_key().to_bytes())
    );
    let mut child = Command::new(env!("CARGO_BIN_EXE_rill-runtime"))
        .args(["serve", "--pack"])
        .arg(&pack_path)
        .args(["--trust-key", &trust])
        .args(["--builtin-handler", "linear-regression"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let requests = [
        RuntimeRequest::Handshake {
            request_id: "integration-handshake".into(),
            api_version: RUNTIME_API_VERSION,
            client_name: "runtime-process-test".into(),
            client_version: "0.7.0".into(),
        },
        RuntimeRequest::Invoke {
            request_id: "integration-invoke".into(),
            api_version: RUNTIME_API_VERSION,
            capability: LINEAR_REGRESSION_CAPABILITY.into(),
            input: serde_json::json!({"features": [4.0, 2.0]}),
        },
    ];
    let mut stdin = child.stdin.take().unwrap();
    for request in requests {
        serde_json::to_writer(&mut stdin, &request).unwrap();
        stdin.write_all(b"\n").unwrap();
    }
    drop(stdin);

    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let responses = output
        .stdout
        .split(|byte| *byte == b'\n')
        .filter(|line| !line.is_empty())
        .map(|line| serde_json::from_slice::<RuntimeResponseV2>(line).unwrap())
        .collect::<Vec<_>>();
    assert_eq!(responses.len(), 2);
    assert!(matches!(
        &responses[0],
        RuntimeResponseV2::Handshake {
            request_id,
            model_pack_id,
            handler_id,
            ..
        } if request_id == "integration-handshake"
            && model_pack_id == "rillml.example.default"
            && handler_id == "rillml.builtin.linear-regression"
    ));
    assert!(matches!(
        &responses[1],
        RuntimeResponseV2::Result {
            request_id,
            output,
            ..
        } if request_id == "integration-invoke" && output["prediction"] == 2.5
    ));
}

#[test]
fn v1_client_receives_v1_wire_format() {
    let signing = SigningKey::from_bytes(&[6; 32]);
    let manifest = ModelPackManifest {
        format_version: MODEL_PACK_FORMAT_VERSION,
        id: "rillml.example.default".into(),
        version: "0.7.0".into(),
        runtime_api_version: RUNTIME_API_VERSION,
        min_runtime_version: "0.7.0".into(),
        publisher_key_id: "v1-test".into(),
        capabilities: vec![LINEAR_REGRESSION_CAPABILITY.into()],
    };
    let model = serde_json::json!({
        "kind": "linearRegression",
        "weights": [1.0],
        "intercept": 0.0
    });
    let pack = build_signed_model_pack(&manifest, &model, &signing).unwrap();
    let temporary = tempfile::tempdir().unwrap();
    let pack_path = temporary.path().join("v1-test.rillpack");
    fs::write(&pack_path, pack).unwrap();

    let trust = format!(
        "v1-test={}",
        hex::encode(signing.verifying_key().to_bytes())
    );
    let mut child = Command::new(env!("CARGO_BIN_EXE_rill-runtime"))
        .args(["serve", "--pack"])
        .arg(&pack_path)
        .args(["--trust-key", &trust])
        .args(["--builtin-handler", "linear-regression"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    // Send a v1 handshake (api_version=1).
    let v1_request = r#"{"method":"handshake","requestId":"v1-client","apiVersion":1,"clientName":"v1-test","clientVersion":"0.6.0"}"#;
    let mut stdin = child.stdin.take().unwrap();
    stdin.write_all(v1_request.as_bytes()).unwrap();
    stdin.write_all(b"\n").unwrap();
    drop(stdin);

    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let response_line = output
        .stdout
        .split(|b| *b == b'\n')
        .find(|l| !l.is_empty())
        .unwrap();
    let response: RuntimeResponse = serde_json::from_slice(response_line).unwrap();
    assert!(matches!(
        response,
        RuntimeResponse::Handshake { request_id, .. } if request_id == "v1-client"
    ));
    // V1 response must not contain handler fields.
    let json = std::str::from_utf8(response_line).unwrap();
    assert!(!json.contains("handlerId"));
    assert!(!json.contains("effectiveCapabilities"));
}

// ----- R-021: compatibility tests -----

/// Returns the echo handler WASM component path, or `None` if not available.
#[cfg(feature = "wasm")]
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);
        }
    }
    let workspace_target =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/echo-handler.wasm");
    if workspace_target.exists() {
        return Some(workspace_target);
    }
    None
}

#[test]
fn builtin_handler_deprecation_notice_printed() {
    // Starting the runtime with --builtin-handler linear-regression must print
    // a deprecation notice on stderr, guiding users toward --handler.
    let signing = SigningKey::from_bytes(&[51; 32]);
    let manifest = ModelPackManifest {
        format_version: MODEL_PACK_FORMAT_VERSION,
        id: "rillml.example.default".into(),
        version: "0.7.0".into(),
        runtime_api_version: RUNTIME_API_VERSION,
        min_runtime_version: "0.7.0".into(),
        publisher_key_id: "deprecate-test".into(),
        capabilities: vec![LINEAR_REGRESSION_CAPABILITY.into()],
    };
    let model = serde_json::json!({
        "kind": "linearRegression",
        "weights": [1.0],
        "intercept": 0.0
    });
    let pack = build_signed_model_pack(&manifest, &model, &signing).unwrap();
    let temporary = tempfile::tempdir().unwrap();
    let pack_path = temporary.path().join("deprecate.rillpack");
    fs::write(&pack_path, pack).unwrap();

    let trust = format!(
        "deprecate-test={}",
        hex::encode(signing.verifying_key().to_bytes())
    );
    let mut child = Command::new(env!("CARGO_BIN_EXE_rill-runtime"))
        .args(["serve", "--pack"])
        .arg(&pack_path)
        .args(["--trust-key", &trust])
        .args(["--builtin-handler", "linear-regression"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // Send a handshake so the process can exit cleanly.
    let request = RuntimeRequest::Handshake {
        request_id: "deprecate-notice-test".into(),
        api_version: RUNTIME_API_VERSION,
        client_name: "deprecate-test".into(),
        client_version: "0.7.0".into(),
    };
    let mut stdin = child.stdin.take().unwrap();
    serde_json::to_writer(&mut stdin, &request).unwrap();
    stdin.write_all(b"\n").unwrap();
    drop(stdin);

    let output = child.wait_with_output().unwrap();
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("deprecated"),
        "expected deprecation notice on stderr, got: {stderr}"
    );
}

#[test]
#[cfg(feature = "wasm")]
fn wasm_handler_handshake_across_process_boundary() {
    // End-to-end test: start the runtime with a signed .rillhandler (WASM
    // echo handler), send a v2 handshake + invoke, and verify the response.
    // This covers the cross-process WASM handler path that is distinct from
    // the built-in handler path tested above.
    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 signed model pack.
    let model_signing = SigningKey::from_bytes(&[52; 32]);
    let model_manifest = ModelPackManifest {
        format_version: MODEL_PACK_FORMAT_VERSION,
        id: "rillml.example.default".into(),
        version: "0.7.0".into(),
        runtime_api_version: RUNTIME_API_VERSION,
        min_runtime_version: "0.7.0".into(),
        publisher_key_id: "wasm-process-model".into(),
        capabilities: vec!["rillml.linearRegression.predict".into()],
    };
    let model = serde_json::json!({
        "kind": "linearRegression",
        "weights": [0.5],
        "intercept": 0.0
    });
    let model_pack = build_signed_model_pack(&model_manifest, &model, &model_signing).unwrap();

    // Build a signed handler pack from the echo handler component.
    let handler_signing = SigningKey::from_bytes(&[53; 32]);
    let handler_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: "0.7.0".into(),
        publisher_key_id: "wasm-process-handler".into(),
        capabilities: vec!["rillml.linearRegression.predict".into()],
        module_sha256: hex::encode(Sha256::digest(&component)),
        module_size: component.len() as u64,
    };
    let handler_pack =
        build_signed_handler_pack(&handler_manifest, &component, &handler_signing).unwrap();

    let temporary = tempfile::tempdir().unwrap();
    let model_path = temporary.path().join("model.rillpack");
    let handler_path = temporary.path().join("echo.rillhandler");
    fs::write(&model_path, model_pack).unwrap();
    fs::write(&handler_path, handler_pack).unwrap();

    let model_trust = format!(
        "wasm-process-model={}",
        hex::encode(model_signing.verifying_key().to_bytes())
    );
    let handler_trust = format!(
        "wasm-process-handler={}",
        hex::encode(handler_signing.verifying_key().to_bytes())
    );

    let mut child = Command::new(env!("CARGO_BIN_EXE_rill-runtime"))
        .args(["serve", "--pack"])
        .arg(&model_path)
        .args(["--trust-key", &model_trust])
        .args(["--handler"])
        .arg(&handler_path)
        .args(["--handler-trust-key", &handler_trust])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let requests = [
        RuntimeRequest::Handshake {
            request_id: "wasm-process-handshake".into(),
            api_version: RUNTIME_API_VERSION,
            client_name: "wasm-process-test".into(),
            client_version: env!("CARGO_PKG_VERSION").into(),
        },
        RuntimeRequest::Invoke {
            request_id: "wasm-process-invoke".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.linearRegression.predict".into(),
            input: serde_json::json!({"features": [4.0, 2.0]}),
        },
    ];
    let mut stdin = child.stdin.take().unwrap();
    for request in requests {
        serde_json::to_writer(&mut stdin, &request).unwrap();
        stdin.write_all(b"\n").unwrap();
    }
    drop(stdin);

    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let responses = output
        .stdout
        .split(|byte| *byte == b'\n')
        .filter(|line| !line.is_empty())
        .map(|line| serde_json::from_slice::<RuntimeResponseV2>(line).unwrap())
        .collect::<Vec<_>>();
    assert_eq!(responses.len(), 2);
    // Handshake must report the WASM handler id (not the built-in id).
    assert!(matches!(
        &responses[0],
        RuntimeResponseV2::Handshake {
            request_id,
            handler_id,
            ..
        } if request_id == "wasm-process-handshake"
            && handler_id == "rillml.echo.handler"
    ));
    // Echo handler returns the input as output.
    assert!(matches!(
        &responses[1],
        RuntimeResponseV2::Result {
            request_id,
            output,
            ..
        } if request_id == "wasm-process-invoke"
            && output["features"] == serde_json::json!([4.0, 2.0])
    ));
}

#[test]
fn missing_handler_option_returns_error() {
    // 1.0 contract: when neither --handler nor --builtin-handler is passed,
    // the runtime must refuse to start. The previous behaviour silently fell
    // back to the deprecated built-in linear-regression handler, which
    // contradicted the 1.0 deprecation policy. This test pins the new
    // contract so a future regression cannot reintroduce the implicit
    // fallback.
    let signing = SigningKey::from_bytes(&[77; 32]);
    let manifest = ModelPackManifest {
        format_version: MODEL_PACK_FORMAT_VERSION,
        id: "rillml.example.default".into(),
        version: "0.7.0".into(),
        runtime_api_version: RUNTIME_API_VERSION,
        min_runtime_version: "0.7.0".into(),
        publisher_key_id: "missing-handler-test".into(),
        capabilities: vec![LINEAR_REGRESSION_CAPABILITY.into()],
    };
    let model = serde_json::json!({
        "kind": "linearRegression",
        "weights": [1.0],
        "intercept": 0.0
    });
    let pack = build_signed_model_pack(&manifest, &model, &signing).unwrap();
    let temporary = tempfile::tempdir().unwrap();
    let pack_path = temporary.path().join("missing-handler.rillpack");
    fs::write(&pack_path, pack).unwrap();

    let trust = format!(
        "missing-handler-test={}",
        hex::encode(signing.verifying_key().to_bytes())
    );

    // Start the runtime with --pack and --model-trust-key but NO --handler
    // or --builtin-handler. Do not wire stdin so the process exits
    // immediately after the CLI parser rejects the missing handler option.
    let output = Command::new(env!("CARGO_BIN_EXE_rill-runtime"))
        .args(["serve", "--pack"])
        .arg(&pack_path)
        .args(["--model-trust-key", &trust])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "expected non-zero exit when no handler option is supplied; stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("no --handler or --builtin-handler specified"),
        "expected MissingHandlerOption diagnostic on stderr, got: {stderr}"
    );

    // Also verify the primary parameter name --model-trust-key is accepted
    // (not just the deprecated --trust-key alias) by checking the runtime
    // gets past trust-store parsing and fails specifically on the handler
    // option. A trust-store parse error would emit a different diagnostic.
    assert!(
        !stderr.contains("invalid trusted key"),
        "expected --model-trust-key to be accepted as the primary name; stderr={stderr}"
    );
}