sdx 1.13.0

Native Xet client library for Shardline's Xet frontend.
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
//! Parsing and decoding of serialized Xorb byte ranges (M2a).
//!
//! The Xet download path fetches a **byte range** of a serialized xorb (the
//! chunk payload, excluding the footer), so a reader must be able to walk the
//! chunk stream without any footer metadata. This module is therefore
//! **footer-less tolerant** (`docs/SDX_PLAN.md` §7.8): it decodes the chunk
//! stream sequentially via the pinned upstream `xet-core-structures` public
//! API [`deserialize_chunks`] — the same call the reference client uses for
//! ranged xorb fetches
//! (`xet-client-1.5.4/src/cas_client/remote_client.rs:455`) — and exposes each
//! decoded chunk with its data hash (BLAKE3 `DATA_KEY`, M0
//! [`compute_chunk_hash`]).
//!
//! ByteGrouping4LZ4 / chunk deserialization is **not reimplemented**; the
//! pinned `xet-core-structures` crate owns the format (plan §4.1 / §11 Q3).

use std::io::{Cursor, Write};

use bytes::Bytes;
use thiserror::Error;
use xet_core_structures::error::CoreError;
use xet_core_structures::merklehash::MerkleHash;
use xet_core_structures::xorb_object::{
    XORB_CHUNK_HEADER_LENGTH, deserialize_chunks, deserialize_chunks_to_writer, parse_chunk_header,
};

use crate::hash::compute_chunk_hash;

/// Failure to decode a serialized xorb byte range.
#[derive(Debug, Error)]
pub enum XorbError {
    /// The serialized chunk stream was malformed or corrupted.
    #[error("failed to parse serialized xorb: {0}")]
    Format(#[from] CoreError),
    /// A decoded chunk's byte offsets were inconsistent with the data.
    #[error("xorb chunk byte offsets are inconsistent with the decoded data")]
    InconsistentChunkOffsets,
}

/// A single decoded chunk from a serialized xorb byte range.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedChunk {
    /// Decompressed chunk data.
    pub data: Vec<u8>,
    /// Data hash of the chunk: `compute_chunk_hash(data)` (BLAKE3 `DATA_KEY`).
    pub hash: MerkleHash,
}

/// Decompressed chunk payload with per-chunk byte offsets, for zero-copy
/// slicing of a fetched xorb byte range (the streaming download path).
///
/// `data` is the concatenation of every decoded chunk payload in fetch order;
/// `chunk_offsets` records the start offset of each chunk within `data` (the
/// first entry is always `0`, and the length is `num_chunks + 1`, mirroring the
/// upstream `deserialize_chunks` byte-index contract).
#[derive(Debug, Clone)]
pub struct DecodedChunkData {
    /// Concatenated decompressed chunk payloads.
    pub data: Bytes,
    /// Start byte offset of each chunk within `data`.
    pub chunk_offsets: Vec<usize>,
}

/// Reader over serialized xorb bytes.
///
/// Constructed from a fetched xorb byte range (see
/// [`crate::transfer::TransferClient::fetch_xorb_range`]). The bytes are the
/// concatenated serialized chunk payload; the footer is not required.
#[derive(Debug, Clone)]
pub struct XorbReader {
    bytes: Vec<u8>,
}

