Skip to main content

vortex_array/arrays/varbinview/
compact.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Defines a compaction operation for VarBinViewArrays that evicts unused buffers so they can
5//! be dropped.
6
7use std::ops::Range;
8
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_mask::Mask;
12
13use crate::ExecutionCtx;
14use crate::array::TypedArrayRef;
15use crate::arrays::VarBinView;
16use crate::arrays::VarBinViewArray;
17use crate::arrays::varbinview::Ref;
18use crate::builders::VarBinViewBuilder;
19
20const DEFAULT_COMPACTION_THRESHOLD: f64 = 0.5;
21const MIN_RETAINED_BYTES_PER_ROW_TO_CHECK_COMPACTION: u64 = 128;
22
23/// The maximum number of data buffers that compaction keeps as they are, well below the
24/// `u16::MAX` buffers that the serializer accepts for an array and all its descendants.
25const MAX_RETAINED_DATA_BUFFERS: usize = u16::MAX as usize / 2;
26
27/// A utilization threshold that no buffer can reach, thus compaction rewrites every buffer.
28const REWRITE_ALL_THRESHOLD: f64 = f64::INFINITY;
29
30impl VarBinViewArray {
31    /// Returns a compacted copy of the input array, where all wasted space has been cleaned up. This
32    /// operation can be very expensive, in the worst case copying all existing string data into
33    /// a new allocation.
34    ///
35    /// After slicing/taking operations `VarBinViewArray`s can continue to hold references to buffers
36    /// that are no longer visible. We detect when there is wasted space in any of the buffers, and if
37    /// so, will aggressively compact all visible outlined string data into new buffers while keeping
38    /// well-utilized buffers unchanged.
39    pub fn compact_buffers(&self, ctx: &mut ExecutionCtx) -> VortexResult<VarBinViewArray> {
40        // If there is nothing to be gained by compaction, return the original array untouched.
41        if !self.should_compact(ctx)? {
42            return Ok(self.clone());
43        }
44
45        // Many buffers fail to serialize even when each one is well used. Copy all referenced
46        // bytes into new buffers, which the builder fills before it starts the next one.
47        if self.data_buffers().len() > MAX_RETAINED_DATA_BUFFERS {
48            return self.compact_with_threshold(REWRITE_ALL_THRESHOLD, ctx);
49        }
50
51        self.compact_with_threshold(DEFAULT_COMPACTION_THRESHOLD, ctx)
52    }
53
54    fn should_compact(&self, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
55        let nbuffers = self.data_buffers().len();
56
57        // If the array is entirely inlined strings, do not attempt to compact.
58        if nbuffers == 0 {
59            return Ok(false);
60        }
61
62        // These will fail to write, so in most cases we want to compact this.
63        if nbuffers > MAX_RETAINED_DATA_BUFFERS {
64            return Ok(true);
65        }
66
67        let buffer_total_bytes: u64 = self.buffers.iter().map(|buf| buf.len() as u64).sum();
68        if buffer_total_bytes == 0 {
69            return Ok(true);
70        }
71
72        let len = u64::try_from(self.len()).unwrap_or(u64::MAX);
73        if len > 0 && buffer_total_bytes / len <= MIN_RETAINED_BYTES_PER_ROW_TO_CHECK_COMPACTION {
74            return Ok(false);
75        }
76
77        let bytes_referenced: u64 = self.count_referenced_bytes(ctx)?;
78        Ok((bytes_referenced as f64 / buffer_total_bytes as f64) < DEFAULT_COMPACTION_THRESHOLD)
79    }
80
81    /// Returns a compacted copy of the input array using selective buffer compaction.
82    ///
83    /// This method analyzes each buffer's utilization and applies one of three strategies:
84    /// - **KeepFull** (zero-copy): Well-utilized buffers are kept unchanged
85    /// - **Slice** (zero-copy): Buffers with contiguous ranges of used data are sliced to that range
86    /// - **Rewrite**: Poorly-utilized buffers have their data copied to new compact buffers
87    ///
88    /// By preserving or slicing well-utilized buffers, compaction becomes zero-copy in many cases.
89    ///
90    /// # Arguments
91    ///
92    /// * `buffer_utilization_threshold` - Threshold in range [0, 1]. Buffers with utilization
93    ///   below this value will be compacted. Use 0.0 for no compaction, 1.0 for aggressive
94    ///   compaction of any buffer with wasted space.
95    pub fn compact_with_threshold(
96        &self,
97        buffer_utilization_threshold: f64, // [0, 1]
98        ctx: &mut ExecutionCtx,
99    ) -> VortexResult<VarBinViewArray> {
100        let mut builder = VarBinViewBuilder::with_compaction_in(
101            self.dtype().clone(),
102            self.len(),
103            buffer_utilization_threshold,
104            ctx.allocator().clone(),
105        );
106        builder.append_varbinview_array(self.as_view(), ctx)?;
107        Ok(builder.finish_into_varbinview())
108    }
109}
110
111/// Read-only compaction statistics over a `VarBinView` array.
112///
113/// These live on a trait rather than on [`VarBinViewArray`] so that a borrowed
114/// [`ArrayView`](crate::array::ArrayView) can ask for them without cloning the array behind it.
115pub(crate) trait VarBinViewCompactExt: TypedArrayRef<VarBinView> {
116    /// Iterates over all valid, non-inlined views, calling the provided
117    /// closure for each one.
118    #[allow(clippy::inline_always)]
119    #[inline(always)]
120    fn iter_valid_views<F>(&self, ctx: &mut ExecutionCtx, mut f: F) -> VortexResult<()>
121    where
122        F: FnMut(&Ref),
123    {
124        match self.as_ref().validity()?.execute_mask(self.len(), ctx)? {
125            Mask::AllTrue(_) => {
126                for &view in self.views().iter() {
127                    if !view.is_inlined() {
128                        f(view.as_view());
129                    }
130                }
131            }
132            Mask::AllFalse(_) => {}
133            Mask::Values(v) => {
134                for (&view, is_valid) in self.views().iter().zip(v.bit_buffer().iter()) {
135                    if is_valid && !view.is_inlined() {
136                        f(view.as_view());
137                    }
138                }
139            }
140        }
141        Ok(())
142    }
143
144    /// Count the number of bytes addressed by the views, not including null
145    /// values or any inlined strings.
146    fn count_referenced_bytes(&self, ctx: &mut ExecutionCtx) -> VortexResult<u64> {
147        let mut total = 0u64;
148        self.iter_valid_views(ctx, |view| total += view.size as u64)?;
149        Ok(total)
150    }
151
152    fn buffer_utilizations(&self, ctx: &mut ExecutionCtx) -> VortexResult<Vec<BufferUtilization>> {
153        let mut utilizations: Vec<BufferUtilization> = self
154            .data_buffers()
155            .iter()
156            .map(|buf| {
157                let len = u32::try_from(buf.len()).vortex_expect("buffer sizes must fit in u32");
158                BufferUtilization::zero(len)
159            })
160            .collect();
161
162        self.iter_valid_views(ctx, |view| {
163            utilizations[view.buffer_index as usize].add(view.offset, view.size);
164        })?;
165
166        Ok(utilizations)
167    }
168}
169
170impl<T: TypedArrayRef<VarBinView>> VarBinViewCompactExt for T {}
171
172pub(crate) struct BufferUtilization {
173    len: u32,
174    used: u32,
175    min_offset: u32,
176    max_offset_end: u32,
177}
178
179impl BufferUtilization {
180    pub(crate) fn zero(len: u32) -> Self {
181        BufferUtilization {
182            len,
183            used: 0u32,
184            min_offset: u32::MAX,
185            max_offset_end: 0,
186        }
187    }
188
189    pub(crate) fn add(&mut self, offset: u32, size: u32) {
190        self.used += size;
191        self.min_offset = self.min_offset.min(offset);
192        self.max_offset_end = self.max_offset_end.max(offset + size);
193    }
194
195    pub(crate) fn used(&self) -> u32 {
196        self.used
197    }
198
199    pub fn overall_utilization(&self) -> f64 {
200        match self.len {
201            0 => 0.0,
202            len => self.used as f64 / len as f64,
203        }
204    }
205
206    pub fn range_utilization(&self) -> f64 {
207        match self.range_span() {
208            0 => 0.0,
209            span => self.used as f64 / span as f64,
210        }
211    }
212
213    pub fn range(&self) -> Range<u32> {
214        self.min_offset..self.max_offset_end
215    }
216
217    fn range_span(&self) -> u32 {
218        self.max_offset_end.saturating_sub(self.min_offset)
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use std::sync::LazyLock;
225
226    use rstest::rstest;
227    use vortex_buffer::ByteBuffer;
228    use vortex_buffer::buffer;
229    use vortex_error::VortexResult;
230    use vortex_session::VortexSession;
231
232    use super::MAX_RETAINED_DATA_BUFFERS;
233    use super::VarBinViewCompactExt;
234    use crate::IntoArray;
235    use crate::VortexSessionExecute;
236    use crate::arrays::VarBinArray;
237    use crate::arrays::VarBinViewArray;
238    use crate::arrays::varbinview::BinaryView;
239    use crate::assert_arrays_eq;
240    use crate::dtype::DType;
241    use crate::dtype::Nullability;
242    use crate::validity::Validity;
243
244    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
245    #[test]
246    fn test_optimize_compacts_buffers() {
247        let mut ctx = SESSION.create_execution_ctx();
248        // Create a VarBinViewArray with some long strings that will create multiple buffers
249        let excluded = "unused long string".repeat(100);
250        let original = VarBinViewArray::from_iter_nullable_str([
251            Some("short"),
252            Some("this is a longer string that will be stored in a buffer"),
253            Some(excluded.as_str()),
254            Some("another very long string that definitely needs a buffer to store it"),
255            Some("tiny"),
256        ]);
257
258        // Verify it has buffers
259        assert!(!original.data_buffers().is_empty());
260        let original_buffers = original.data_buffers().len();
261
262        // Take only the first and last elements (indices 0 and 4)
263        let indices = buffer![0u32, 4u32].into_array();
264        let taken = original.take(indices).unwrap();
265        let taken = taken.execute::<VarBinViewArray>(&mut ctx).unwrap();
266        // The taken array should still have the same number of buffers
267        assert_eq!(taken.data_buffers().len(), original_buffers);
268
269        // Now optimize the taken array
270        let optimized_array = taken.compact_buffers(&mut ctx).unwrap();
271
272        assert!(optimized_array.data_buffers().is_empty());
273
274        // Verify the data is still correct
275        assert_arrays_eq!(
276            optimized_array,
277            <VarBinArray as FromIterator<_>>::from_iter([Some("short"), Some("tiny")]),
278            &mut ctx
279        );
280    }
281
282    #[test]
283    fn test_optimize_with_long_strings() {
284        let mut ctx = SESSION.create_execution_ctx();
285        // Create strings that are definitely longer than 12 bytes
286        let long_string_1 = "this is definitely a very long string that exceeds the inline limit";
287        let long_string_2 = "another extremely long string that also needs external buffer storage";
288        let long_string_3 = "yet another long string for testing buffer compaction functionality";
289
290        let original = VarBinViewArray::from_iter_str([
291            long_string_1,
292            long_string_2,
293            long_string_3,
294            "short1",
295            "short2",
296        ]);
297
298        // Take only the first and third long strings (indices 0 and 2)
299        let indices = buffer![0u32, 2u32].into_array();
300        let taken = original.take(indices).unwrap();
301        let taken_array = taken
302            .execute::<VarBinViewArray>(&mut SESSION.create_execution_ctx())
303            .unwrap();
304
305        let optimized_array = taken_array.compact_with_threshold(1.0, &mut ctx).unwrap();
306
307        // The optimized array should have exactly 1 buffer (consolidated)
308        assert_eq!(optimized_array.data_buffers().len(), 1);
309        assert_eq!(
310            optimized_array.buffer(0).len(),
311            long_string_1.len() + long_string_3.len()
312        );
313
314        // Verify the data is still correct
315        assert_arrays_eq!(
316            optimized_array,
317            VarBinArray::from(vec![long_string_1, long_string_3]),
318            &mut ctx
319        );
320    }
321
322    #[test]
323    fn test_optimize_no_buffers() {
324        let mut ctx = SESSION.create_execution_ctx();
325        // Create an array with only short strings (all inlined)
326        let original = VarBinViewArray::from_iter_str(["a", "bb", "ccc", "dddd"]);
327
328        // This should have no buffers
329        assert_eq!(original.data_buffers().len(), 0);
330
331        // Optimize should return the same array
332        let optimized_array = original.compact_buffers(&mut ctx).unwrap();
333
334        assert_eq!(optimized_array.data_buffers().len(), 0);
335
336        assert_arrays_eq!(optimized_array, original, &mut ctx);
337    }
338
339    #[test]
340    fn test_optimize_single_buffer() {
341        let mut ctx = SESSION.create_execution_ctx();
342        // Create an array that naturally has only one buffer
343        let str1 = "this is a long string that goes into a buffer";
344        let str2 = "another long string in the same buffer";
345        let original = VarBinViewArray::from_iter_str([str1, str2]);
346
347        // Should have 1 compact buffer
348        assert_eq!(original.data_buffers().len(), 1);
349        assert_eq!(original.buffer(0).len(), str1.len() + str2.len());
350
351        // Optimize should return the same array (no change needed)
352        let optimized_array = original.compact_buffers(&mut ctx).unwrap();
353
354        assert_eq!(optimized_array.data_buffers().len(), 1);
355
356        assert_arrays_eq!(optimized_array, original, &mut ctx);
357    }
358
359    #[test]
360    fn test_selective_compaction_with_threshold_zero() {
361        let mut ctx = SESSION.create_execution_ctx();
362        // threshold=0 should keep all buffers (no compaction)
363        let original = VarBinViewArray::from_iter_str([
364            "this is a longer string that will be stored in a buffer",
365            "another very long string that definitely needs a buffer to store it",
366        ]);
367
368        let original_buffers = original.data_buffers().len();
369        assert!(original_buffers > 0);
370
371        // Take only first element
372        let indices = buffer![0u32].into_array();
373        let taken = original.take(indices).unwrap();
374        let taken = taken
375            .execute::<VarBinViewArray>(&mut SESSION.create_execution_ctx())
376            .unwrap();
377        // Compact with threshold=0 (should not compact)
378        let compacted = taken.compact_with_threshold(0.0, &mut ctx).unwrap();
379
380        // Should still have the same number of buffers as the taken array
381        assert_eq!(compacted.data_buffers().len(), taken.data_buffers().len());
382
383        // Verify correctness
384        assert_arrays_eq!(compacted, taken, &mut ctx);
385    }
386
387    #[test]
388    fn test_selective_compaction_with_high_threshold() {
389        let mut ctx = SESSION.create_execution_ctx();
390        // threshold=1.0 should compact any buffer with waste
391        let original = VarBinViewArray::from_iter_str([
392            "this is a longer string that will be stored in a buffer",
393            "another very long string that definitely needs a buffer to store it",
394            "yet another long string",
395        ]);
396
397        // Take only first and last elements
398        let indices = buffer![0u32, 2u32].into_array();
399        let taken = original.take(indices).unwrap();
400        let taken = taken
401            .execute::<VarBinViewArray>(&mut SESSION.create_execution_ctx())
402            .unwrap();
403
404        let original_buffers = taken.data_buffers().len();
405
406        // Compact with threshold=1.0 (aggressive compaction)
407        let compacted = taken.compact_with_threshold(1.0, &mut ctx).unwrap();
408
409        // Should have compacted buffers
410        assert!(compacted.data_buffers().len() <= original_buffers);
411        assert!(
412            compacted
413                .data_buffers()
414                .iter()
415                .map(|b| b.len())
416                .sum::<usize>()
417                < taken.data_buffers().iter().map(|b| b.len()).sum::<usize>()
418        );
419
420        // Verify correctness
421        assert_arrays_eq!(compacted, taken, &mut ctx);
422    }
423
424    #[test]
425    fn test_selective_compaction_preserves_well_utilized_buffers() {
426        let mut ctx = SESSION.create_execution_ctx();
427        // Create an array with multiple strings in one buffer (well-utilized)
428        let str1 = "first long string that needs external buffer storage";
429        let str2 = "second long string also in buffer";
430        let str3 = "third long string in same buffer";
431
432        let original = VarBinViewArray::from_iter_str([str1, str2, str3]);
433
434        // All strings should be in one well-utilized buffer
435        assert_eq!(original.data_buffers().len(), 1);
436
437        // Compact with high threshold
438        let compacted = original.compact_with_threshold(0.8, &mut ctx).unwrap();
439
440        // Well-utilized buffer should be preserved
441        assert_eq!(compacted.data_buffers().len(), 1);
442        assert_eq!(compacted.buffer(0).as_ptr(), original.buffer(0).as_ptr());
443        assert_eq!(
444            compacted.buffer(0).as_slice(),
445            original.buffer(0).as_slice()
446        );
447
448        // Verify all data is correct
449        assert_arrays_eq!(compacted, original, &mut ctx);
450    }
451
452    #[test]
453    fn test_selective_compaction_with_mixed_utilization() {
454        let mut ctx = SESSION.create_execution_ctx();
455        // Create array with some long strings
456        let strings: Vec<String> = (0..10)
457            .map(|i| {
458                format!(
459                    "this is a long string number {} that needs buffer storage",
460                    i
461                )
462            })
463            .collect();
464
465        let original = VarBinViewArray::from_iter_str(strings.iter().map(|s| s.as_str()));
466
467        // Take every other element to create mixed utilization
468        let indices_array = buffer![0u32, 2u32, 4u32, 6u32, 8u32].into_array();
469        let taken = original.take(indices_array).unwrap();
470        let taken = taken
471            .execute::<VarBinViewArray>(&mut SESSION.create_execution_ctx())
472            .unwrap();
473
474        // Compact with moderate threshold
475        let compacted = taken.compact_with_threshold(0.7, &mut ctx).unwrap();
476
477        let expected = VarBinViewArray::from_iter(
478            [0, 2, 4, 6, 8].map(|i| Some(strings[i].as_str())),
479            DType::Utf8(Nullability::NonNullable),
480        );
481        assert_arrays_eq!(compacted, expected, &mut ctx);
482    }
483
484    #[test]
485    fn test_slice_strategy_with_contiguous_range() {
486        let mut ctx = SESSION.create_execution_ctx();
487        // Create array with strings that will be in one buffer
488        let strings: Vec<String> = (0..20)
489            .map(|i| format!("this is a long string number {} for slice test", i))
490            .collect();
491
492        let original = VarBinViewArray::from_iter_str(strings.iter().map(|s| s.as_str()));
493
494        // Take only the first 5 elements - they should be in a contiguous range at the start
495        let indices_array = buffer![0u32, 1u32, 2u32, 3u32, 4u32].into_array();
496        let taken = original.take(indices_array).unwrap();
497        let taken = taken
498            .execute::<VarBinViewArray>(&mut SESSION.create_execution_ctx())
499            .unwrap();
500        // Get buffer stats before compaction
501        let original_ptr = taken.buffer(0).as_ptr();
502
503        // Compact with a threshold that should trigger slicing
504        // The range utilization should be high even if overall utilization is low
505        let compacted = taken.compact_with_threshold(0.8, &mut ctx).unwrap();
506
507        // After compaction, we should still have buffers (sliced, not rewritten)
508        assert!(
509            !compacted.data_buffers().is_empty(),
510            "Should have buffers after slice compaction"
511        );
512
513        // Verify correctness
514        assert_arrays_eq!(&compacted, taken, &mut ctx);
515
516        assert_eq!(compacted.data_buffers().len(), 1);
517        assert_eq!(compacted.buffer(0).as_ptr(), original_ptr);
518        assert_eq!(
519            compacted.buffer(0).len(),
520            strings[..5].iter().map(String::len).sum::<usize>()
521        );
522    }
523
524    const LONG1: &str = "long string one!";
525    const LONG2: &str = "long string two!";
526    const SHORT: &str = "x";
527    const EXPECTED_BYTES: u64 = (LONG1.len() + LONG2.len()) as u64;
528
529    fn mixed_array() -> VarBinViewArray {
530        VarBinViewArray::from_iter_nullable_str([Some(LONG1), None, Some(LONG2), Some(SHORT)])
531    }
532
533    #[rstest]
534    #[case::non_nullable(VarBinViewArray::from_iter_str([LONG1, LONG2, SHORT]), EXPECTED_BYTES, &[1.0])]
535    #[case::all_valid(VarBinViewArray::from_iter_nullable_str([Some(LONG1), Some(LONG2), Some(SHORT)]), EXPECTED_BYTES, &[1.0])]
536    #[case::all_invalid(VarBinViewArray::from_iter_nullable_str([None::<&str>, None]), 0, &[])]
537    #[case::mixed_validity(mixed_array(), EXPECTED_BYTES, &[1.0])]
538    fn test_validity_code_paths(
539        #[case] arr: VarBinViewArray,
540        #[case] expected_bytes: u64,
541        #[case] expected_utils: &[f64],
542    ) {
543        let mut ctx = SESSION.create_execution_ctx();
544        assert_eq!(
545            arr.count_referenced_bytes(&mut ctx).unwrap(),
546            expected_bytes
547        );
548        let utils: Vec<f64> = arr
549            .buffer_utilizations(&mut ctx)
550            .unwrap()
551            .iter()
552            .map(|u| u.overall_utilization())
553            .collect();
554        assert_eq!(utils, expected_utils);
555    }
556
557    /// Each 16-byte value sits in its own fully referenced data buffer.
558    fn one_buffer_per_value(nbuffers: usize) -> VortexResult<VarBinViewArray> {
559        let mut ctx = SESSION.create_execution_ctx();
560        let values: Vec<[u8; 16]> = (0u32..)
561            .take(nbuffers)
562            .map(|i| {
563                let mut value = [b'a'; 16];
564                value[..4].copy_from_slice(&i.to_le_bytes());
565                value
566            })
567            .collect();
568
569        VarBinViewArray::try_new(
570            values
571                .iter()
572                .zip(0u32..)
573                .map(|(value, i)| BinaryView::make_view(value, i, 0))
574                .collect(),
575            values.iter().map(ByteBuffer::copy_from).collect(),
576            DType::Binary(Nullability::NonNullable),
577            Validity::NonNullable,
578            &mut ctx,
579        )
580    }
581
582    #[test]
583    fn test_compact_keeps_full_buffers_at_limit() -> VortexResult<()> {
584        let mut ctx = SESSION.create_execution_ctx();
585        let original = one_buffer_per_value(MAX_RETAINED_DATA_BUFFERS)?;
586
587        let compacted = original.compact_buffers(&mut ctx)?;
588
589        assert_eq!(compacted.data_buffers().len(), MAX_RETAINED_DATA_BUFFERS);
590        assert_arrays_eq!(compacted, original, &mut ctx);
591
592        Ok(())
593    }
594
595    #[test]
596    fn test_compact_too_many_buffers_fits_serializer_limit() -> VortexResult<()> {
597        let mut ctx = SESSION.create_execution_ctx();
598        let original = one_buffer_per_value(u16::MAX as usize + 1)?;
599
600        let compacted = original.compact_buffers(&mut ctx)?;
601
602        assert!(compacted.data_buffers().len() < u16::MAX as usize);
603        assert_arrays_eq!(compacted, original, &mut ctx);
604
605        Ok(())
606    }
607}