You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/12/21 18:36:16 UTC

[GitHub] [arrow] andygrove opened a new pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

andygrove opened a new pull request #8982:
URL: https://github.com/apache/arrow/pull/8982


   DRAFT


----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
andygrove commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547527322



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,336 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.
+                let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();
+                tx.push(sender);
+                rx.push(receiver);
+            }
+            // launch one async task per *input* partition
+            for i in 0..num_input_partitions {
+                let input = self.input.clone();
+                let mut tx = tx.clone();
+                let partitioning = self.partitioning.clone();
+                let _: JoinHandle<Result<()>> = tokio::spawn(async move {
+                    let mut stream = input.execute(i).await?;
+                    let mut counter = 0;
+                    while let Some(result) = stream.next().await {
+                        match partitioning {
+                            Partitioning::RoundRobinBatch(_) => {

Review comment:
       No. I filed https://issues.apache.org/jira/browse/ARROW-11011 to implementing hash partitioning as a separate PR since it will be quite a lot of work.
   
   `RepartitionExec::try_new` returns a `DataFusionError::NotImplemented` error if you try and create it with the hash partitioning scheme.

##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,336 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.
+                let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();
+                tx.push(sender);
+                rx.push(receiver);
+            }
+            // launch one async task per *input* partition
+            for i in 0..num_input_partitions {
+                let input = self.input.clone();
+                let mut tx = tx.clone();
+                let partitioning = self.partitioning.clone();
+                let _: JoinHandle<Result<()>> = tokio::spawn(async move {
+                    let mut stream = input.execute(i).await?;
+                    let mut counter = 0;
+                    while let Some(result) = stream.next().await {
+                        match partitioning {
+                            Partitioning::RoundRobinBatch(_) => {

Review comment:
       No. I filed https://issues.apache.org/jira/browse/ARROW-11011 to implement hash partitioning as a separate PR since it will be quite a lot of work.
   
   `RepartitionExec::try_new` returns a `DataFusionError::NotImplemented` error if you try and create it with the hash partitioning scheme.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
codecov-io commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (a89bace) into [master](https://codecov.io/gh/apache/arrow/commit/4c48539c936e74aed266221d9fc76f377700216d?el=desc) (4c48539) will **decrease** coverage by `0.50%`.
   > The diff coverage is `35.76%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   83.09%   82.59%   -0.51%     
   ==========================================
     Files         200      201       +1     
     Lines       49076    49711     +635     
   ==========================================
   + Hits        40782    41061     +279     
   - Misses       8294     8650     +356     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/arrow-flight/src/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy1mbGlnaHQvc3JjL3V0aWxzLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/SparseTensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9TcGFyc2VUZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/Tensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9UZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/convert.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2NvbnZlcnQucnM=) | `91.90% <27.27%> (-1.11%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `85.71% <33.33%> (-1.47%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/File.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9GaWxlLnJz) | `40.94% <39.28%> (-2.20%)` | :arrow_down: |
   | [rust/parquet/src/arrow/schema.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9wYXJxdWV0L3NyYy9hcnJvdy9zY2hlbWEucnM=) | `90.62% <40.00%> (-0.44%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/Message.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9NZXNzYWdlLnJz) | `32.03% <42.10%> (+2.21%)` | :arrow_up: |
   | [rust/arrow/src/ipc/reader.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL3JlYWRlci5ycw==) | `82.86% <50.00%> (-0.84%)` | :arrow_down: |
   | ... and [4 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [c751295...b03c055](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] alamb commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r548508923



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,333 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+type MaybeBatch = Option<ArrowResult<RecordBatch>>;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Channels for sending batches from input partitions to output partitions
+    channels: Arc<Mutex<Vec<(Sender<MaybeBatch>, Receiver<MaybeBatch>)>>>,

Review comment:
       ```suggestion
       /// Channels for sending batches from input partitions to output partitions
       /// there is one entry in this Vec for each output partition
       channels: Arc<Mutex<Vec<(Sender<MaybeBatch>, Receiver<MaybeBatch>)>>>,
   ```

##########
File path: rust/datafusion/src/execution/dataframe_impl.rs
##########
@@ -111,6 +112,16 @@ impl DataFrame for DataFrameImpl {
         Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))
     }
 
+    fn repartition(
+        &self,
+        partitioning_scheme: Partitioning,

Review comment:
       I agree keeping the number of different names low is important 
   
   I suggest using
   * `partition` to refer to an actual portion of the data (in a bunch of `RecordBatch`es)
   * `partitioning` to refer to the "schema" of how the data is divided into `partition`s (the use of the `Partitioning` scheme now)
   
   Thus we would `repartition` the data into a new `partitioning`
   
   

##########
File path: rust/datafusion/src/logical_plan/plan.rs
##########
@@ -198,6 +206,15 @@ impl LogicalPlan {
     }
 }
 
+/// Logical partitioning schemes supported by the repartition operator.
+#[derive(Debug, Clone)]
+pub enum Partitioning {
+    /// Allocate batches using a round-robin algorithm
+    RoundRobinBatch(usize),
+    /// Allocate rows based on a hash of one of more expressions

Review comment:
       Maybe also add a comment here that `Hash` partitioning is not yet completely implemented so as to avoid runtime disappointment for someone who sees this enum in the code

##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,333 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+type MaybeBatch = Option<ArrowResult<RecordBatch>>;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Channels for sending batches from input partitions to output partitions
+    channels: Arc<Mutex<Vec<(Sender<MaybeBatch>, Receiver<MaybeBatch>)>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut channels = self.channels.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if channels.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.

Review comment:
       I think the other work around is to ensure that any operator that reads from multiple partitions doesn't block waiting for data from partition channel if other partitions can produce data. 
   
   With that invariant, the only operators that would need spill to disk would be ones that are maintaining the sorted ness (e.g a classic merge)




----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749738819


   @alamb @jorgecarleitao @seddonm1 @Dandandan This is ready for review now


----------------------------------------------------------------
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.

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



[GitHub] [arrow] Dandandan commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547528995



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,336 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.
+                let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();
+                tx.push(sender);
+                rx.push(receiver);
+            }
+            // launch one async task per *input* partition
+            for i in 0..num_input_partitions {
+                let input = self.input.clone();
+                let mut tx = tx.clone();
+                let partitioning = self.partitioning.clone();
+                let _: JoinHandle<Result<()>> = tokio::spawn(async move {
+                    let mut stream = input.execute(i).await?;
+                    let mut counter = 0;
+                    while let Some(result) = stream.next().await {
+                        match partitioning {
+                            Partitioning::RoundRobinBatch(_) => {

Review comment:
       Ok 👍 makes sense!




----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
andygrove commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547447512



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+///! The repartition operator maps N input partitions to M output partitions based on a
+///! partitioning scheme.
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use futures::channel::mpsc::{self, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<ArrowResult<RecordBatch>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<ArrowResult<RecordBatch>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            let buffer_size = 64; // TODO: configurable?

Review comment:
       So this turned out to be the really challenging part. Input partitions are sending to multiple output partitions, but those output partitions could be read in order and this results in deadlocks if the buffer is too small. I switched to using unbounded channels for now to make this functional but I know this isn't a great solution. I think I need to sleep on this and have another look tomorrow now.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] seddonm1 commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547476612



##########
File path: rust/datafusion/src/physical_plan/mod.rs
##########
@@ -107,6 +107,13 @@ pub async fn collect(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
 /// Partitioning schemes supported by operators.
 #[derive(Debug, Clone)]
 pub enum Partitioning {
+    /// Allocate batches using a round-robin algorithm
+    RoundRobinBatch(usize),
+    /// Allocate rows using a round-robin algorithm. This provides finer-grained partitioning
+    /// than `RoundRobinBatch` but also has much more overhead.
+    RoundRobinRow(usize),

Review comment:
       Agree. I was trying to implement the `RoundRobinRow` functionality independently and was going down a route similar to the `StructBuilder` vector of builders route: https://github.com/apache/arrow/blob/master/rust/arrow/src/array/builder.rs#L1600. Staying at the `RecordBatch` level is much more sensible.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749663045


   @alamb @jorgecarleitao I have not implemented a `poll_next` method before and am struggling a bit with this. I have not given up yet, but if you happen to have time today, maybe you give me some advice.
   
   I have a `Receiver` already (from async-channel) which is also supposed to implement `Stream` so I thought it would be trivial to connect these together but it is not. I am very likely missing something obvious here though.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] alamb commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r548504953



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+///! The repartition operator maps N input partitions to M output partitions based on a
+///! partitioning scheme.
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use futures::channel::mpsc::{self, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<ArrowResult<RecordBatch>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<ArrowResult<RecordBatch>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            let buffer_size = 64; // TODO: configurable?

Review comment:
       I would expect the deadlock problem to be most acute when trying to keep the data sorted (e.g a traditional merge). I didn't think we had any operators like that (yet) in DataFusion.
   
   Maybe we need to use `try_recv` when reading from channels rather than `recv`so as not to block on empty channels
   
   When we do actually have something that is trying to keep the data sorted, the behavior you want is "keep producing until every output channel has at least one record batch"
   
   Using round robin repartitioning, you can probably avoid infinite channels. Using hash re-partitioning, however, I don't think in general there is any way to ensure you have evenly distributed rows 




----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io edited a comment on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (23c0b6c) into [master](https://codecov.io/gh/apache/arrow/commit/0519c4c0ecccd7d84ce44bd3a3e7bcb4fef8f4d6?el=desc) (0519c4c) will **decrease** coverage by `0.11%`.
   > The diff coverage is `51.54%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   82.64%   82.52%   -0.12%     
   ==========================================
     Files         200      201       +1     
     Lines       49730    49921     +191     
   ==========================================
   + Hits        41098    41199     +101     
   - Misses       8632     8722      +90     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/benchmarks/src/bin/tpch.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9iZW5jaG1hcmtzL3NyYy9iaW4vdHBjaC5ycw==) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/execution/dataframe\_impl.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9leGVjdXRpb24vZGF0YWZyYW1lX2ltcGwucnM=) | `93.47% <0.00%> (-2.80%)` | :arrow_down: |
   | [rust/datafusion/src/logical\_plan/builder.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vYnVpbGRlci5ycw==) | `88.26% <0.00%> (-1.84%)` | :arrow_down: |
   | [...datafusion/src/optimizer/hash\_build\_probe\_order.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvaGFzaF9idWlsZF9wcm9iZV9vcmRlci5ycw==) | `58.42% <0.00%> (-0.67%)` | :arrow_down: |
   | [...t/datafusion/src/optimizer/projection\_push\_down.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvcHJvamVjdGlvbl9wdXNoX2Rvd24ucnM=) | `97.70% <ø> (ø)` | |
   | [rust/datafusion/src/optimizer/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvdXRpbHMucnM=) | `58.71% <0.00%> (-3.05%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/planner.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3BsYW5uZXIucnM=) | `77.46% <0.00%> (-3.00%)` | :arrow_down: |
   | [rust/datafusion/src/logical\_plan/plan.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vcGxhbi5ycw==) | `82.73% <5.55%> (-5.39%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `87.80% <50.00%> (+0.62%)` | :arrow_up: |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `76.56% <76.56%> (ø)` | |
   | ... and [2 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [0519c4c...23c0b6c](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io edited a comment on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (d845f92) into [master](https://codecov.io/gh/apache/arrow/commit/0519c4c0ecccd7d84ce44bd3a3e7bcb4fef8f4d6?el=desc) (0519c4c) will **decrease** coverage by `0.22%`.
   > The diff coverage is `2.79%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   82.64%   82.42%   -0.23%     
   ==========================================
     Files         200      201       +1     
     Lines       49730    49870     +140     
   ==========================================
   + Hits        41098    41103       +5     
   - Misses       8632     8767     +135     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/benchmarks/src/bin/tpch.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9iZW5jaG1hcmtzL3NyYy9iaW4vdHBjaC5ycw==) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/execution/dataframe\_impl.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9leGVjdXRpb24vZGF0YWZyYW1lX2ltcGwucnM=) | `93.47% <0.00%> (-2.80%)` | :arrow_down: |
   | [rust/datafusion/src/logical\_plan/builder.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vYnVpbGRlci5ycw==) | `88.26% <0.00%> (-1.84%)` | :arrow_down: |
   | [...datafusion/src/optimizer/hash\_build\_probe\_order.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvaGFzaF9idWlsZF9wcm9iZV9vcmRlci5ycw==) | `58.42% <0.00%> (-0.67%)` | :arrow_down: |
   | [...t/datafusion/src/optimizer/projection\_push\_down.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvcHJvamVjdGlvbl9wdXNoX2Rvd24ucnM=) | `97.70% <ø> (ø)` | |
   | [rust/datafusion/src/optimizer/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvdXRpbHMucnM=) | `58.71% <0.00%> (-3.05%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/planner.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3BsYW5uZXIucnM=) | `77.46% <0.00%> (-3.00%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `2.59% <2.59%> (ø)` | |
   | [rust/datafusion/src/logical\_plan/plan.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vcGxhbi5ycw==) | `82.73% <5.55%> (-5.39%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `87.80% <50.00%> (+0.62%)` | :arrow_up: |
   | ... and [2 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [0519c4c...d845f92](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io edited a comment on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (0c3ce2c) into [master](https://codecov.io/gh/apache/arrow/commit/4c48539c936e74aed266221d9fc76f377700216d?el=desc) (4c48539) will **decrease** coverage by `0.54%`.
   > The diff coverage is `34.30%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   83.09%   82.55%   -0.55%     
   ==========================================
     Files         200      201       +1     
     Lines       49076    49735     +659     
   ==========================================
   + Hits        40782    41060     +278     
   - Misses       8294     8675     +381     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/arrow-flight/src/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy1mbGlnaHQvc3JjL3V0aWxzLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/SparseTensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9TcGFyc2VUZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/Tensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9UZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/convert.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2NvbnZlcnQucnM=) | `91.90% <27.27%> (-1.11%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `85.71% <33.33%> (-1.47%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/File.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9GaWxlLnJz) | `40.94% <39.28%> (-2.20%)` | :arrow_down: |
   | [rust/parquet/src/arrow/schema.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9wYXJxdWV0L3NyYy9hcnJvdy9zY2hlbWEucnM=) | `90.62% <40.00%> (-0.44%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/Message.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9NZXNzYWdlLnJz) | `32.03% <42.10%> (+2.21%)` | :arrow_up: |
   | [rust/arrow/src/ipc/reader.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL3JlYWRlci5ycw==) | `82.86% <50.00%> (-0.84%)` | :arrow_down: |
   | ... and [5 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [c751295...0c3ce2c](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749136400


   https://issues.apache.org/jira/browse/ARROW-10582


----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove closed pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
andygrove closed pull request #8982:
URL: https://github.com/apache/arrow/pull/8982


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
andygrove commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547451094



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+///! The repartition operator maps N input partitions to M output partitions based on a
+///! partitioning scheme.
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use futures::channel::mpsc::{self, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<ArrowResult<RecordBatch>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<ArrowResult<RecordBatch>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            let buffer_size = 64; // TODO: configurable?

Review comment:
       I am adding unit tests now that will be easily modifiable to demonstrate this issue.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-750921164


   Thanks for the reviews. I have pushed changes to address feedback:
   
   - Made variable names more consistent
   - Documented that Partitioning::Hash is not yet supported (with link to JIRA issue)
   - Updated the enum documentation to mention that the usize represents the number of partitions


----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749665545


   @alamb @jorgecarleitao never mind ... switching to crossbeam did the trick


----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io edited a comment on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (c611c5a) into [master](https://codecov.io/gh/apache/arrow/commit/4c48539c936e74aed266221d9fc76f377700216d?el=desc) (4c48539) will **decrease** coverage by `0.51%`.
   > The diff coverage is `35.13%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   83.09%   82.58%   -0.52%     
   ==========================================
     Files         200      201       +1     
     Lines       49076    49721     +645     
   ==========================================
   + Hits        40782    41061     +279     
   - Misses       8294     8660     +366     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/arrow-flight/src/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy1mbGlnaHQvc3JjL3V0aWxzLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/SparseTensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9TcGFyc2VUZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/gen/Tensor.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9UZW5zb3IucnM=) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `0.00% <0.00%> (ø)` | |
   | [rust/arrow/src/ipc/convert.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2NvbnZlcnQucnM=) | `91.90% <27.27%> (-1.11%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `85.71% <33.33%> (-1.47%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/File.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9GaWxlLnJz) | `40.94% <39.28%> (-2.20%)` | :arrow_down: |
   | [rust/parquet/src/arrow/schema.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9wYXJxdWV0L3NyYy9hcnJvdy9zY2hlbWEucnM=) | `90.62% <40.00%> (-0.44%)` | :arrow_down: |
   | [rust/arrow/src/ipc/gen/Message.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL2dlbi9NZXNzYWdlLnJz) | `32.03% <42.10%> (+2.21%)` | :arrow_up: |
   | [rust/arrow/src/ipc/reader.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvaXBjL3JlYWRlci5ycw==) | `82.86% <50.00%> (-0.84%)` | :arrow_down: |
   | ... and [4 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [c751295...0c3ce2c](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] alamb commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547242606



##########
File path: rust/datafusion/src/physical_plan/mod.rs
##########
@@ -107,6 +107,13 @@ pub async fn collect(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
 /// Partitioning schemes supported by operators.
 #[derive(Debug, Clone)]
 pub enum Partitioning {
+    /// Allocate batches using a round-robin algorithm
+    RoundRobinBatch(usize),
+    /// Allocate rows using a round-robin algorithm. This provides finer-grained partitioning
+    /// than `RoundRobinBatch` but also has much more overhead.
+    RoundRobinRow(usize),

Review comment:
       Not that you asked, but if I had to pick 2 of these three schemes to implement, I would pick `RoundRobinBatch` and `Hash` and leave `RoundRobinRow` until later 
   
   The rationale being that I theorize `RoundRobinRow` usecase is much less common (e.g. maybe re-evening output of joins or filters, but I would expect most operators to respect the requested batch size if possible when creating their output)

##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+///! The repartition operator maps N input partitions to M output partitions based on a
+///! partitioning scheme.
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use futures::channel::mpsc::{self, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<ArrowResult<RecordBatch>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<ArrowResult<RecordBatch>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            let buffer_size = 64; // TODO: configurable?

Review comment:
       it seems to me that the biggest buffer we would want would be the total number of cores available for processing. Any larger and we are just wasting memory and cache size if the producer can make them faster than the consumer can consume them




----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io edited a comment on pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#issuecomment-749155213


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=h1) Report
   > Merging [#8982](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=desc) (aabdf94) into [master](https://codecov.io/gh/apache/arrow/commit/0519c4c0ecccd7d84ce44bd3a3e7bcb4fef8f4d6?el=desc) (0519c4c) will **decrease** coverage by `0.10%`.
   > The diff coverage is `50.78%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/8982/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #8982      +/-   ##
   ==========================================
   - Coverage   82.64%   82.54%   -0.11%     
   ==========================================
     Files         200      201       +1     
     Lines       49730    49983     +253     
   ==========================================
   + Hits        41098    41256     +158     
   - Misses       8632     8727      +95     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/benchmarks/src/bin/tpch.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9iZW5jaG1hcmtzL3NyYy9iaW4vdHBjaC5ycw==) | `0.00% <0.00%> (ø)` | |
   | [rust/datafusion/src/execution/dataframe\_impl.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9leGVjdXRpb24vZGF0YWZyYW1lX2ltcGwucnM=) | `93.47% <0.00%> (-2.80%)` | :arrow_down: |
   | [rust/datafusion/src/logical\_plan/builder.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vYnVpbGRlci5ycw==) | `88.26% <0.00%> (-1.84%)` | :arrow_down: |
   | [...datafusion/src/optimizer/hash\_build\_probe\_order.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvaGFzaF9idWlsZF9wcm9iZV9vcmRlci5ycw==) | `58.42% <0.00%> (-0.67%)` | :arrow_down: |
   | [...t/datafusion/src/optimizer/projection\_push\_down.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvcHJvamVjdGlvbl9wdXNoX2Rvd24ucnM=) | `97.70% <ø> (ø)` | |
   | [rust/datafusion/src/optimizer/utils.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9vcHRpbWl6ZXIvdXRpbHMucnM=) | `58.71% <0.00%> (-3.05%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/planner.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3BsYW5uZXIucnM=) | `77.46% <0.00%> (-3.00%)` | :arrow_down: |
   | [rust/datafusion/src/logical\_plan/plan.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9sb2dpY2FsX3BsYW4vcGxhbi5ycw==) | `82.73% <5.55%> (-5.39%)` | :arrow_down: |
   | [rust/datafusion/src/physical\_plan/mod.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL21vZC5ycw==) | `87.80% <50.00%> (+0.62%)` | :arrow_up: |
   | [rust/datafusion/src/physical\_plan/repartition.rs](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree#diff-cnVzdC9kYXRhZnVzaW9uL3NyYy9waHlzaWNhbF9wbGFuL3JlcGFydGl0aW9uLnJz) | `76.00% <76.00%> (ø)` | |
   | ... and [12 more](https://codecov.io/gh/apache/arrow/pull/8982/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=footer). Last update [0519c4c...aabdf94](https://codecov.io/gh/apache/arrow/pull/8982?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r548381582



##########
File path: rust/datafusion/src/dataframe.rs
##########
@@ -172,6 +174,24 @@ pub trait DataFrame {
         right_cols: &[&str],
     ) -> Result<Arc<dyn DataFrame>>;
 
+    /// Repartition a DataFrame based on a logical partitioning scheme.
+    ///
+    /// ```
+    /// # use datafusion::prelude::*;
+    /// # use datafusion::error::Result;
+    /// # fn main() -> Result<()> {
+    /// let mut ctx = ExecutionContext::new();
+    /// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;
+    /// let df1 = df.repartition(Partitioning::RoundRobinBatch(4))?;
+    /// let df2 = df.repartition(Partitioning::Hash(vec![col("a")], 4))?;

Review comment:
       I would not place it in an example since we do not support it yet.

##########
File path: rust/datafusion/src/execution/dataframe_impl.rs
##########
@@ -111,6 +112,16 @@ impl DataFrame for DataFrameImpl {
         Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))
     }
 
+    fn repartition(
+        &self,
+        partitioning_scheme: Partitioning,

Review comment:
       nit: this introduces a new naming, `partitioning_scheme`.
   
   We have:
   
   * `partition`
   * `partitioning`
   * `partitioning_scheme`
   * `repartition`
   * `part`
   
   I do not know the common notation, but we could try to reduce the number of different names we use.
   
   In my (little) understanding:
   * data is partitioned according to a `partition`
   * partitioned data is divided in `part`s 
   * we can `repartition` it according to a new `partition`.
   
   In this understanding, I would replace `partitioning` and `partitioning_scheme` by `partition`.
   
   Even if this understanding is not correct, maybe we could reduce the number of different names?

##########
File path: rust/datafusion/src/logical_plan/plan.rs
##########
@@ -198,6 +206,15 @@ impl LogicalPlan {
     }
 }
 
+/// Logical partitioning schemes supported by the repartition operator.
+#[derive(Debug, Clone)]
+pub enum Partitioning {
+    /// Allocate batches using a round-robin algorithm
+    RoundRobinBatch(usize),
+    /// Allocate rows based on a hash of one of more expressions

Review comment:
       Document `usize`? (Number of parts?)

##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,336 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.
+                let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();
+                tx.push(sender);
+                rx.push(receiver);
+            }
+            // launch one async task per *input* partition
+            for i in 0..num_input_partitions {
+                let input = self.input.clone();
+                let mut tx = tx.clone();
+                let partitioning = self.partitioning.clone();
+                let _: JoinHandle<Result<()>> = tokio::spawn(async move {
+                    let mut stream = input.execute(i).await?;
+                    let mut counter = 0;
+                    while let Some(result) = stream.next().await {
+                        match partitioning {
+                            Partitioning::RoundRobinBatch(_) => {

Review comment:
       I have an old hash repartitioning code in a branch around from a previous try. Quite old by now, but I can definitely put it together for this (like I did for the join). I think we now actually have the framework in place to use it.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] Dandandan commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547524983



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,336 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partitions = self.partitioning.partition_count();
+
+        // if this is the first partition to be invoked then we need to set up initial state
+        if tx.is_empty() {
+            // create one channel per *output* partition
+            for _ in 0..num_output_partitions {
+                // Note that this operator uses unbounded channels to avoid deadlocks because
+                // the output partitions can be read in any order and this could cause input
+                // partitions to be blocked when sending data to output receivers that are not
+                // being read yet. This may cause high memory usage if the next operator is
+                // reading output partitions in order rather than concurrently. One workaround
+                // for this would be to add spill-to-disk capabilities.
+                let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();
+                tx.push(sender);
+                rx.push(receiver);
+            }
+            // launch one async task per *input* partition
+            for i in 0..num_input_partitions {
+                let input = self.input.clone();
+                let mut tx = tx.clone();
+                let partitioning = self.partitioning.clone();
+                let _: JoinHandle<Result<()>> = tokio::spawn(async move {
+                    let mut stream = input.execute(i).await?;
+                    let mut counter = 0;
+                    while let Some(result) = stream.next().await {
+                        match partitioning {
+                            Partitioning::RoundRobinBatch(_) => {

Review comment:
       The hash partition is not yet implemented here?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] andygrove commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator [WIP]

Posted by GitBox <gi...@apache.org>.
andygrove commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547393470



##########
File path: rust/datafusion/src/physical_plan/mod.rs
##########
@@ -107,6 +107,13 @@ pub async fn collect(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
 /// Partitioning schemes supported by operators.
 #[derive(Debug, Clone)]
 pub enum Partitioning {
+    /// Allocate batches using a round-robin algorithm
+    RoundRobinBatch(usize),
+    /// Allocate rows using a round-robin algorithm. This provides finer-grained partitioning
+    /// than `RoundRobinBatch` but also has much more overhead.
+    RoundRobinRow(usize),

Review comment:
       Thanks. That makes sense and I have removed `RoundRobinRow` now.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] seddonm1 commented on a change in pull request #8982: ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator

Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #8982:
URL: https://github.com/apache/arrow/pull/8982#discussion_r547483460



##########
File path: rust/datafusion/src/physical_plan/repartition.rs
##########
@@ -0,0 +1,332 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The repartition operator maps N input partitions to M output partitions based on a
+//! partitioning scheme.
+
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{RecordBatchStream, SendableRecordBatchStream};
+use async_trait::async_trait;
+
+use crossbeam::channel::{unbounded, Receiver, Sender};
+use futures::stream::Stream;
+use futures::StreamExt;
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+
+/// partition. No guarantees are made about the order of the resulting partition.
+#[derive(Debug)]
+pub struct RepartitionExec {
+    /// Input execution plan
+    input: Arc<dyn ExecutionPlan>,
+    /// Partitioning scheme to use
+    partitioning: Partitioning,
+    /// Receivers for output batches
+    rx: Arc<Mutex<Vec<Receiver<Option<ArrowResult<RecordBatch>>>>>>,
+    /// Senders for output batches
+    tx: Arc<Mutex<Vec<Sender<Option<ArrowResult<RecordBatch>>>>>>,
+}
+
+#[async_trait]
+impl ExecutionPlan for RepartitionExec {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    /// Get the schema for this execution plan
+    fn schema(&self) -> SchemaRef {
+        self.input.schema()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.input.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            1 => Ok(Arc::new(RepartitionExec::try_new(
+                children[0].clone(),
+                self.partitioning.clone(),
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "RepartitionExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.partitioning.clone()
+    }
+
+    async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
+        // lock mutexes
+        let mut tx = self.tx.lock().await;
+        let mut rx = self.rx.lock().await;
+
+        let num_input_partitions = self.input.output_partitioning().partition_count();
+        let num_output_partition = self.partitioning.partition_count();

Review comment:
       Bikeshedding but `num_output_partition` -> `num_output_partitions` would help readability




----------------------------------------------------------------
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.

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