rill-runtime 1.3.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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
use std::sync::Arc;

use rill_runtime_protocol::{
    MIN_RUNTIME_API_VERSION, RUNTIME_API_VERSION, RuntimeRequest, RuntimeResponse,
    RuntimeResponseV2, error_code,
};
use serde_json::Value;

use crate::handler::HandlerIdentity;
use crate::package::LoadedModelPack;

/// Typed invoke error.
///
/// Replaces the previous `Result<Value, String>` contract. The `kind`
/// selects a stable IPC error code and a fixed public message; `detail`
/// carries host-only diagnostic text (e.g. for stderr logs) and is **never**
/// forwarded to IPC clients, so guests cannot exfiltrate arbitrary content
/// through the error path.
#[derive(Debug, Clone)]
pub struct InvokeError {
    kind: InvokeErrorKind,
    detail: Option<String>,
}

/// Maximum byte length of the host-only `detail` string. Guests can fully
/// control this payload via the WIT `handler-error` variant, so the host
/// truncates it to bound memory and stderr noise. The limit is enforced
/// on a UTF-8 char boundary so the stored string stays valid.
pub const MAX_DETAIL_BYTES: usize = 4 * 1024;

/// Stable categorisation of invoke failures.
///
/// The four guest-reported variants (`InvalidModel`, `InvalidInput`,
/// `UnsupportedCapability`, `ExecutionFailed`) correspond 1:1 to the
/// WIT `handler-error` variants. They share the same stable IPC code
/// (`handlerInternalError`) for backwards compatibility with v1/v2
/// clients, but carry distinct fixed public messages and are
/// distinguishable host-side for logging and diagnostics.
///
/// Marked `#[non_exhaustive]` so future variants (e.g. for new WIT
/// `handler-error` entries or host-side failure modes) can be added
/// without breaking downstream exhaustive `match` arms. This preserves
/// the patch-level version guarantee even though the enum is part of
/// the crate's public API surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvokeErrorKind {
    /// Host-side input serialisation or size check failed.
    Internal,
    /// Fuel budget or epoch deadline was hit. Retryable.
    Timeout,
    /// Wasmtime trap (unreachable, OOB, stack overflow, …).
    Trap,
    /// Handler output exceeded [`MAX_IO_BYTES`](crate::MAX_IO_BYTES).
    OutputTooLarge,
    /// Handler output failed JSON deserialisation on the host side.
    InvalidOutput,
    /// Guest reported `invalid-model` via the WIT `handler-error`
    /// variant. The variant detail is stored in [`InvokeError::detail`]
    /// for host logs only.
    InvalidModel,
    /// Guest reported `invalid-input` via the WIT `handler-error`
    /// variant. The variant detail is stored in [`InvokeError::detail`]
    /// for host logs only.
    InvalidInput,
    /// Guest reported `unsupported-capability` via the WIT
    /// `handler-error` variant. The variant detail is stored in
    /// [`InvokeError::detail`] for host logs only.
    UnsupportedCapability,
    /// Guest reported `execution-failed` via the WIT `handler-error`
    /// variant. The variant detail is stored in [`InvokeError::detail`]
    /// for host logs only.
    ExecutionFailed,
}

impl InvokeError {
    /// Create a new typed error with no host detail.
    pub const fn new(kind: InvokeErrorKind) -> Self {
        Self { kind, detail: None }
    }

    /// Create a new typed error carrying host-only diagnostic text.
    ///
    /// `detail` is intended for `eprintln!` logs and **must not** be sent
    /// to IPC clients. Guests can fully control this string via the WIT
    /// `handler-error` payload, so it cannot be trusted for security
    /// decisions. It is truncated to [`MAX_DETAIL_BYTES`] on a UTF-8 char
    /// boundary so a malicious guest cannot grow host memory unboundedly
    /// through the error path.
    pub fn with_detail(kind: InvokeErrorKind, detail: impl Into<String>) -> Self {
        Self {
            kind,
            detail: Some(truncate_to_bytes(detail.into(), MAX_DETAIL_BYTES)),
        }
    }

    /// Error category.
    pub const fn kind(&self) -> InvokeErrorKind {
        self.kind
    }