impl XorbReader {
    /// Creates a reader over the serialized chunk payload `bytes`.
    #[must_use]
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self { bytes }
    }

    /// Decodes the chunk stream into a single concatenated payload with
    /// per-chunk byte offsets, without copying each chunk into its own buffer.
    ///
    /// Used by the streaming download path ([`crate::stream`]) where a fetched
    /// xorb byte range is sliced into per-file-term bytes zero-copy. Equivalent
    /// to the reference client's `deserialize_chunks` usage for ranged xorb
    /// fetches (`xet-data-1.5.4` `xorb_block.rs` `build_chunk_offsets`).
    ///
    /// # Errors
    ///
    /// Returns [`XorbError::Format`] when the chunk stream is malformed or a
    /// chunk fails to decompress.
    pub fn decode_chunk_data(&self) -> Result<DecodedChunkData, XorbError> {
        let (data, offsets) = deserialize_chunks(&mut Cursor::new(self.bytes.as_slice()))?;
        Ok(DecodedChunkData {
            data: Bytes::from(data),
            chunk_offsets: offsets
                .into_iter()
                .map(|offset| usize::try_from(offset).unwrap_or(usize::MAX))
                .collect(),
        })
    }

    /// Decodes within a buffer reservation, checking upstream chunk headers
    /// before decompressing and bounding the decoder's output writer as well.
    pub(crate) fn decode_chunk_data_bounded(
        &self,
        limit: usize,
    ) -> Result<DecodedChunkData, XorbError> {
        let mut position = 0usize;
        let mut decoded_size = 0usize;
        let mut chunk_count = 0usize;
        while position < self.bytes.len() {
            chunk_count = chunk_count.saturating_add(1);
            if chunk_count > 8192 {
                return Err(XorbError::InconsistentChunkOffsets);
            }
            let header_end = position
                .checked_add(XORB_CHUNK_HEADER_LENGTH)
                .ok_or(XorbError::InconsistentChunkOffsets)?;
            let header_bytes = self
                .bytes
                .get(position..header_end)
                .ok_or(XorbError::InconsistentChunkOffsets)?;
            let header = parse_chunk_header(
                header_bytes
                    .try_into()
                    .map_err(|_error| XorbError::InconsistentChunkOffsets)?,
            )?;
            decoded_size = decoded_size
                .checked_add(header.get_uncompressed_length() as usize)
                .filter(|size| *size <= limit)
                .ok_or_else(|| {
                    XorbError::Format(CoreError::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "decoded xorb exceeds buffer reservation",
                    )))
                })?;
            position = header_end
                .checked_add(header.get_compressed_length() as usize)
                .filter(|end| *end <= self.bytes.len())
                .ok_or(XorbError::InconsistentChunkOffsets)?;
        }
        let mut writer = BoundedChunkWriter {
            data: Vec::with_capacity(decoded_size),
            limit: decoded_size,
        };
        let (_, offsets) =
            deserialize_chunks_to_writer(&mut Cursor::new(self.bytes.as_slice()), &mut writer)?;
        Ok(DecodedChunkData {
            data: Bytes::from(writer.data),
            chunk_offsets: offsets
                .into_iter()
                .map(|offset| usize::try_from(offset).unwrap_or(usize::MAX))
                .collect(),
        })
    }

    /// Decodes every chunk in the serialized payload, in order.
    ///
    /// Each chunk is decompressed and its data hash computed. Chunk headers are
    /// validated by the upstream decoder (compression scheme, length bounds,
    /// and the uncompressed-length-vs-header agreement), so a corrupted stream
    /// surfaces as [`XorbError::Format`].
    ///
    /// # Errors
    ///
    /// Returns [`XorbError::Format`] when the chunk stream is malformed or a
    /// chunk fails to decompress, and [`XorbError::InconsistentChunkOffsets`]
    /// when the decoder's chunk offsets disagree with the decoded data length.
    pub fn decode_chunks(&self) -> Result<Vec<DecodedChunk>, XorbError> {
        let (data, offsets) = deserialize_chunks(&mut Cursor::new(self.bytes.as_slice()))?;
        let mut chunks = Vec::with_capacity(offsets.len().saturating_sub(1));
        let mut previous_offset: Option<u32> = None;
        for offset in offsets {
            if let Some(start) = previous_offset {
                let end = offset;
                let chunk_bytes = data
                    .get(start as usize..end as usize)
                    .ok_or(XorbError::InconsistentChunkOffsets)?;
                let hash = compute_chunk_hash(chunk_bytes);
                chunks.push(DecodedChunk {
                    data: chunk_bytes.to_vec(),
                    hash,
                });
            }
            previous_offset = Some(offset);
        }
        Ok(chunks)
    }
}

struct BoundedChunkWriter {
    data: Vec<u8>,
    limit: usize,
}

