vyre_foundation/serial/wire.rs
1// Stable binary IR wire format for serialized IR programs.
2
3use crate::ir::{BufferDecl, DataType, Expr, Node, Program};
4
5/// The `decode` module.
6pub mod decode;
7/// The `encode` module.
8pub mod encode;
9/// The `framing` module.
10pub mod framing;
11/// The `tags` module.
12pub mod tags;
13
14/// Maximum buffers accepted from one IR wire-format program.
15///
16/// I10 requires bounded allocation before validating semantics. This limit
17/// rejects hostile wire blobs before allocating the buffer table.
18pub const MAX_BUFFERS: usize = 16_384;
19
20/// Maximum statement nodes accepted from any single wire-format node list.
21///
22/// I10 requires node vectors to be bounded before allocation; nested lists are
23/// each checked against this budget as they are decoded.
24pub const MAX_NODES: usize = 1_000_000;
25
26/// Maximum call arguments accepted from one wire-format call expression.
27///
28/// I10 requires expression argument vectors to be bounded before allocation.
29pub const MAX_ARGS: usize = 4_096;
30
31/// Maximum tensor rank (dimension count) accepted from a wire-format
32/// `DataType::TensorShaped` shape.
33///
34/// I10 requires the shape vector to be bounded before the decoder reads each
35/// dimension. Real tensors are single-digit rank (the inline `SmallVec`
36/// capacity is 4); this ceiling is generous enough never to reject a real
37/// program yet bounds the shape allocation to a small fixed size instead of the
38/// transitive `MAX_PROGRAM_BYTES / 4` worst case. Makes the "rank-limited shape"
39/// contract on `DataType::TensorShaped` actually enforced.
40pub const MAX_TENSOR_RANK: usize = 4_096;
41
42/// Maximum device-mesh axis count accepted from a wire-format
43/// `DataType::DeviceMesh`.
44///
45/// I10 requires the axis vector to be bounded before the decoder reads each
46/// axis. Real meshes have a handful of axes (data/model/pipeline parallelism);
47/// this ceiling never rejects a real program yet bounds the allocation.
48pub const MAX_MESH_AXES: usize = 4_096;
49
50/// Maximum UTF-8 string length accepted from the IR wire format.
51///
52/// I10 bounds allocation for names and operation identifiers carried by
53/// attacker-controlled wire bytes.
54pub const MAX_STRING_LEN: usize = 1 << 20;
55
56/// Maximum opaque payload length accepted from the IR wire format.
57///
58/// I10 bounds allocation for extension-defined `Expr::Opaque` and
59/// `Node::Opaque` payloads carried by attacker-controlled wire bytes.
60/// Must match the encoder limit in `put_node.rs` and `put_expr.rs`.
61pub const MAX_OPAQUE_PAYLOAD_LEN: usize = MAX_ARGS * 1024;
62
63/// Maximum recursive decode depth for the IR wire format.
64///
65/// The limit is applied to the **shared** recursion counter in `Reader`
66/// that `Reader::node` and `Reader::expr` both increment on entry and
67/// decrement on exit. A hostile blob cannot evade the cap by alternating
68/// statement and expression nesting - every nested decode call, whether it
69/// descends into a `Node::If`/`Loop`/`Block` body or into a nested
70/// [`Expr`] argument tree, counts against the same budget. Depth ≥
71/// `MAX_DECODE_DEPTH` is rejected with a `Fix:`-prefixed error before any
72/// stack frame is pushed, preventing stack-overflow `DoS` from a blob that
73/// nests `Block(Block(... Block(...) ...))` a million times deep.
74///
75/// Covers audit L.1.35 (HIGH).
76pub const MAX_DECODE_DEPTH: u32 = 64;
77
78/// Hard ceiling on the size of a single wire-encoded Program in bytes.
79///
80/// The framing layer rejects larger blobs before any decode allocation so
81/// attacker-controlled input cannot force unbounded memory growth.
82pub const MAX_PROGRAM_BYTES: usize = 64 * 1024 * 1024;
83
84pub(crate) struct Reader<'a> {
85 pub bytes: &'a [u8],
86 pub pos: usize,
87 /// Current recursion depth on the decode call stack. Incremented by
88 /// every `node()` and `expr()` call and compared against
89 /// [`MAX_DECODE_DEPTH`] before any nested decode proceeds.
90 pub depth: u32,
91}
92
93impl Program {
94 /// Serialize this IR program into the stable `VIR0` IR wire format.
95 ///
96 /// # Errors
97 ///
98 /// Returns [`crate::error::IrError::WireFormatValidation`] when a count
99 /// cannot be represented in the versioned wire format or when a public
100 /// enum variant has no registered stable wire tag. The `message` field
101 /// carries the actionable diagnostic prose including a `Fix:` hint.
102 #[inline]
103 #[must_use]
104 pub fn to_wire(&self) -> Result<Vec<u8>, crate::error::IrError> {
105 encode::to_wire(self).map_err(wire_err)
106 }
107
108 /// Serialize this IR program into the stable `VIR0` IR wire format,
109 /// appending to an existing buffer.
110 ///
111 /// # Errors
112 ///
113 /// Returns [`crate::error::IrError::WireFormatValidation`] when a count
114 /// cannot be represented in the versioned wire format or when a public
115 /// enum variant has no registered stable wire tag. The `message` field
116 /// carries the actionable diagnostic prose including a `Fix:` hint.
117 #[inline]
118 pub fn to_wire_into(&self, dst: &mut Vec<u8>) -> Result<(), crate::error::IrError> {
119 encode::to_wire_into(self, dst).map_err(wire_err)
120 }
121
122 /// Deserialize an IR program from the stable `VYRE` IR wire format.
123 ///
124 /// # Errors
125 ///
126 /// Returns [`crate::error::IrError::VersionMismatch`] when the payload
127 /// advertises a schema version this runtime does not understand. Returns
128 /// [`crate::error::IrError::WireFormatValidation`] for any other decode
129 /// failure: truncated bytes, unknown enum tag, integrity digest mismatch,
130 /// or malformed structural section.
131 #[inline]
132 #[must_use]
133 pub fn from_wire(bytes: &[u8]) -> Result<Self, crate::error::IrError> {
134 if bytes.len() > MAX_PROGRAM_BYTES {
135 return Err(wire_err(format!(
136 "Fix: wire blob is {} bytes, exceeding the {}-byte IR framing cap. Reject this input or split the Program before serialization.",
137 bytes.len(),
138 MAX_PROGRAM_BYTES
139 )));
140 }
141 // The version field is validated before the string-based
142 // decoder so that an out-of-range version surfaces as the
143 // typed `VersionMismatch` variant instead of being absorbed
144 // into the generic `WireFormatValidation` bucket. Tooling
145 // that hangs off the diagnostic code `E-WIRE-VERSION` relies
146 // on this distinction.
147 if bytes.len() >= framing::MAGIC.len() + 2
148 && &bytes[..framing::MAGIC.len()] == framing::MAGIC
149 {
150 let version = u16::from_le_bytes([bytes[4], bytes[5]]);
151 if !framing::wire_format_version_is_supported(version) {
152 return Err(crate::error::IrError::VersionMismatch {
153 expected: u32::from(framing::WIRE_FORMAT_VERSION),
154 found: u32::from(version),
155 });
156 }
157 }
158 decode::from_wire(bytes).map_err(wire_err)
159 }
160
161 /// Stable content hash of this Program, used as a cache identity.
162 ///
163 /// Computed as BLAKE3 of the canonical wire-format encoding. This is the
164 /// exact-match identity for persistent-cache consumers that need a
165 /// deterministic key per Program without re-implementing canonicalization.
166 /// On canonical wire-encoding failure, the value is a domain-separated
167 /// error digest rather than an all-zero sentinel, so malformed programs do
168 /// not collapse into the same cache identity.
169 #[must_use]
170 pub fn content_hash(&self) -> [u8; 32] {
171 self.fingerprint()
172 }
173}
174
175/// Wrap an internal wire-format error string in the typed [`crate::error::IrError`]
176/// so every public boundary of this module returns a structured variant.
177fn wire_err(message: String) -> crate::error::IrError {
178 crate::error::IrError::WireFormatValidation { message }
179}
180
181/// Append stable VIR0 wire bytes for a [`DataType`] (tag + any payload) into
182/// `buf`. Used by disk-cache fingerprinting where `Debug` output would be
183/// the wrong contract.
184///
185/// # Errors
186///
187/// Returns a wire-format diagnostic when `value` contains a datatype variant
188/// without a stable tag or a payload that cannot fit the VIR0 encoding.
189pub fn append_data_type_fingerprint(buf: &mut Vec<u8>, value: &DataType) -> Result<(), String> {
190 tags::data_type_tag::put_data_type(buf, value).map_err(String::from)
191}
192
193/// Append stable VIR0 wire bytes for a `Node` statement list (count + each
194/// node). Matches the statement encoding used in full program wire (`to_wire`)
195/// (without the file envelope, metadata, or buffer table).
196///
197/// # Errors
198///
199/// Returns a wire-format diagnostic when the node list or any nested payload
200/// cannot be represented in VIR0.
201pub fn append_node_list_fingerprint(buf: &mut Vec<u8>, nodes: &[Node]) -> Result<(), String> {
202 encode::put_nodes(buf, nodes).map_err(String::from)
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use crate::ir::{BufferDecl, DataType, Node, Program};
209
210 /// EDGE-001 regression: `MAX_DECODE_DEPTH` covers **both** Node and Expr
211 /// recursion through the same counter. A blob that nests statement
212 /// bodies past the depth limit must be rejected at decode time,
213 /// preventing stack-overflow DoS on untrusted input.
214 ///
215 /// The test runs on a dedicated thread with an 8 MiB stack because
216 /// the encode/decode walk down a `MAX_DECODE_DEPTH + 1`-deep Block
217 /// tree uses ~3–4× the native frames the default 2 MiB test stack
218 /// allocates. Without the explicit stack, the test itself
219 /// stack-overflows before the decode guard ever fires - masking
220 /// the real assertion.
221 #[test]
222 pub(crate) fn decode_depth_cap_rejects_deeply_nested_blocks() {
223 std::thread::Builder::new()
224 .stack_size(8 * 1024 * 1024)
225 .spawn(run_decode_depth_cap)
226 .expect("Fix: spawn test worker")
227 .join()
228 .expect("Fix: decode-depth-cap worker panicked");
229 }
230
231 fn run_decode_depth_cap() {
232 // Build the nested program iteratively so the test thread's
233 // stack only owns the tree, not a recursion chain the depth
234 // of the tree.
235 let mut inner = Node::Block(vec![]);
236 for _ in 0..MAX_DECODE_DEPTH {
237 inner = Node::Block(vec![inner]);
238 }
239 let program = Program::wrapped(
240 vec![BufferDecl::read_write("out", 0, DataType::U32)],
241 [1, 1, 1],
242 vec![inner],
243 );
244 let bytes = program
245 .to_wire()
246 .expect("Fix: building a (MAX_DEPTH+1)-nested program must still encode");
247 let decoded = Program::from_wire(&bytes);
248 assert!(
249 decoded.is_err(),
250 "decoding a program deeper than MAX_DECODE_DEPTH must fail; got Ok"
251 );
252 let err = decoded.unwrap_err().to_string();
253 assert!(
254 err.contains("Fix:"),
255 "depth-exceed error must carry a `Fix:` hint, got: {err}"
256 );
257 }
258}
259
260/// OPAQUE-001 regression: encoder and decoder must agree on the
261/// maximum opaque payload length. A payload at MAX_OPAQUE_PAYLOAD_LEN
262/// must encode; a payload one byte larger must fail at encode time.
263#[test]
264pub(crate) fn opaque_payload_limit_is_symmetric() {
265 use crate::ir::{Expr, ExprNode};
266 use std::any::Any;
267
268 #[derive(Debug)]
269 struct BigOpaque(Vec<u8>);
270 impl ExprNode for BigOpaque {
271 fn extension_kind(&self) -> &'static str {
272 "test.big"
273 }
274 fn debug_identity(&self) -> &str {
275 "test.big"
276 }
277 fn result_type(&self) -> Option<DataType> {
278 Some(DataType::U32)
279 }
280 fn cse_safe(&self) -> bool {
281 false
282 }
283 fn stable_fingerprint(&self) -> [u8; 32] {
284 [0; 32]
285 }
286 fn validate_extension(&self) -> Result<(), String> {
287 Ok(())
288 }
289 fn as_any(&self) -> &dyn Any {
290 self
291 }
292 fn wire_payload(&self) -> Vec<u8> {
293 self.0.clone()
294 }
295 }
296
297 // At the limit: must encode successfully.
298 let expr_ok = Expr::opaque(BigOpaque(vec![0u8; MAX_OPAQUE_PAYLOAD_LEN]));
299 let program_ok = Program::wrapped(
300 vec![BufferDecl::read_write("out", 0, DataType::U32)],
301 [1, 1, 1],
302 vec![Node::let_bind("_", expr_ok)],
303 );
304 assert!(
305 program_ok.to_wire().is_ok(),
306 "at-limit opaque payload ({MAX_OPAQUE_PAYLOAD_LEN} bytes) must encode"
307 );
308
309 // One byte over: must fail at encode time.
310 let expr_over = Expr::opaque(BigOpaque(vec![0u8; MAX_OPAQUE_PAYLOAD_LEN + 1]));
311 let program_over = Program::wrapped(
312 vec![BufferDecl::read_write("out", 0, DataType::U32)],
313 [1, 1, 1],
314 vec![Node::let_bind("_", expr_over)],
315 );
316 let err = program_over
317 .to_wire()
318 .expect_err("opaque payload exceeding MAX_OPAQUE_PAYLOAD_LEN must fail at encode");
319 let msg = err.to_string();
320 assert!(
321 msg.contains("MAX_OPAQUE_PAYLOAD_LEN") || msg.contains(&MAX_OPAQUE_PAYLOAD_LEN.to_string()),
322 "error should mention the limit, got: {msg}"
323 );
324}