cjc-runtime 0.1.9

Runtime library: values, builtins, tensors, COW buffers
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
//! Deterministic binary serialization for tensors and tensor lists.
//!
//! This module provides a small, self-contained, byte-stable format for
//! saving and loading f64 tensors. It lives in `cjc-runtime` (not
//! `cjc-snap`) because `cjc-snap` already depends on `cjc-runtime`, so
//! adding the reverse dependency would create a cycle.
//!
//! # Wire format
//!
//! All integers are little-endian, all floats are IEEE-754 f64 little-endian.
//!
//! ```text
//! offset  bytes  field
//! ------  -----  ------------------------------------------------------
//!      0      4  magic = b"CJCT"
//!      4      1  format version = 1
//!      5      3  reserved = 0
//!      8      8  n_tensors : u64
//!     16      -  tensor[0], tensor[1], ...
//!
//! tensor layout:
//!      0      8  ndim : u64
//!      8  ndim*8  shape[0..ndim] : u64[]
//!      *  numel*8  data : f64[]      (row-major, contiguous)
//!
//! after the last tensor:
//!      0      8  footer_hash : u64  (SplitMix64 fold of all preceding bytes)
//! ```
//!
//! The footer hash lets a reader cheaply detect corruption and lets tests
//! assert byte-identity across executors without parsing the payload.
//!
//! Determinism properties:
//! - Tensors are materialized with `to_vec()` so stride/offset views are
//!   flattened to a canonical row-major order before serialization.
//! - NaN bit patterns are preserved as-written (we do not canonicalize);
//!   CJC-Lang produces NaN only through explicit `0.0 / 0.0`-style paths,
//!   and the determinism contract never introduces spurious NaNs.
//! - The footer hash is a SplitMix64 fold, which is order-sensitive and
//!   deterministic across platforms (pure integer arithmetic, no FP).

use crate::tensor::Tensor;

const MAGIC: &[u8; 4] = b"CJCT";
const FORMAT_VERSION: u8 = 1;
const HEADER_LEN: usize = 16; // magic(4) + ver(1) + reserved(3) + n_tensors(8)

/// Errors returned by the tensor snap codec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TensorSnapError {
    TooShort,
    BadMagic,
    BadVersion(u8),
    TrailingGarbage,
    BadShape,
    BadHash { expected: u64, actual: u64 },
}

impl std::fmt::Display for TensorSnapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooShort => write!(f, "tensor snap: input too short"),
            Self::BadMagic => write!(f, "tensor snap: bad magic (expected CJCT)"),
            Self::BadVersion(v) => write!(f, "tensor snap: unsupported version {v}"),
            Self::TrailingGarbage => write!(f, "tensor snap: trailing garbage after footer"),
            Self::BadShape => write!(f, "tensor snap: corrupt shape header"),
            Self::BadHash { expected, actual } => {
                write!(f, "tensor snap: hash mismatch (expected {expected:#x}, got {actual:#x})")
            }
        }
    }
}

/// SplitMix64 folding hash. Pure integer arithmetic, deterministic across
/// platforms. Not cryptographic — used only for integrity/parity checks.
#[inline]
fn splitmix64_fold(bytes: &[u8]) -> u64 {
    let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
    // Mix length first so `[]` hashes differently from `[0x00 * 0]`.
    state ^= bytes.len() as u64;
    state = mix64(state);

    // Fold 8 bytes at a time.
    let mut i = 0;
    while i + 8 <= bytes.len() {
        let mut chunk = [0u8; 8];
        chunk.copy_from_slice(&bytes[i..i + 8]);
        state ^= u64::from_le_bytes(chunk);
        state = mix64(state);
        i += 8;
    }
    // Fold the trailing tail (0..7 bytes).
    if i < bytes.len() {
        let mut chunk = [0u8; 8];
        for (j, b) in bytes[i..].iter().enumerate() {
            chunk[j] = *b;
        }
        state ^= u64::from_le_bytes(chunk);
        state = mix64(state);
    }
    state
}