    /// Host-only diagnostic text. Never sent to IPC clients.
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }

    /// Stable IPC error code. Backwards-compatible with the v1/v2 wire
    /// format produced by the previous `map_invoke_error` string matching.
    ///
    /// All four guest-reported WIT `handler-error` variants
    /// (`invalid-model`, `invalid-input`, `unsupported-capability`,
    /// `execution-failed`) collapse to `handlerInternalError` on the wire
    /// to preserve compatibility with v1/v2 clients. The host still
    /// distinguishes them internally via [`InvokeError::kind`] for
    /// logging and diagnostics.
    pub const fn stable_code(&self) -> &'static str {
        match self.kind {
            InvokeErrorKind::Internal => error_code::HANDLER_INTERNAL_ERROR,
            InvokeErrorKind::Timeout => error_code::HANDLER_TIMEOUT,
            InvokeErrorKind::Trap => error_code::HANDLER_TRAP,
            InvokeErrorKind::OutputTooLarge => error_code::HANDLER_OUTPUT_TOO_LARGE,
            InvokeErrorKind::InvalidOutput => error_code::HANDLER_INVALID_OUTPUT,
            // Guest-reported WIT `handler-error` variants all collapse to
            // `handlerInternalError` on the wire, matching the previous
            // `map_invoke_error` behaviour that mapped
            // `handlerExecutionFailed: ...` to `handlerInternalError`.
            InvokeErrorKind::InvalidModel
            | InvokeErrorKind::InvalidInput
            | InvokeErrorKind::UnsupportedCapability
            | InvokeErrorKind::ExecutionFailed => error_code::HANDLER_INTERNAL_ERROR,
        }
    }

    /// Fixed public message. Never contains guest-supplied content.
    pub const fn public_message(&self) -> &'static str {
        match self.kind {
            InvokeErrorKind::Internal => "internal runtime error",
            InvokeErrorKind::Timeout => "handler exceeded the wall-clock deadline",
            InvokeErrorKind::Trap => "handler trapped",
            InvokeErrorKind::OutputTooLarge => "handler output exceeded the size limit",
            InvokeErrorKind::InvalidOutput => "handler output was not valid JSON",
            InvokeErrorKind::InvalidModel => "handler rejected the model configuration",
            InvokeErrorKind::InvalidInput => "handler rejected the input",
            InvokeErrorKind::UnsupportedCapability => "handler does not support the capability",
            InvokeErrorKind::ExecutionFailed => "handler execution failed",
        }
    }

    /// Whether the caller may retry the same request on a fresh handler.
    pub const fn retryable(&self) -> bool {
        matches!(self.kind, InvokeErrorKind::Timeout)
    }
}

impl std::fmt::Display for InvokeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.detail {
            Some(detail) => write!(f, "{}: {}", self.stable_code(), detail),
            None => f.write_str(self.stable_code()),
        }
    }
}

impl std::error::Error for InvokeError {}

/// Truncate `s` to at most `max_bytes` on a UTF-8 char boundary.
///
/// `String::truncate` panics on a non-char boundary, so we walk backwards
/// from `max_bytes` until `is_char_boundary` succeeds. The result is always
/// valid UTF-8 and never longer than `max_bytes`.
fn truncate_to_bytes(s: String, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    let mut truncated = s;
    truncated.truncate(end);
    truncated
}

/// Minimal host-side log sink for invoke diagnostics.
///
/// Production code uses [`StderrLogSink`]. Downstream test harnesses can
/// implement this trait to capture and verify log content without touching
/// stderr. Keeping this trait tiny avoids pulling in a full logging
/// framework while still making the runtime's only log call testable.
///
/// The sink receives a single pre-formatted message per invoke error. The
/// message is constructed from the already-truncated
/// [`InvokeError::detail`], so a malicious 16 KiB guest error payload can
/// never produce a 16 KiB log line.
pub trait HostLogSink: Send + Sync + std::fmt::Debug {
    /// Emit a single log line. The implementation decides where it goes.
    fn emit(&self, message: &str);
}

/// Default [`HostLogSink`] writing to stderr via `eprintln!`.
#[derive(Debug, Default, Clone)]
pub struct StderrLogSink;

impl HostLogSink for StderrLogSink {
    fn emit(&self, message: &str) {
        eprintln!("{message}");
    }
}

/// Consumers can implement this trait to add business-specific invocation logic.
pub trait InvokeHandler: Send + Sync + std::fmt::Debug {
    fn invoke(&self, capability: &str, input: &Value) -> Result<Value, InvokeError>;
}

/// Engine-side response produced by [`RuntimeEngine`]. The IPC layer converts
/// this to a v1 [`RuntimeResponse`] or v2 [`RuntimeResponseV2`] based on the
/// request's `api_version`.
///
/// This type is part of the 1.x stable API because it is the return type of
/// [`RuntimeEngine::handle`]. Downstream consumers that embed the engine
/// (rather than using the `rill-runtime` CLI) call `handle` and then convert
/// the result to the appropriate wire version.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum EngineResponse {
    Handshake {
        request_id: String,
        runtime_version: String,
        model_pack_id: String,
        model_pack_version: String,
        capabilities: Vec<String>,
        handler: Option<HandlerIdentity>,
    },
    Health {
        request_id: String,
        healthy: bool,
        model_pack_id: String,
        model_pack_version: String,
    },
    Result {
        request_id: String,
        output: Value,
    },
    Error {
        request_id: String,
        code: String,
        message: String,
        retryable: bool,
    },
}

