Skip to main content

dora_node_api/node/
arrow_utils.rs

1//! Utility functions for converting Arrow arrays to/from raw data.
2//!
3pub mod ipc_encode;
4
5use arrow::array::ArrayData;
6use eyre::Context;
7
8/// Maximum Arrow IPC payload size (256 MB).
9const MAX_IPC_BYTES: usize = 256 * 1024 * 1024;
10
11/// Alignment guaranteed for every raw Arrow buffer inside Dora payloads.
12///
13/// Arrow kernels can issue SIMD loads from buffer bases. Some ARM platforms
14/// fault on under-aligned SIMD loads, so every body buffer of an Arrow IPC
15/// stream is placed at a 64-byte boundary relative to the payload base.
16pub(crate) const ARROW_BUFFER_ALIGNMENT: usize = 64;
17pub(crate) const ARROW_BUFFER_ALIGNMENT_EXPONENT: u8 =
18    ARROW_BUFFER_ALIGNMENT.trailing_zeros() as u8;
19const _: () = assert!(ARROW_BUFFER_ALIGNMENT.is_power_of_two());
20
21/// Encode an Arrow [`ArrayData`] into an Arrow IPC stream byte buffer.
22///
23/// The resulting buffer contains a full IPC stream: schema message, one record
24/// batch, and an end-of-stream marker. This is self-describing and can be
25/// decoded without external type information.
26pub fn encode_arrow_ipc(arrow_array: &ArrayData) -> eyre::Result<Vec<u8>> {
27    use arrow::ipc::writer::StreamWriter;
28    use arrow::record_batch::RecordBatch;
29    use arrow_schema::{Field, Schema};
30    use std::sync::Arc;
31
32    let schema = Schema::new(vec![Field::new(
33        "data",
34        arrow_array.data_type().clone(),
35        true,
36    )]);
37    let schema_ref = Arc::new(schema);
38
39    let array_ref = arrow::array::make_array(arrow_array.clone());
40    let batch = RecordBatch::try_new(schema_ref.clone(), vec![array_ref])
41        .context("failed to create RecordBatch for IPC encoding")?;
42
43    let mut buf = Vec::new();
44    {
45        let mut writer = StreamWriter::try_new(&mut buf, &schema_ref)
46            .context("failed to create Arrow IPC StreamWriter")?;
47        writer
48            .write(&batch)
49            .context("failed to write RecordBatch to IPC stream")?;
50        writer
51            .finish()
52            .context("failed to finish Arrow IPC stream")?;
53    }
54    Ok(buf)
55}
56
57/// Decode an Arrow IPC stream byte buffer back into [`ArrayData`].
58///
59/// Expects the buffer to contain exactly one record batch with a single
60/// column named `"data"`, as produced by [`encode_arrow_ipc`].
61pub fn decode_arrow_ipc(ipc_buf: &[u8]) -> eyre::Result<ArrayData> {
62    use arrow::ipc::reader::StreamReader;
63    use std::io::Cursor;
64
65    if ipc_buf.len() > MAX_IPC_BYTES {
66        eyre::bail!(
67            "Arrow IPC payload too large: {} bytes (max {MAX_IPC_BYTES})",
68            ipc_buf.len()
69        );
70    }
71
72    let cursor = Cursor::new(ipc_buf);
73    let mut reader =
74        StreamReader::try_new(cursor, None).context("failed to open Arrow IPC stream")?;
75
76    let batch = reader
77        .next()
78        .ok_or_else(|| eyre::eyre!("Arrow IPC stream contained no record batches"))?
79        .context("failed to read RecordBatch from IPC stream")?;
80
81    if batch.num_columns() != 1 {
82        eyre::bail!(
83            "expected 1 column in IPC record batch, got {}",
84            batch.num_columns()
85        );
86    }
87
88    Ok(batch.column(0).to_data())
89}
90
91/// Decode an Arrow IPC stream from an Arrow [`Buffer`] **without copying** the
92/// payload buffers when they are properly aligned.
93///
94/// Unlike [`decode_arrow_ipc`], which reads from a byte slice through
95/// `StreamReader` (and therefore allocates a fresh buffer and copies every
96/// array buffer out of the stream), this uses
97/// [`arrow::ipc::reader::StreamDecoder`], which slices the array buffers
98/// directly out of the provided [`Buffer`]. When the input buffer is suitably
99/// aligned — as Dora's shared-memory payloads always are (128-byte `AVec` /
100/// page-aligned Zenoh SHM) — the decoded array aliases the input and no payload
101/// copy happens.
102///
103/// The decoder runs with the default `require_alignment = false`, so an
104/// under-aligned input (e.g. an arbitrary heap `Vec`) is handled gracefully by
105/// copying just the misaligned buffers rather than erroring. This keeps the
106/// receive path robust while preserving zero-copy for the common SHM case.
107pub fn decode_arrow_ipc_zero_copy(
108    mut buffer: arrow::buffer::Buffer,
109) -> eyre::Result<arrow::array::ArrayData> {
110    use arrow::ipc::reader::StreamDecoder;
111
112    if buffer.len() > MAX_IPC_BYTES {
113        eyre::bail!(
114            "Arrow IPC payload too large: {} bytes (max {MAX_IPC_BYTES})",
115            buffer.len()
116        );
117    }
118
119    let mut decoder = StreamDecoder::new();
120    let mut batch = None;
121    // `decode` is push-based: it may consume the schema message and return
122    // `None` before yielding the record batch, so loop until we get a batch or
123    // exhaust the input.
124    while !buffer.is_empty() {
125        let before = buffer.len();
126        if let Some(b) = decoder
127            .decode(&mut buffer)
128            .context("failed to decode Arrow IPC stream")?
129        {
130            batch = Some(b);
131            break;
132        }
133        // `decode` must consume bytes when it yields no batch; a crafted or
134        // truncated payload that leaves the buffer unchanged would otherwise
135        // spin this loop forever on the zenoh IO worker. Bail instead.
136        if buffer.len() == before {
137            eyre::bail!("Arrow IPC decoder made no progress on a partial/corrupt stream");
138        }
139    }
140
141    let batch = batch.ok_or_else(|| eyre::eyre!("Arrow IPC stream contained no record batches"))?;
142
143    if batch.num_columns() != 1 {
144        eyre::bail!(
145            "expected 1 column in IPC record batch, got {}",
146            batch.num_columns()
147        );
148    }
149
150    Ok(batch.column(0).to_data())
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use arrow::array::{Array, StringArray, UInt64Array};
157
158    #[test]
159    fn ipc_roundtrip_primitive() {
160        let array = UInt64Array::from(vec![1, 2, 3, 4, 5]);
161        let data = array.into_data();
162        let encoded = encode_arrow_ipc(&data).unwrap();
163        let decoded = decode_arrow_ipc(&encoded).unwrap();
164        assert_eq!(data, decoded);
165    }
166
167    /// Copy `bytes` into a 128-byte-aligned buffer, mirroring how Dora's
168    /// receive path backs IPC payloads (an `AVec<u8, ConstAlign<128>>` for the
169    /// daemon path, page-aligned Zenoh SHM for the zero-copy path). This is the
170    /// precondition under which `decode_arrow_ipc_zero_copy` aliases the input.
171    fn aligned_buffer_from(bytes: &[u8]) -> (arrow::buffer::Buffer, usize, usize) {
172        use aligned_vec::{AVec, ConstAlign};
173        use std::ptr::NonNull;
174
175        let mut aligned: AVec<u8, ConstAlign<128>> = AVec::__from_elem(128, 0, bytes.len());
176        aligned.copy_from_slice(bytes);
177        let base = aligned.as_ptr() as usize;
178        let len = aligned.len();
179        let ptr = NonNull::new(aligned.as_ptr() as *mut u8).unwrap();
180        // SAFETY: `ptr`/`len` describe `aligned`'s allocation, which the Arc
181        // keeps alive for the Buffer's lifetime.
182        let buffer = unsafe {
183            arrow::buffer::Buffer::from_custom_allocation(ptr, len, std::sync::Arc::new(aligned))
184        };
185        (buffer, base, len)
186    }
187
188    #[test]
189    fn ipc_zero_copy_roundtrip_primitive() {
190        let array = UInt64Array::from((0..1000u64).collect::<Vec<_>>());
191        let data = array.into_data();
192        let encoded = encode_arrow_ipc(&data).unwrap();
193        let (buffer, _, _) = aligned_buffer_from(&encoded);
194        let decoded = decode_arrow_ipc_zero_copy(buffer).unwrap();
195        assert_eq!(data, decoded);
196    }
197
198    /// The headline claim: for an aligned input buffer the decoded array's data
199    /// buffer points *into* the input allocation (no payload copy), and the
200    /// strict `require_alignment(true)` decoder accepts it without falling back
201    /// to a realigning copy.
202    #[test]
203    fn ipc_decode_is_zero_copy_for_aligned_buffer() {
204        use arrow::ipc::reader::StreamDecoder;
205
206        // A large primitive array so the data buffer dominates and any copy
207        // would be unmistakable.
208        let array = UInt64Array::from((0..100_000u64).collect::<Vec<_>>());
209        let data = array.into_data();
210        let encoded = encode_arrow_ipc(&data).unwrap();
211
212        // 1) Proof via the strict decoder: require_alignment(true) errors if any
213        //    buffer would need realigning. A clean decode proves the body
214        //    buffers are used in place.
215        {
216            let (mut buffer, _, _) = aligned_buffer_from(&encoded);
217            let mut decoder = StreamDecoder::new().with_require_alignment(true);
218            let mut got = None;
219            while !buffer.is_empty() {
220                if let Some(b) = decoder
221                    .decode(&mut buffer)
222                    .expect("aligned IPC buffer must decode without realignment")
223                {
224                    got = Some(b);
225                    break;
226                }
227            }
228            assert_eq!(got.unwrap().column(0).to_data(), data);
229        }
230
231        // 2) Proof via pointer aliasing: the decoded data buffer lies within the
232        //    input allocation's address range.
233        {
234            let (buffer, base, len) = aligned_buffer_from(&encoded);
235            let decoded = decode_arrow_ipc_zero_copy(buffer).unwrap();
236            let data_ptr = decoded.buffers()[0].as_ptr() as usize;
237            assert!(
238                data_ptr >= base && data_ptr < base + len,
239                "decoded data buffer at {data_ptr:#x} is outside input \
240                 [{base:#x}, {:#x}) — a copy happened (not zero-copy)",
241                base + len
242            );
243        }
244    }
245
246    /// Production safety: an *under-aligned* input must still decode correctly.
247    /// The default decoder (`require_alignment = false`) falls back to copying
248    /// only the misaligned buffers rather than erroring.
249    #[test]
250    fn ipc_zero_copy_decoder_handles_misaligned_input() {
251        let array = UInt64Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8]);
252        let data = array.into_data();
253        let encoded = encode_arrow_ipc(&data).unwrap();
254
255        // Force a 1-byte-offset (deliberately misaligned) backing buffer.
256        let mut shifted = Vec::with_capacity(encoded.len() + 1);
257        shifted.push(0u8);
258        shifted.extend_from_slice(&encoded);
259        let buffer = arrow::buffer::Buffer::from_vec(shifted).slice(1);
260
261        let decoded = decode_arrow_ipc_zero_copy(buffer).unwrap();
262        assert_eq!(data, decoded);
263    }
264
265    #[test]
266    fn ipc_roundtrip_string() {
267        let array = StringArray::from(vec!["hello", "world"]);
268        let data = array.into_data();
269        let encoded = encode_arrow_ipc(&data).unwrap();
270        let decoded = decode_arrow_ipc(&encoded).unwrap();
271        assert_eq!(data, decoded);
272    }
273
274    #[test]
275    fn ipc_roundtrip_empty_array() {
276        let array = UInt64Array::from(Vec::<u64>::new());
277        let data = array.into_data();
278        let encoded = encode_arrow_ipc(&data).unwrap();
279        let decoded = decode_arrow_ipc(&encoded).unwrap();
280        assert_eq!(data.len(), decoded.len());
281    }
282
283    /// A zero-length *typed* array must encode to a self-describing stream that
284    /// decodes back to the SAME type, not `Null`. record/replay relies on this:
285    /// `record-node` IPC-encodes empty typed arrays (rather than dropping them
286    /// to an absent payload) so replay preserves the type instead of collapsing
287    /// to `NullArray::new(0)` (#2027/#2083).
288    #[test]
289    fn ipc_roundtrip_empty_typed_array_preserves_type() {
290        use arrow::array::Float32Array;
291        let data = Float32Array::from(Vec::<f32>::new()).into_data();
292        let encoded = encode_arrow_ipc(&data).unwrap();
293        let decoded = decode_arrow_ipc(&encoded).unwrap();
294        assert_eq!(decoded.data_type(), &arrow_schema::DataType::Float32);
295        assert_eq!(decoded.len(), 0);
296    }
297
298    #[test]
299    fn ipc_roundtrip_with_nulls() {
300        let array = UInt64Array::from(vec![Some(1), None, Some(3)]);
301        let data = array.into_data();
302        let encoded = encode_arrow_ipc(&data).unwrap();
303        let decoded = decode_arrow_ipc(&encoded).unwrap();
304        assert_eq!(data, decoded);
305    }
306}