impl Write for BoundedChunkWriter {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        if self
            .data
            .len()
            .checked_add(bytes.len())
            .is_none_or(|size| size > self.limit)
        {
            return Err(std::io::Error::other(
                "decoded xorb exceeds buffer reservation",
            ));
        }
        self.data
            .try_reserve_exact(bytes.len())
            .map_err(std::io::Error::other)?;
        self.data.extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use xet_core_structures::merklehash::MerkleHash;
    use xet_core_structures::xorb_object::{CompressionScheme, serialize_chunk};

    #[test]
    fn bounded_decode_rejects_declared_output_before_decompression() {
        let mut payload = Vec::new();
        serialize_chunk(&vec![7u8; 4096], &mut payload, CompressionScheme::LZ4).unwrap();
        let reader = super::XorbReader::new(payload);
        assert!(matches!(
            reader.decode_chunk_data_bounded(8),
            Err(super::XorbError::Format(_))
        ));
        let decoded = reader.decode_chunk_data_bounded(4096).unwrap();
        assert_eq!(decoded.data.as_ref(), vec![7u8; 4096]);
    }

    #[test]
    fn bounded_decode_limits_zero_length_chunk_metadata() {
        let one = [0u8; 8];
        let payload = one.repeat(8193);
        assert!(matches!(
            super::XorbReader::new(payload).decode_chunk_data_bounded(1),
            Err(super::XorbError::InconsistentChunkOffsets)
        ));
    }

    use super::{DecodedChunk, XorbError, XorbReader};
    use crate::hash::compute_chunk_hash;

    /// Serializes the given chunk payloads (without a footer) using the
    /// pinned upstream chunk serializer.
    fn serialize_payload(chunks: &[&[u8]]) -> Vec<u8> {
        let mut payload = Vec::new();
        for chunk in chunks {
            serialize_chunk(chunk, &mut payload, CompressionScheme::None).unwrap();
        }
        payload
    }

    fn expected_chunks(chunks: &[&[u8]]) -> Vec<DecodedChunk> {
        chunks
            .iter()
            .map(|data| DecodedChunk {
                data: data.to_vec(),
                hash: compute_chunk_hash(data),
            })
            .collect()
    }

    #[test]
    fn decode_chunks_round_trips_payload_without_footer() {
        let chunk_a = b"hello xet chunk";
        let chunk_b = b"second chunk payload";
        let payload = serialize_payload(&[chunk_a, chunk_b]);

        let decoded = XorbReader::new(payload).decode_chunks().unwrap();

        assert_eq!(decoded, expected_chunks(&[chunk_a, chunk_b]));
    }

    #[test]
    fn decode_chunks_single_chunk() {
        let chunk = b"just one chunk";
        let payload = serialize_payload(&[chunk]);

        let decoded = XorbReader::new(payload).decode_chunks().unwrap();

        assert_eq!(decoded, expected_chunks(&[chunk]));
    }

    #[test]
    fn decode_chunks_empty_payload_yields_no_chunks() {
        let decoded = XorbReader::new(Vec::new()).decode_chunks().unwrap();
        assert!(decoded.is_empty());
    }

    #[test]
    fn decode_chunks_rejects_truncated_chunk() {
        let chunk = b"truncated-chunk-data";
        let mut payload = serialize_payload(&[chunk]);
        payload.truncate(payload.len() - 3);

        let result = XorbReader::new(payload).decode_chunks();
        assert!(matches!(result, Err(XorbError::Format(_))));
    }

    #[test]
    fn decode_chunks_rejects_footer_appended_after_payload() {
        // A full serialized xorb (payload + footer) must NOT be fed to the
        // chunk-stream decoder: the footer's "XETBLOB" ident is rejected by
        // the chunk header parser. Footer parsing is XorbObject::deserialize's
        // job; the transfer endpoint serves payload-only ranges.
        let chunk = b"with-footer";
        let mut payload = serialize_payload(&[chunk]);
        payload.extend_from_slice(&[b'X', b'E', b'T', b'B', b'L', b'O', b'B', 1, 0, 0, 0]);

        let result = XorbReader::new(payload).decode_chunks();
        assert!(matches!(result, Err(XorbError::Format(_))));
    }