impl EngineResponse {
    /// Convert to a v1 wire response. Handler identity fields are dropped.
    pub fn to_v1(&self, api_version: u32) -> RuntimeResponse {
        match self {
            Self::Handshake {
                request_id,
                runtime_version,
                model_pack_id,
                model_pack_version,
                capabilities,
                ..
            } => RuntimeResponse::Handshake {
                request_id: request_id.clone(),
                api_version,
                runtime_version: runtime_version.clone(),
                model_pack_id: model_pack_id.clone(),
                model_pack_version: model_pack_version.clone(),
                capabilities: capabilities.clone(),
            },
            Self::Health {
                request_id,
                healthy,
                model_pack_id,
                model_pack_version,
            } => RuntimeResponse::Health {
                request_id: request_id.clone(),
                api_version,
                healthy: *healthy,
                model_pack_id: model_pack_id.clone(),
                model_pack_version: model_pack_version.clone(),
            },
            Self::Result { request_id, output } => RuntimeResponse::Result {
                request_id: request_id.clone(),
                api_version,
                output: output.clone(),
            },
            Self::Error {
                request_id,
                code,
                message,
                retryable,
            } => RuntimeResponse::Error {
                request_id: request_id.clone(),
                api_version,
                code: code.clone(),
                message: message.clone(),
                retryable: *retryable,
            },
        }
    }

    /// Convert to a v2 wire response. If no handler is loaded, handler fields
    /// are filled with empty/zero values and effective_capabilities equals the
    /// model capabilities.
    pub fn to_v2(&self, api_version: u32) -> RuntimeResponseV2 {
        match self {
            Self::Handshake {
                request_id,
                runtime_version,
                model_pack_id,
                model_pack_version,
                capabilities,
                handler,
            } => {
                let (handler_id, handler_version, handler_api_version, effective) = match handler {
                    Some(h) => (
                        h.handler_id.clone(),
                        h.handler_version.clone(),
                        h.handler_api_version,
                        h.effective_capabilities.clone(),
                    ),
                    None => (String::new(), String::new(), 0, capabilities.clone()),
                };
                RuntimeResponseV2::Handshake {
                    request_id: request_id.clone(),
                    api_version,
                    runtime_version: runtime_version.clone(),
                    model_pack_id: model_pack_id.clone(),
                    model_pack_version: model_pack_version.clone(),
                    capabilities: capabilities.clone(),
                    handler_id,
                    handler_version,
                    handler_api_version,
                    effective_capabilities: effective,
                }
            }
            Self::Health {
                request_id,
                healthy,
                model_pack_id,
                model_pack_version,
            } => RuntimeResponseV2::Health {
                request_id: request_id.clone(),
                api_version,
                healthy: *healthy,
                model_pack_id: model_pack_id.clone(),
                model_pack_version: model_pack_version.clone(),
            },
            Self::Result { request_id, output } => RuntimeResponseV2::Result {
                request_id: request_id.clone(),
                api_version,
                output: output.clone(),
            },
            Self::Error {
                request_id,
                code,
                message,
                retryable,
            } => RuntimeResponseV2::Error {
                request_id: request_id.clone(),
                api_version,
                code: code.clone(),
                message: message.clone(),
                retryable: *retryable,
            },
        }
    }
}

#[derive(Debug, Clone)]
pub struct RuntimeEngine {
    pack: LoadedModelPack,
    invoke_handler: Option<Arc<dyn InvokeHandler>>,
    handler_identity: Option<HandlerIdentity>,
    effective_capabilities: Vec<String>,
    log_sink: Arc<dyn HostLogSink>,
}

impl RuntimeEngine {
    pub fn new(pack: LoadedModelPack) -> Self {
        Self {
            pack,
            invoke_handler: None,
            handler_identity: None,
            effective_capabilities: Vec::new(),
            log_sink: Arc::new(StderrLogSink),
        }
    }

    pub fn with_invoke_handler(mut self, handler: Arc<dyn InvokeHandler>) -> Self {
        self.invoke_handler = Some(handler);
        self
    }

    /// Replace the default [`StderrLogSink`] with a custom sink. Tests
    /// inject a capturing sink to verify log bounds and content
    /// without capturing stderr.
    pub fn with_log_sink(mut self, sink: Arc<dyn HostLogSink>) -> Self {
        self.log_sink = sink;
        self
    }

    /// Attach handler identity and effective capabilities for IPC v2 handshake.
    pub fn with_handler_identity(mut self, identity: HandlerIdentity) -> Self {
        self.effective_capabilities = identity.effective_capabilities.clone();
        self.handler_identity = Some(identity);
        self
    }

    /// Effective capability set (intersection of model and handler). Empty when
    /// no handler is loaded.
    pub fn effective_capabilities(&self) -> &[String] {
        &self.effective_capabilities
    }

    /// Handler identity if a handler was loaded.
    pub fn handler_identity(&self) -> Option<&HandlerIdentity> {
        self.handler_identity.as_ref()
    }