#[inline]
fn mix64(mut z: u64) -> u64 {
    z = z.wrapping_add(0x9e37_79b9_7f4a_7c15);
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

/// Encode a list of tensors into the wire format. Infallible for any
/// well-formed `Tensor` (materializes views via `to_vec`).
pub fn encode_list(tensors: &[Tensor]) -> Vec<u8> {
    // Estimate capacity to avoid reallocation.
    let mut cap = HEADER_LEN + 8; // + footer
    for t in tensors {
        cap += 8 + 8 * t.ndim() + 8 * t.shape().iter().product::<usize>();
    }
    let mut buf = Vec::with_capacity(cap);

    // Header
    buf.extend_from_slice(MAGIC);
    buf.push(FORMAT_VERSION);
    buf.extend_from_slice(&[0u8; 3]); // reserved
    buf.extend_from_slice(&(tensors.len() as u64).to_le_bytes());

    // Tensors
    for t in tensors {
        let shape = t.shape();
        buf.extend_from_slice(&(shape.len() as u64).to_le_bytes());
        for &d in shape {
            buf.extend_from_slice(&(d as u64).to_le_bytes());
        }
        let data = t.to_vec();
        for v in &data {
            buf.extend_from_slice(&v.to_le_bytes());
        }
    }

    // Footer hash over everything so far.
    let hash = splitmix64_fold(&buf);
    buf.extend_from_slice(&hash.to_le_bytes());
    buf
}

/// Encode a single tensor (convenience wrapper).
pub fn encode_one(tensor: &Tensor) -> Vec<u8> {
    encode_list(std::slice::from_ref(tensor))
}

/// Decode a list of tensors from the wire format. Verifies magic, version,
/// and footer hash.
pub fn decode_list(bytes: &[u8]) -> Result<Vec<Tensor>, TensorSnapError> {
    if bytes.len() < HEADER_LEN + 8 {
        return Err(TensorSnapError::TooShort);
    }
    if &bytes[0..4] != MAGIC {
        return Err(TensorSnapError::BadMagic);
    }
    let version = bytes[4];
    if version != FORMAT_VERSION {
        return Err(TensorSnapError::BadVersion(version));
    }

    // Verify footer hash over everything except the last 8 bytes.
    let footer_start = bytes.len() - 8;
    let expected_hash = u64::from_le_bytes([
        bytes[footer_start],
        bytes[footer_start + 1],
        bytes[footer_start + 2],
        bytes[footer_start + 3],
        bytes[footer_start + 4],
        bytes[footer_start + 5],
        bytes[footer_start + 6],
        bytes[footer_start + 7],
    ]);
    let actual_hash = splitmix64_fold(&bytes[..footer_start]);
    if expected_hash != actual_hash {
        return Err(TensorSnapError::BadHash {
            expected: expected_hash,
            actual: actual_hash,
        });
    }

    // n_tensors
    let n_tensors = read_u64(bytes, 8)? as usize;
    let mut cursor = HEADER_LEN;
    let mut out = Vec::with_capacity(n_tensors);

    for _ in 0..n_tensors {
        if cursor + 8 > footer_start {
            return Err(TensorSnapError::TooShort);
        }
        let ndim = read_u64(bytes, cursor)? as usize;
        cursor += 8;

        // Cap ndim to a sane value to avoid pathological allocation.
        if ndim > 16 {
            return Err(TensorSnapError::BadShape);
        }
        if cursor + 8 * ndim > footer_start {
            return Err(TensorSnapError::TooShort);
        }

        let mut shape = Vec::with_capacity(ndim);
        for _ in 0..ndim {
            let d = read_u64(bytes, cursor)? as usize;
            shape.push(d);
            cursor += 8;
        }

        // Guard against shape-overflow DoS.
        let numel = shape.iter().try_fold(1usize, |acc, &d| acc.checked_mul(d))
            .ok_or(TensorSnapError::BadShape)?;

        if cursor + 8 * numel > footer_start {
            return Err(TensorSnapError::TooShort);
        }

        let mut data = Vec::with_capacity(numel);
        for _ in 0..numel {
            let mut chunk = [0u8; 8];
            chunk.copy_from_slice(&bytes[cursor..cursor + 8]);
            data.push(f64::from_le_bytes(chunk));
            cursor += 8;
        }

        let t = Tensor::from_vec(data, &shape).map_err(|_| TensorSnapError::BadShape)?;
        out.push(t);
    }

    if cursor != footer_start {
        return Err(TensorSnapError::TrailingGarbage);
    }
    Ok(out)
}

/// Decode a single tensor from the wire format. Errors if the payload
/// contains zero or more than one tensor.
pub fn decode_one(bytes: &[u8]) -> Result<Tensor, TensorSnapError> {
    let list = decode_list(bytes)?;
    if list.len() != 1 {
        return Err(TensorSnapError::BadShape);
    }
    Ok(list.into_iter().next().unwrap())
}

/// Deterministic content hash of a tensor list. Separate from the wire
/// format's footer hash — this one hashes *logical* content (shape + data)
/// only, so it is invariant under re-encoding.
pub fn hash_list(tensors: &[Tensor]) -> u64 {
    let mut state: u64 = 0x243F_6A88_85A3_08D3; // arbitrary constant
    state ^= tensors.len() as u64;
    state = mix64(state);
    for t in tensors {
        let shape = t.shape();
        state ^= shape.len() as u64;
        state = mix64(state);
        for &d in shape {
            state ^= d as u64;
            state = mix64(state);
        }
        let data = t.to_vec();
        // Fold the f64 bits (NaN-bit-preserving — determinism relies on the
        // caller not producing garbage NaN bit patterns).
        for v in &data {
            state ^= v.to_bits();
            state = mix64(state);
        }
    }
    state
}

fn read_u64(bytes: &[u8], offset: usize) -> Result<u64, TensorSnapError> {
    if offset + 8 > bytes.len() {
        return Err(TensorSnapError::TooShort);
    }
    let mut chunk = [0u8; 8];
    chunk.copy_from_slice(&bytes[offset..offset + 8]);
    Ok(u64::from_le_bytes(chunk))
}

// =============================================================================
// Unit tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn t(data: Vec<f64>, shape: &[usize]) -> Tensor {
        Tensor::from_vec(data, shape).unwrap()
    }

    #[test]
    fn empty_list_roundtrips() {
        let bytes = encode_list(&[]);
        let out = decode_list(&bytes).unwrap();
        assert_eq!(out.len(), 0);
    }

    #[test]
    fn scalar_tensor_roundtrips() {
        let a = t(vec![42.0], &[1]);
        let bytes = encode_one(&a);
        let b = decode_one(&bytes).unwrap();
        assert_eq!(b.shape(), &[1]);
        assert_eq!(b.to_vec(), vec![42.0]);
    }

    #[test]
    fn matrix_roundtrips() {
        let a = t(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
        let bytes = encode_one(&a);
        let b = decode_one(&bytes).unwrap();
        assert_eq!(b.shape(), &[2, 3]);
        assert_eq!(b.to_vec(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
    }

    #[test]
    fn multiple_tensors_roundtrip() {
        let a = t(vec![1.0, 2.0], &[2]);
        let b = t(vec![3.0, 4.0, 5.0, 6.0], &[2, 2]);
        let c = t(vec![7.0], &[1, 1]);
        let bytes = encode_list(&[a.clone(), b.clone(), c.clone()]);
        let out = decode_list(&bytes).unwrap();
        assert_eq!(out.len(), 3);
        assert_eq!(out[0].to_vec(), a.to_vec());
        assert_eq!(out[1].to_vec(), b.to_vec());
        assert_eq!(out[2].to_vec(), c.to_vec());
    }

    #[test]
    fn encoding_is_deterministic() {
        let a = t(vec![1.5, -2.5, 3.25], &[3]);
        let e1 = encode_one(&a);
        let e2 = encode_one(&a);
        assert_eq!(e1, e2, "encoding must be byte-identical for the same input");
    }

    #[test]
    fn different_tensors_produce_different_encodings() {
        let a = t(vec![1.0, 2.0], &[2]);
        let b = t(vec![1.0, 2.0, 3.0], &[3]);
        assert_ne!(encode_one(&a), encode_one(&b));
    }

    #[test]
    fn different_shapes_same_data_produce_different_encodings() {
        let a = t(vec![1.0, 2.0, 3.0, 4.0], &[4]);
        let b = t(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
        assert_ne!(encode_one(&a), encode_one(&b));
    }

    #[test]
    fn bad_magic_is_rejected() {
        let a = t(vec![1.0], &[1]);
        let mut bytes = encode_one(&a);
        bytes[0] = b'X';
        assert!(matches!(decode_list(&bytes), Err(TensorSnapError::BadMagic)));
    }

    #[test]
    fn bad_version_is_rejected() {
        let a = t(vec![1.0], &[1]);
        let mut bytes = encode_one(&a);
        bytes[4] = 99;
        assert!(matches!(decode_list(&bytes), Err(TensorSnapError::BadVersion(99))));
    }

    #[test]
    fn hash_mismatch_is_rejected() {
        let a = t(vec![1.0, 2.0, 3.0], &[3]);
        let mut bytes = encode_one(&a);
        // Flip one data byte
        let idx = HEADER_LEN + 8 + 8; // past ndim + shape[0]
        bytes[idx] ^= 0xFF;
        assert!(matches!(decode_list(&bytes), Err(TensorSnapError::BadHash { .. })));
    }

    #[test]
    fn too_short_is_rejected() {
        assert!(matches!(decode_list(&[]), Err(TensorSnapError::TooShort)));
        assert!(matches!(decode_list(&[0u8; 10]), Err(TensorSnapError::TooShort)));
    }

    #[test]
    fn hash_list_is_deterministic() {
        let a = t(vec![1.0, 2.0, 3.0], &[3]);
        let b = t(vec![4.0, 5.0], &[2]);
        let h1 = hash_list(&[a.clone(), b.clone()]);
        let h2 = hash_list(&[a.clone(), b.clone()]);
        assert_eq!(h1, h2);
    }

    #[test]
    fn hash_list_is_order_sensitive() {
        let a = t(vec![1.0, 2.0, 3.0], &[3]);
        let b = t(vec![4.0, 5.0], &[2]);
        let h1 = hash_list(&[a.clone(), b.clone()]);
        let h2 = hash_list(&[b, a]);
        assert_ne!(h1, h2, "hash must change when order changes");
    }

    #[test]
    fn hash_list_distinguishes_shapes_and_data() {
        let a = t(vec![1.0, 2.0, 3.0, 4.0], &[4]);
        let b = t(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
        let c = t(vec![1.0, 2.0, 3.0, 5.0], &[4]);
        assert_ne!(hash_list(&[a.clone()]), hash_list(&[b]));
        assert_ne!(hash_list(&[a]), hash_list(&[c]));
    }

    #[test]
    fn pathological_ndim_is_rejected() {
        // Construct a blob with ndim=1000 in the header — should error out
        // before attempting to allocate.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(MAGIC);
        bytes.push(FORMAT_VERSION);
        bytes.extend_from_slice(&[0u8; 3]);
        bytes.extend_from_slice(&1u64.to_le_bytes()); // n_tensors
        bytes.extend_from_slice(&1000u64.to_le_bytes()); // ndim = 1000
        let hash = splitmix64_fold(&bytes);
        bytes.extend_from_slice(&hash.to_le_bytes());
        assert!(matches!(decode_list(&bytes), Err(TensorSnapError::BadShape)));
    }

    #[test]
    fn shape_overflow_is_rejected() {
        // ndim=2, shape=[usize::MAX, 2] — multiplying should overflow.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(MAGIC);
        bytes.push(FORMAT_VERSION);
        bytes.extend_from_slice(&[0u8; 3]);
        bytes.extend_from_slice(&1u64.to_le_bytes());
        bytes.extend_from_slice(&2u64.to_le_bytes()); // ndim
        bytes.extend_from_slice(&u64::MAX.to_le_bytes());
        bytes.extend_from_slice(&2u64.to_le_bytes());
        let hash = splitmix64_fold(&bytes);
        bytes.extend_from_slice(&hash.to_le_bytes());
        assert!(matches!(decode_list(&bytes), Err(TensorSnapError::BadShape)));
    }
}