    #[test]
    fn decode_chunks_computes_data_hashes() {
        let chunk = b"hash me";
        let payload = serialize_payload(&[chunk]);
        let decoded = XorbReader::new(payload).decode_chunks().unwrap();
        assert_eq!(decoded[0].hash, compute_chunk_hash(chunk));
        assert_ne!(decoded[0].hash, compute_chunk_hash(b"hash different"));
    }

    #[test]
    fn decode_chunks_handles_incompressible_data() {
        // CompressionScheme::None keeps data byte-identical even for highly
        // compressible input; use a varied payload to exercise the path.
        let chunk: Vec<u8> = (0..512).map(|i| (i * 31 % 251) as u8).collect();
        let payload = serialize_payload(&[&chunk]);
        let decoded = XorbReader::new(payload).decode_chunks().unwrap();
        assert_eq!(decoded[0].data, chunk);
    }

    #[test]
    fn term_verification_hash_matches_xorb_footer_chunk_range_hash() {
        use std::io::Cursor;

        use xet_core_structures::merklehash::xorb_hash;
        use xet_core_structures::xorb_object::{XorbObject, XorbObjectInfoV1, serialize_chunk};

        // Build a full serialized xorb (payload + footer) using the pinned
        // upstream public API, then confirm that the term verification hash
        // computed from the *decoded* chunk hashes equals the xorb footer's
        // authoritative `generate_chunk_range_hash` (range_hash_from_chunks /
        // VERIFICATION_KEY) over its stored chunk table.
        let chunks: [Vec<u8>; 3] = [
            b"first chunk of the xorb".to_vec(),
            b"second chunk of the xorb".to_vec(),
            b"third chunk of the xorb".to_vec(),
        ];
        let chunk_hashes: Vec<MerkleHash> = chunks
            .iter()
            .map(|chunk| compute_chunk_hash(chunk))
            .collect();

        let mut payload = Vec::new();
        let mut boundaries: Vec<u32> = Vec::new();
        let mut unpacked: Vec<u32> = Vec::new();
        let mut packed_total: u32 = 0;
        let mut unpacked_total: u32 = 0;
        for chunk in &chunks {
            let written = serialize_chunk(chunk, &mut payload, CompressionScheme::None).unwrap();
            packed_total = packed_total.saturating_add(u32::try_from(written).unwrap());
            boundaries.push(packed_total);
            unpacked_total = unpacked_total.saturating_add(u32::try_from(chunk.len()).unwrap());
            unpacked.push(unpacked_total);
        }

        let mut info = XorbObjectInfoV1::default();
        info.xorb_hash = xorb_hash(
            &chunks
                .iter()
                .map(|chunk| {
                    (
                        compute_chunk_hash(chunk),
                        u64::try_from(chunk.len()).unwrap(),
                    )
                })
                .collect::<Vec<_>>(),
        );
        info.num_chunks = u32::try_from(chunks.len()).unwrap();
        info.chunk_hashes = chunk_hashes.clone();
        info.chunk_boundary_offsets = boundaries;
        info.unpacked_chunk_offsets = unpacked;
        info.fill_in_boundary_offsets();
        // Content payload length excludes the footer.
        let content_len = usize::try_from(packed_total).unwrap();
        let (_xorb_object, _footer_len) =
            XorbObject::serialize_given_info(&mut payload, info).unwrap();

        // Decode the content payload (footer excluded).
        let decoded = XorbReader::new(payload[..content_len].to_vec())
            .decode_chunks()
            .unwrap();
        let decoded_hashes: Vec<MerkleHash> = decoded.iter().map(|chunk| chunk.hash).collect();
        let computed = crate::hash::compute_term_verification_hash(&decoded_hashes);

        // The footer's authoritative chunk-range hash over the same chunk range.
        let xorb = XorbObject::deserialize(&mut Cursor::new(payload.as_slice())).unwrap();
        let authoritative = xorb
            .generate_chunk_range_hash(0, u32::try_from(chunks.len()).unwrap())
            .unwrap();

        assert_eq!(computed, authoritative);
        assert_eq!(decoded_hashes, chunk_hashes);
    }
}