    pub fn handle(&self, request: RuntimeRequest) -> EngineResponse {
        let request_id = request.request_id().to_string();
        if request_id.is_empty() || request_id.len() > 128 {
            return self.error(
                request_id,
                error_code::INVALID_REQUEST_ID,
                "invalid request id",
                false,
            );
        }
        let api_version = request.api_version();
        if !(MIN_RUNTIME_API_VERSION..=RUNTIME_API_VERSION).contains(&api_version) {
            return self.error(
                request_id,
                error_code::INCOMPATIBLE_API_VERSION,
                "runtime API version is not supported",
                false,
            );
        }

        match request {
            RuntimeRequest::Handshake {
                request_id,
                client_name,
                client_version,
                ..
            } => {
                if client_name.is_empty()
                    || client_name.len() > 96
                    || client_version.is_empty()
                    || client_version.len() > 48
                {
                    return self.error(
                        request_id,
                        error_code::INVALID_CLIENT_IDENTITY,
                        "invalid client identity",
                        false,
                    );
                }
                EngineResponse::Handshake {
                    request_id,
                    runtime_version: env!("CARGO_PKG_VERSION").into(),
                    model_pack_id: self.pack.manifest.id.clone(),
                    model_pack_version: self.pack.manifest.version.clone(),
                    capabilities: self.pack.manifest.capabilities.clone(),
                    handler: self.handler_identity.clone(),
                }
            }
            RuntimeRequest::Health { request_id, .. } => EngineResponse::Health {
                request_id,
                healthy: true,
                model_pack_id: self.pack.manifest.id.clone(),
                model_pack_version: self.pack.manifest.version.clone(),
            },
            RuntimeRequest::Invoke {
                request_id,
                capability,
                input,
                ..
            } => {
                if !self.is_capability_allowed(&capability) {
                    return self.error(
                        request_id,
                        error_code::UNSUPPORTED_CAPABILITY,
                        "capability is not in the effective set",
                        false,
                    );
                }
                let Some(handler) = &self.invoke_handler else {
                    return self.error(
                        request_id,
                        error_code::NO_INVOKE_HANDLER,
                        "no invoke handler registered",
                        false,
                    );
                };
                match handler.invoke(&capability, &input) {
                    Ok(output) => EngineResponse::Result { request_id, output },
                    Err(invoke_err) => {
                        // Log host-side detail (if any) for debugging; the
                        // IPC message is always the fixed public string so
                        // guests cannot exfiltrate content via the error
                        // payload. The detail is already truncated to
                        // [`MAX_DETAIL_BYTES`] by [`InvokeError::with_detail`],
                        // so a 16 KiB guest payload can never produce a
                        // 16 KiB log line. This is the single log call for
                        // invoke errors; the WASM adapter must not also
                        // log the same error (see audit 5.2).
                        if let Some(detail) = invoke_err.detail() {
                            self.log_sink.emit(&format!(
                                "rill-runtime: invoke {} -> {} (detail: {})",
                                capability,
                                invoke_err.stable_code(),
                                detail
                            ));
                        }
                        self.error(
                            request_id,
                            invoke_err.stable_code(),
                            invoke_err.public_message(),
                            invoke_err.retryable(),
                        )
                    }
                }
            }
        }
    }

    /// Checks the capability against the effective set when a handler is loaded,
    /// or against the model pack's declared capabilities when no handler is
    /// loaded (for backwards compatibility with built-in handlers selected by
    /// the binary).
    fn is_capability_allowed(&self, capability: &str) -> bool {
        if !self.effective_capabilities.is_empty() {
            self.effective_capabilities.iter().any(|c| c == capability)
        } else {
            self.pack
                .manifest
                .capabilities
                .iter()
                .any(|c| c == capability)
        }
    }

    fn error(
        &self,
        request_id: String,
        code: &str,
        message: &str,
        retryable: bool,
    ) -> EngineResponse {
        EngineResponse::Error {
            request_id,
            code: code.into(),
            message: message.into(),
            retryable,
        }
    }
}

#[cfg(test)]
mod tests {
    use rill_runtime_protocol::{MODEL_PACK_FORMAT_VERSION, ModelPackManifest};
    use std::sync::Mutex;

    use super::*;
    use crate::handler::builtin::LINEAR_REGRESSION_CAPABILITY;

    /// Test-only [`HostLogSink`] that captures every emitted message in a
    /// `Mutex<Vec<String>>`. Tests inspect the captured messages to verify
    /// log bounds, content, and deduplication without touching stderr.
    ///
    /// This type is `pub(crate)` and lives inside `#[cfg(test)]` so it
    /// never appears in the public API surface. Downstream test harnesses
    /// that need similar functionality should implement [`HostLogSink`]
    /// directly.
    #[derive(Debug, Default)]
    pub(crate) struct CapturingLogSink {
        messages: Mutex<Vec<String>>,
    }

    impl CapturingLogSink {
        /// Create an empty capturing sink.
        pub(crate) fn new() -> Self {
            Self::default()
        }

        /// Return a snapshot of all captured messages in emission order.
        pub(crate) fn messages(&self) -> Vec<String> {
            self.messages
                .lock()
                .expect("CapturingLogSink poisoned")
                .clone()
        }

        /// Total byte length of all captured messages. Useful for asserting
        /// that a 16 KiB guest error did not produce a 16 KiB log.
        #[allow(dead_code)]
        pub(crate) fn total_bytes(&self) -> usize {
            self.messages
                .lock()
                .expect("CapturingLogSink poisoned")
                .iter()
                .map(String::len)
                .sum()
        }

