You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "alamb (via GitHub)" <gi...@apache.org> on 2024/09/25 15:01:38 UTC

[PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

alamb opened a new pull request, #12623:
URL: https://github.com/apache/datafusion/pull/12623

   ## Which issue does this PR close?
   
   Follow on to https://github.com/apache/datafusion/pull/12269 from @jayzhan211
   
   ## Rationale for this change
   
   The initial implementation of the Column-wise group checking code uses `Vec<bool>` to track null/validity but Arrow has a variety of optimized structures for doing so (`BooleanBufferBuilder`, etc)
   
   I would like to get this code into great shape before we fill out support for other data types (like StringView and BinaryView)
   
   I also feel like  `PrimitiveGroupValueBuilder` could largely be a wrapper around PrimitiveBuilder in arrow which would avoid the code duplication as well as take advantage of Arrow's optimizations
   
   Let's use BooleanBufferBuilder to simplify the null handling in PrimitiveGroupValueBuilder. I 
   
   
   ## What changes are included in this PR?
   Rewrite `PrimitiveGroupValueBuilder`
   
   ## Are these changes tested?
   
   By existing CI
   
   ## Are there any user-facing changes?
   No
   
   Performance results (RUNNING)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776133521


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder
+    // (todo it would be great to use something like `set_bits` from arrow here.
+    let mut new_builder = BooleanBufferBuilder::new(nulls.len());
+    for i in n..nulls.len() {
+        new_builder.append(nulls.get_bit(i));

Review Comment:
   Maybe we could implement `get_bit_slice(i, j) -> &[bool]` and append with `append_slice`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1779845711


##########
datafusion/physical-plan/src/aggregates/group_values/group_column.rs:
##########
@@ -62,57 +64,60 @@ pub trait GroupColumn: Send + Sync {
 
 pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
     group_values: Vec<T::Native>,
-    nulls: Vec<bool>,
-    // whether the array contains at least one null, for fast non-null path
-    has_null: bool,
-    nullable: bool,
+    /// Null state (when None, input is guaranteed not to have nulls)
+    nulls: Option<MaybeNullBufferBuilder>,

Review Comment:
   My benchmark shows a slowdown compared to the main branch. I experienced a similar slowdown before due to the use of Option, and I suspect that might be the case again with this change



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776517883


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   Another approach I'm thinking of is we only append the boolean and implement `finish_slice()` to take arbitrary slice, so we can avoid *shifting bitmap* which requires careful implementation. The only downside is we may *garbage collection*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1775413885


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -62,57 +62,81 @@ pub trait ArrayRowEq: Send + Sync {
 
 pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
     group_values: Vec<T::Native>,
-    nulls: Vec<bool>,
-    // whether the array contains at least one null, for fast non-null path
-    has_null: bool,
+    /// Nulls buffer for the group values --
+    /// * None if we have seen no arrays yet
+    /// * Some if we have seen arrays and have at least one null
+    ///
+    /// Note this is an Arrow *VALIDITY* buffer (so it is false for nulls, true
+    /// for non-nulls)
+    nulls: Option<BooleanBufferBuilder>,
+    /// If true, the input is guaranteed not to have nulls
     nullable: bool,
 }
 
 impl<T> PrimitiveGroupValueBuilder<T>
 where
     T: ArrowPrimitiveType,
 {
+    /// Create a new [`PrimitiveGroupValueBuilder`]
+    ///
+    /// If `nullable` is false, it means the input will never have nulls
     pub fn new(nullable: bool) -> Self {
         Self {
             group_values: vec![],
-            nulls: vec![],
-            has_null: false,
+            nulls: None,
             nullable,
         }
     }
 }
 
 impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {
-        // non-null fast path
-        // both non-null
+        // fast path when input has no nulls
         if !self.nullable {
+            debug_assert!(self.nulls.is_none());
             return self.group_values[lhs_row]
                 == array.as_primitive::<T>().value(rhs_row);
         }
-
-        // lhs is non-null
-        if self.nulls[lhs_row] {
-            if array.is_null(rhs_row) {
+        // slow path if the input could have nulls
+        if let Some(nulls) = self.nulls.as_ref() {
+            // if lhs_row is valid (non null), but array is null
+            let lhs_is_null = !nulls.get_bit(lhs_row);
+            let rhs_is_null = array.is_null(rhs_row);
+            if lhs_is_null != rhs_is_null {
                 return false;
             }
-
-            return self.group_values[lhs_row]
-                == array.as_primitive::<T>().value(rhs_row);
         }
-
-        array.is_null(rhs_row)
+        self.group_values[lhs_row] == array.as_primitive::<T>().value(rhs_row)
     }
 
     fn append_val(&mut self, array: &ArrayRef, row: usize) {
-        if self.nullable && array.is_null(row) {
-            self.group_values.push(T::default_value());
-            self.nulls.push(false);
-            self.has_null = true;
-        } else {
-            let elem = array.as_primitive::<T>().value(row);
-            self.group_values.push(elem);
-            self.nulls.push(true);

Review Comment:
   it seems like this previous code manages `self.nulls` even when there are and have been no nulls at all in the input



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#issuecomment-2374378722

   Marking draft until I have benchmark numbers


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776133521


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder
+    // (todo it would be great to use something like `set_bits` from arrow here.
+    let mut new_builder = BooleanBufferBuilder::new(nulls.len());
+    for i in n..nulls.len() {
+        new_builder.append(nulls.get_bit(i));

Review Comment:
   Maybe we could implement `get_bit_slice(i, j) -> &[bool]` and append with `append_slice`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776133521


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder
+    // (todo it would be great to use something like `set_bits` from arrow here.
+    let mut new_builder = BooleanBufferBuilder::new(nulls.len());
+    for i in n..nulls.len() {
+        new_builder.append(nulls.get_bit(i));

Review Comment:
   Maybe we could implement `get_bits -> &[bool]` in arrow and append with `append_slice`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776133521


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder
+    // (todo it would be great to use something like `set_bits` from arrow here.
+    let mut new_builder = BooleanBufferBuilder::new(nulls.len());
+    for i in n..nulls.len() {
+        new_builder.append(nulls.get_bit(i));

Review Comment:
   Maybe we could implement `get_bit_slice(i, j) -> &[bool]` in arrow and append with `append_slice`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776517883


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   Another approach I'm thinking of is we only append the boolean and implement `finish_slice()` to take arbitrary slice.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1779666579


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   WIll do it as a follow on



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776517883


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   Another approach I'm thinking of is we only append the boolean and implement `finish_slice()` to take arbitrary slice, so we can avoid *shifting bitmap* which requires careful implementation



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1779665405


##########
datafusion/physical-plan/src/aggregates/group_values/group_column.rs:
##########
@@ -62,57 +64,60 @@ pub trait GroupColumn: Send + Sync {
 
 pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
     group_values: Vec<T::Native>,
-    nulls: Vec<bool>,
-    // whether the array contains at least one null, for fast non-null path
-    has_null: bool,
-    nullable: bool,
+    /// Null state (when None, input is guaranteed not to have nulls)
+    nulls: Option<MaybeNullBufferBuilder>,

Review Comment:
   I collapsed `nullable` and `has_nulls` into an `Option` and an `Enum` which I think makes the intent much clearer (and harder to mess up the `nullable` optimization



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1777745457


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   > The challenge is to "shift bitmap" without setting bit one by one but byte-wise. I think we need get_bit_slice that can read the partial byte or full byte efficiently and use set_bit_slice to copy those bytes to a new one.
   
   >  so we can avoid shifting bitmap which requires careful implementation. 
    
   There is already a function that does this shifting in arrow-rs (that also has had quite a bit of careful optimizaton and testing already):  https://docs.rs/arrow/latest/arrow/util/bit_mask/fn.set_bits.html
   
   To use it though you need mutable access to the underlying `[u8]`
   
   I'll see what I can come up with tomorro



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#issuecomment-2377959248

   > Marking draft until I have benchmark numbers
   
   The benchmark numbers look good -- now I just need to debug one test and I will put this up for review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1775414765


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   This was the trickiest bit of code. It could be optimized significantly further, but maybe best done in arrow or elsewhere



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Refactor PrimitiveGroupValueBuilder to use BooleanBuilder [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12623:
URL: https://github.com/apache/datafusion/pull/12623#discussion_r1776454559


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -121,37 +145,64 @@ impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
     }
 
     fn size(&self) -> usize {
-        self.group_values.allocated_size() + self.nulls.allocated_size()
+        // BooleanBufferBuilder builder::capacity returns capacity in bits (not bytes)
+        let null_builder_size = self
+            .nulls
+            .as_ref()
+            .map(|nulls| nulls.capacity() / 8)
+            .unwrap_or(0);
+        self.group_values.allocated_size() + null_builder_size
     }
 
     fn build(self: Box<Self>) -> ArrayRef {
-        if self.has_null {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                Some(NullBuffer::from(self.nulls)),
-            ))
-        } else {
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(self.group_values),
-                None,
-            ))
-        }
+        let Self {
+            group_values,
+            nulls,
+            nullable: _,
+        } = *self;
+        let null_buffer = nulls.map(|mut nulls| NullBuffer::from(nulls.finish()));
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(group_values),
+            null_buffer,
+        ))
     }
 
     fn take_n(&mut self, n: usize) -> ArrayRef {
-        if self.has_null {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
-            Arc::new(PrimitiveArray::<T>::new(
-                ScalarBuffer::from(first_n),
-                Some(NullBuffer::from(first_n_nulls)),
-            ))
-        } else {
-            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
-            self.nulls.truncate(self.nulls.len() - n);
-            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), None))
-        }
+        let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+
+        let first_n_nulls = self.nulls.take().map(|nulls| {
+            let (first_n_nulls, remaining_nulls) = take_n_nulls(n, nulls);
+            self.nulls = Some(remaining_nulls);
+            first_n_nulls
+        });
+
+        Arc::new(PrimitiveArray::<T>::new(
+            ScalarBuffer::from(first_n),
+            first_n_nulls,
+        ))
+    }
+}
+
+/// Takes the first `n` nulls from the `nulls` buffer and
+///
+/// Returns
+/// * [`NullBuffer`] with the first `n` nulls
+/// * [`BooleanBufferBuilder`] with the remaining nulls
+fn take_n_nulls(
+    n: usize,
+    mut nulls: BooleanBufferBuilder,
+) -> (NullBuffer, BooleanBufferBuilder) {
+    // Copy over the values at  n..len-1 values to the start of a new builder

Review Comment:
   The challenge is to "shift bitmap" without setting bit one by one but *byte-wise*. I think we need `get_bit_slice` that can read the partial byte or full byte efficiently and use `set_bit_slice` to copy those bytes to a new one.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org