        /// Drop all captured messages.
        #[allow(dead_code)]
        pub(crate) fn clear(&self) {
            self.messages
                .lock()
                .expect("CapturingLogSink poisoned")
                .clear();
        }
    }

    impl HostLogSink for CapturingLogSink {
        fn emit(&self, message: &str) {
            self.messages
                .lock()
                .expect("CapturingLogSink poisoned")
                .push(message.to_string());
        }
    }

    fn engine() -> RuntimeEngine {
        RuntimeEngine::new(LoadedModelPack {
            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: "test".into(),
                capabilities: vec!["rillml.example".into()],
            },
            model: serde_json::json!({}),
        })
    }

    #[test]
    fn handshake_reports_loaded_pack() {
        let response = engine().handle(RuntimeRequest::Handshake {
            request_id: "hello".into(),
            api_version: RUNTIME_API_VERSION,
            client_name: "example-host".into(),
            client_version: "0.9.0".into(),
        });
        assert!(matches!(
            response,
            EngineResponse::Handshake { model_pack_id, .. }
                if model_pack_id == "rillml.example.default"
        ));
    }

    #[test]
    fn incompatible_api_is_a_typed_error() {
        let response = engine().handle(RuntimeRequest::Health {
            request_id: "health".into(),
            api_version: RUNTIME_API_VERSION + 1,
        });
        assert!(matches!(
            response,
            EngineResponse::Error { code, .. } if code == "incompatibleApiVersion"
        ));
    }

    #[test]
    fn invoke_without_handler_returns_no_invoke_handler_error() {
        let response = engine().handle(RuntimeRequest::Invoke {
            request_id: "invoke-1".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.example".into(),
            input: serde_json::json!({}),
        });
        assert!(matches!(
            response,
            EngineResponse::Error { code, .. } if code == "noInvokeHandler"
        ));
    }

    #[test]
    fn invoke_rejects_capability_not_declared_by_signed_manifest() {
        let response = engine().handle(RuntimeRequest::Invoke {
            request_id: "invoke-undeclared".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "undeclared.capability".into(),
            input: serde_json::json!({}),
        });
        assert!(matches!(
            response,
            EngineResponse::Error { code, .. } if code == "unsupportedCapability"
        ));
    }

    #[test]
    fn v1_handshake_omits_handler_fields() {
        let identity = HandlerIdentity {
            handler_id: "org.example.handler".into(),
            handler_version: "1.0.0".into(),
            handler_api_version: 1,
            effective_capabilities: vec!["rillml.example".into()],
        };
        let engine = engine().with_handler_identity(identity);
        let response = engine.handle(RuntimeRequest::Handshake {
            request_id: "v1-test".into(),
            api_version: 1,
            client_name: "v1-host".into(),
            client_version: "0.6.0".into(),
        });
        let v1 = response.to_v1(1);
        let json = serde_json::to_string(&v1).unwrap();
        assert!(!json.contains("handlerId"));
        assert!(!json.contains("effectiveCapabilities"));
    }

    #[test]
    fn v2_handshake_includes_handler_fields() {
        let identity = HandlerIdentity {
            handler_id: "org.example.handler".into(),
            handler_version: "1.0.0".into(),
            handler_api_version: 1,
            effective_capabilities: vec!["rillml.example".into()],
        };
        let engine = engine().with_handler_identity(identity);
        let response = engine.handle(RuntimeRequest::Handshake {
            request_id: "v2-test".into(),
            api_version: 2,
            client_name: "v2-host".into(),
            client_version: "0.7.0".into(),
        });
        let v2 = response.to_v2(2);
        let json = serde_json::to_string(&v2).unwrap();
        assert!(json.contains("\"handlerId\":\"org.example.handler\""));
        assert!(json.contains("\"handlerApiVersion\":1"));
        assert!(json.contains("\"effectiveCapabilities\":[\"rillml.example\"]"));
    }

    #[test]
    fn v2_handshake_without_handler_has_empty_fields() {
        let response = engine().handle(RuntimeRequest::Handshake {
            request_id: "v2-no-handler".into(),
            api_version: 2,
            client_name: "v2-host".into(),
            client_version: "0.7.0".into(),
        });
        let v2 = response.to_v2(2);
        match v2 {
            RuntimeResponseV2::Handshake {
                handler_id,
                handler_version,
                handler_api_version,
                effective_capabilities,
                ..
            } => {
                assert!(handler_id.is_empty());
                assert!(handler_version.is_empty());
                assert_eq!(handler_api_version, 0);
                assert_eq!(effective_capabilities, vec!["rillml.example"]);
            }
            _ => panic!("expected handshake"),
        }
    }

    #[test]
    fn linear_regression_handler_validates_and_predicts() {
        use crate::handler::builtin::LinearRegressionInvokeHandler;

        let pack = LoadedModelPack {
            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: "test".into(),
                capabilities: vec![LINEAR_REGRESSION_CAPABILITY.into()],
            },
            model: serde_json::json!({
                "kind": "linearRegression",
                "weights": [0.5, -0.25],
                "intercept": 1.0
            }),
        };
        let handler = LinearRegressionInvokeHandler::from_pack(&pack).unwrap();
        let engine = RuntimeEngine::new(pack).with_invoke_handler(Arc::new(handler));
        let response = engine.handle(RuntimeRequest::Invoke {
            request_id: "invoke-linear".into(),
            api_version: RUNTIME_API_VERSION,
            capability: LINEAR_REGRESSION_CAPABILITY.into(),
            input: serde_json::json!({"features": [4.0, 2.0]}),
        });
        assert!(matches!(
            response,
            EngineResponse::Result { output, .. } if output["prediction"] == 2.5
        ));
    }

    #[test]
    fn invoke_error_stable_codes_match_wire_format() {
        // Every kind must map to the exact IPC code expected by v1/v2
        // clients, preserving backwards compatibility with the previous
        // `map_invoke_error` string matching.
        assert_eq!(
            InvokeError::new(InvokeErrorKind::Trap).stable_code(),
            "handlerTrap"
        );
        assert_eq!(
            InvokeError::new(InvokeErrorKind::Timeout).stable_code(),
            "handlerTimeout"
        );
        assert_eq!(
            InvokeError::new(InvokeErrorKind::OutputTooLarge).stable_code(),
            "handlerOutputTooLarge"
        );
        assert_eq!(
            InvokeError::new(InvokeErrorKind::InvalidOutput).stable_code(),
            "handlerInvalidOutput"
        );
        assert_eq!(
            InvokeError::new(InvokeErrorKind::Internal).stable_code(),
            "handlerInternalError"
        );
        // All four guest-reported WIT handler-error variants collapse to
        // handlerInternalError on the wire, matching the previous
        // `map_invoke_error` behaviour. The host distinguishes them
        // internally via `kind()` for logging, but v1/v2 clients see
        // the same code.
        for kind in [
            InvokeErrorKind::InvalidModel,
            InvokeErrorKind::InvalidInput,
            InvokeErrorKind::UnsupportedCapability,
            InvokeErrorKind::ExecutionFailed,
        ] {
            assert_eq!(
                InvokeError::new(kind).stable_code(),
                "handlerInternalError",
                "{kind:?} must map to handlerInternalError for v1/v2 compat"
            );
        }
    }

    #[test]
    fn invoke_error_retryable_only_for_timeout() {
        assert!(InvokeError::new(InvokeErrorKind::Timeout).retryable());
        for kind in [
            InvokeErrorKind::Trap,
            InvokeErrorKind::OutputTooLarge,
            InvokeErrorKind::InvalidOutput,
            InvokeErrorKind::Internal,
            InvokeErrorKind::InvalidModel,
            InvokeErrorKind::InvalidInput,
            InvokeErrorKind::UnsupportedCapability,
            InvokeErrorKind::ExecutionFailed,
        ] {
            assert!(
                !InvokeError::new(kind).retryable(),
                "{kind:?} must not be retryable"
            );
        }
    }

    #[test]
    fn invoke_error_guest_variants_have_distinct_public_messages() {
        // Each guest variant carries a fixed public message that never
        // contains guest-supplied content. The messages are distinct so
        // operators can distinguish variants in host logs.
        let messages = [
            InvokeError::new(InvokeErrorKind::InvalidModel).public_message(),
            InvokeError::new(InvokeErrorKind::InvalidInput).public_message(),
            InvokeError::new(InvokeErrorKind::UnsupportedCapability).public_message(),
            InvokeError::new(InvokeErrorKind::ExecutionFailed).public_message(),
        ];
        // All distinct.
        for i in 0..messages.len() {
            for j in (i + 1)..messages.len() {
                assert_ne!(messages[i], messages[j], "public messages must be distinct");
            }
        }
        // None contain guest content markers.
        for msg in messages {
            assert!(!msg.contains("detail"));
            assert!(!msg.contains("guest"));
        }
    }

    #[test]
    fn invoke_error_public_message_never_contains_detail() {
        // Guest can fully control the detail string; the public message
        // must always be the fixed constant.
        let err = InvokeError::with_detail(
            InvokeErrorKind::ExecutionFailed,
            "SECRET-TOKEN-LEAK-ATTEMPT guest-controlled-payload",
        );
        assert_eq!(err.public_message(), "handler execution failed");
        assert_eq!(err.stable_code(), "handlerInternalError");
        assert_eq!(
            err.detail(),
            Some("SECRET-TOKEN-LEAK-ATTEMPT guest-controlled-payload")
        );
        // The Display impl is for host logs only; the IPC layer must
        // never send `err.to_string()` to clients.
        assert!(err.to_string().contains("SECRET-TOKEN-LEAK-ATTEMPT"));
        // The public_message is what the IPC layer actually sends.
        assert!(!err.public_message().contains("SECRET"));
    }

    #[test]
    fn invoke_error_without_detail_has_no_detail() {
        let err = InvokeError::new(InvokeErrorKind::Trap);
        assert_eq!(err.kind(), InvokeErrorKind::Trap);
        assert_eq!(err.detail(), None);
        assert_eq!(err.stable_code(), "handlerTrap");
        assert_eq!(err.to_string(), "handlerTrap");
    }

    #[test]
    fn invoke_error_detail_is_truncated_to_4kib_on_char_boundary() {
        // A malicious guest tries to grow host memory via an oversized
        // error payload. The host must truncate to MAX_DETAIL_BYTES on a
        // UTF-8 char boundary.
        let huge = "A".repeat(MAX_DETAIL_BYTES * 4);
        let err = InvokeError::with_detail(InvokeErrorKind::ExecutionFailed, huge);
        let detail = err.detail().expect("detail must be stored");
        assert!(
            detail.len() <= MAX_DETAIL_BYTES,
            "detail length {} must not exceed {}",
            detail.len(),
            MAX_DETAIL_BYTES
        );
        // Truncation must land on a char boundary (the string is valid UTF-8
        // by construction, but the test guards against a future unsafe path).
        assert!(detail.chars().all(|c| c == 'A'));
    }

    #[test]
    fn invoke_error_detail_truncation_respects_multibyte_chars() {
        // Multi-byte UTF-8 must not be split mid-codepoint. Use 3-byte
        // CJK characters so the MAX_DETAIL_BYTES boundary lands inside a
        // character; the result must back up to the previous char boundary.
        let emoji = "🌟".repeat(MAX_DETAIL_BYTES); // each '🌟' is 4 bytes
        let err = InvokeError::with_detail(InvokeErrorKind::ExecutionFailed, emoji);
        let detail = err.detail().expect("detail must be stored");
        assert!(detail.len() <= MAX_DETAIL_BYTES);
        // Every stored character must be a complete '🌟'.
        for c in detail.chars() {
            assert_eq!(c, '🌟');
        }
    }

    /// Minimal handler that always returns the supplied error, for
    /// exercising the engine's invoke error path without a WASM sandbox.
    #[derive(Debug)]
    struct FailingHandler {
        err: InvokeError,
    }

    impl InvokeHandler for FailingHandler {
        fn invoke(&self, _capability: &str, _input: &Value) -> Result<Value, InvokeError> {
            Err(self.err.clone())
        }
    }

    #[test]
    fn engine_invoke_error_does_not_leak_guest_detail_in_message() {
        // A malicious guest tries to exfiltrate a token via the WIT
        // handler-error payload. The IPC Error.message field must be
        // the fixed public string, not the guest-supplied detail.
        let err = InvokeError::with_detail(
            InvokeErrorKind::ExecutionFailed,
            "leak-attempt:SECRET-TOKEN",
        );
        let pack = LoadedModelPack {
            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: "test".into(),
                capabilities: vec!["rillml.example".into()],
            },
            model: serde_json::json!({}),
        };
        let sink = Arc::new(CapturingLogSink::new());
        let engine = RuntimeEngine::new(pack)
            .with_invoke_handler(Arc::new(FailingHandler { err }))
            .with_log_sink(sink.clone());
        let response = engine.handle(RuntimeRequest::Invoke {
            request_id: "leak-test".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.example".into(),
            input: serde_json::json!({}),
        });
        match response {
            EngineResponse::Error {
                code,
                message,
                retryable,
                ..
            } => {
                assert_eq!(code, "handlerInternalError");
                assert_eq!(message, "handler execution failed");
                assert!(!retryable);
                // The guest-supplied detail must NOT appear anywhere in
                // the IPC response fields.
                assert!(!message.contains("SECRET"));
                assert!(!message.contains("leak-attempt"));
            }
            _ => panic!("expected EngineResponse::Error"),
        }
        // The host log line does contain the (truncated) detail for
        // operator diagnostics, but the detail is host-only — it never
        // reaches the IPC `message` field. This assertion documents that
        // the log sink received exactly one message referencing the
        // secret, proving the detail was captured host-side.
        let messages = sink.messages();
        assert_eq!(
            messages.len(),
            1,
            "the engine must log the invoke error exactly once"
        );
        assert!(messages[0].contains("SECRET-TOKEN"));
    }

    /// Verifies audit 5.2: a 16 KiB guest error payload must not produce
    /// a 16 KiB log line. The host constructs `InvokeError::with_detail`
    /// (which truncates to `MAX_DETAIL_BYTES`) before logging, so the
    /// captured log message must be well under 16 KiB.
    #[test]
    fn engine_log_does_not_emit_oversized_guest_detail() {
        let huge_detail = "X".repeat(MAX_DETAIL_BYTES * 4); // 16 KiB
        let err = InvokeError::with_detail(InvokeErrorKind::ExecutionFailed, huge_detail);
        let pack = LoadedModelPack {
            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: "test".into(),
                capabilities: vec!["rillml.example".into()],
            },
            model: serde_json::json!({}),
        };
        let sink = Arc::new(CapturingLogSink::new());
        let engine = RuntimeEngine::new(pack)
            .with_invoke_handler(Arc::new(FailingHandler { err }))
            .with_log_sink(sink.clone());
        let _ = engine.handle(RuntimeRequest::Invoke {
            request_id: "oversized".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.example".into(),
            input: serde_json::json!({}),
        });
        let messages = sink.messages();
        assert_eq!(messages.len(), 1, "exactly one log line expected");
        let log_line = &messages[0];
        // The log line consists of a fixed prefix + the truncated detail.
        // The detail is at most MAX_DETAIL_BYTES; the prefix is small.
        // 16 KiB must never appear in the log.
        assert!(
            log_line.len() < MAX_DETAIL_BYTES * 2,
            "log line length {} must be well under 2x MAX_DETAIL_BYTES ({}); \
             a 16 KiB guest payload must not produce a 16 KiB log",
            log_line.len(),
            MAX_DETAIL_BYTES * 2
        );
        // The detail portion (after the prefix) must not exceed the cap.
        assert!(
            log_line.len() < MAX_DETAIL_BYTES + 256,
            "log line length {} must be < MAX_DETAIL_BYTES + prefix overhead",
            log_line.len()
        );
    }

    /// Verifies audit 5.2: the same invoke error must not be logged
    /// twice. The WASM adapter must not log the error if the engine
    /// already logs it; this test uses a `FailingHandler` (no WASM
    /// adapter) and confirms exactly one log line per invoke.
    #[test]
    fn engine_logs_invoke_error_exactly_once() {
        let err = InvokeError::with_detail(
            InvokeErrorKind::UnsupportedCapability,
            "capability foo not supported",
        );
        let pack = LoadedModelPack {
            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: "test".into(),
                capabilities: vec!["rillml.example".into()],
            },
            model: serde_json::json!({}),
        };
        let sink = Arc::new(CapturingLogSink::new());
        let engine = RuntimeEngine::new(pack)
            .with_invoke_handler(Arc::new(FailingHandler { err }))
            .with_log_sink(sink.clone());
        let _ = engine.handle(RuntimeRequest::Invoke {
            request_id: "once".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.example".into(),
            input: serde_json::json!({}),
        });
        assert_eq!(
            sink.messages().len(),
            1,
            "the engine must log the invoke error exactly once, not twice"
        );
    }

    /// Verifies audit 5.2: a trap backtrace (which can be very long)
    /// must be truncated before logging. The `FailingHandler` simulates
    /// a trap with a long backtrace-like detail string.
    #[test]
    fn engine_log_traps_backtrace_is_truncated() {
        let fake_backtrace = "trap: unreachable\n".repeat(1024); // ~17 KiB
        let err = InvokeError::with_detail(InvokeErrorKind::Trap, fake_backtrace);
        let pack = LoadedModelPack {
            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: "test".into(),
                capabilities: vec!["rillml.example".into()],
            },
            model: serde_json::json!({}),
        };
        let sink = Arc::new(CapturingLogSink::new());
        let engine = RuntimeEngine::new(pack)
            .with_invoke_handler(Arc::new(FailingHandler { err }))
            .with_log_sink(sink.clone());
        let _ = engine.handle(RuntimeRequest::Invoke {
            request_id: "trap-trunc".into(),
            api_version: RUNTIME_API_VERSION,
            capability: "rillml.example".into(),
            input: serde_json::json!({}),
        });
        let messages = sink.messages();
        assert_eq!(messages.len(), 1);
        let log_line = &messages[0];
        assert!(
            log_line.len() < MAX_DETAIL_BYTES + 256,
            "trap backtrace log must be truncated; got {} bytes",
            log_line.len()
        );
    }

    /// Verifies that all four guest WIT variants flow through the engine
    /// with the correct `kind()` and fixed public message, while the
    /// stable IPC code stays `handlerInternalError` for v1/v2 compat.
    #[test]
    fn engine_preserves_guest_variant_kind_for_all_wit_variants() {
        for (kind, expected_message) in [
            (
                InvokeErrorKind::InvalidModel,
                "handler rejected the model configuration",
            ),
            (InvokeErrorKind::InvalidInput, "handler rejected the input"),
            (
                InvokeErrorKind::UnsupportedCapability,
                "handler does not support the capability",
            ),
            (InvokeErrorKind::ExecutionFailed, "handler execution failed"),
        ] {
            let err = InvokeError::with_detail(kind, "guest detail");
            let pack = LoadedModelPack {
                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: "test".into(),
                    capabilities: vec!["rillml.example".into()],
                },
                model: serde_json::json!({}),
            };
            let engine =
                RuntimeEngine::new(pack).with_invoke_handler(Arc::new(FailingHandler { err }));
            let response = engine.handle(RuntimeRequest::Invoke {
                request_id: "variant".into(),
                api_version: RUNTIME_API_VERSION,
                capability: "rillml.example".into(),
                input: serde_json::json!({}),
            });
            match response {
                EngineResponse::Error { code, message, .. } => {
                    assert_eq!(
                        code, "handlerInternalError",
                        "{kind:?}: stable code must stay handlerInternalError"
                    );
                    assert_eq!(
                        message, expected_message,
                        "{kind:?}: public message mismatch"
                    );
                }
                _ => panic!("{kind:?}: expected EngineResponse::Error"),
            }
        }
    }
}