Apache DataFusion SQL Query Engine
ARROW-12328: [Rust] [Ballista] Fix formatting
Andy Grovebe7d0cc4a3dc
diff --git a/rust/ballista/rust/client/src/context.rs b/rust/ballista/rust/client/src/context.rsindex 09fe8a0ebf..8b2431f56c 100644--- a/rust/ballista/rust/client/src/context.rs+++ b/rust/ballista/rust/client/src/context.rs@@ -100,7 +100,11 @@ impl BallistaContext {/// Create a DataFrame representing a CSV table scan- pub fn read_csv(&self, path: &str, options: CsvReadOptions) -> Result<BallistaDataFrame> {+ pub fn read_csv(+ &self,+ path: &str,+ options: CsvReadOptions,+ ) -> Result<BallistaDataFrame> {// convert to absolute path because the executor likely has a different working directorylet path = PathBuf::from(path);let path = fs::canonicalize(&path)?;@@ -120,7 +124,12 @@ impl BallistaContext {Ok(())}- pub fn register_csv(&self, name: &str, path: &str, options: CsvReadOptions) -> Result<()> {+ pub fn register_csv(+ &self,+ name: &str,+ path: &str,+ options: CsvReadOptions,+ ) -> Result<()> {let df = self.read_csv(path, options)?;self.register_table(name, &df)}@@ -213,14 +222,20 @@ impl BallistaDataFrame {let mut result = vec![];for location in completed.partition_location {let metadata = location.executor_meta.ok_or_else(|| {- BallistaError::Internal("Received empty executor metadata".to_owned())+ BallistaError::Internal(+ "Received empty executor metadata".to_owned(),+ )})?;let partition_id = location.partition_id.ok_or_else(|| {- BallistaError::Internal("Received empty partition id".to_owned())+ BallistaError::Internal(+ "Received empty partition id".to_owned(),+ )})?;- let mut ballista_client =- BallistaClient::try_new(metadata.host.as_str(), metadata.port as u16)- .await?;+ let mut ballista_client = BallistaClient::try_new(+ metadata.host.as_str(),+ metadata.port as u16,+ )+ .await?;let stream = ballista_client.fetch_partition(&partition_id.job_id,@@ -228,8 +243,10 @@ impl BallistaDataFrame {partition_id.partition_id as usize,).await?;- result- .append(&mut datafusion::physical_plan::common::collect(stream).await?);+ result.append(+ &mut datafusion::physical_plan::common::collect(stream)+ .await?,+ );}break Ok(Box::pin(MemoryStream::try_new(result,@@ -264,7 +281,11 @@ impl BallistaDataFrame {))}- pub fn aggregate(&self, group_expr: &[Expr], aggr_expr: &[Expr]) -> Result<BallistaDataFrame> {+ pub fn aggregate(+ &self,+ group_expr: &[Expr],+ aggr_expr: &[Expr],+ ) -> Result<BallistaDataFrame> {Ok(Self::from(self.state.clone(),self.df@@ -292,7 +313,10 @@ impl BallistaDataFrame {// Result<BallistaDataFrame> { Ok(Self::from(self.state.clone(), self.df.join(right, join_type, &left_cols,// &right_cols).map_err(BallistaError::from)?)) }- pub fn repartition(&self, partitioning_scheme: Partitioning) -> Result<BallistaDataFrame> {+ pub fn repartition(+ &self,+ partitioning_scheme: Partitioning,+ ) -> Result<BallistaDataFrame> {Ok(Self::from(self.state.clone(),self.dfdiff --git a/rust/ballista/rust/core/src/client.rs b/rust/ballista/rust/core/src/client.rsindex c882cfc6c2..f64f95f7cf 100644--- a/rust/ballista/rust/core/src/client.rs+++ b/rust/ballista/rust/core/src/client.rs@@ -62,14 +62,15 @@ impl BallistaClient {pub async fn try_new(host: &str, port: u16) -> Result<Self> {let addr = format!("http://{}:{}", host, port);debug!("BallistaClient connecting to {}", addr);- let flight_client = FlightServiceClient::connect(addr.clone())- .await- .map_err(|e| {- BallistaError::General(format!(- "Error connecting to Ballista scheduler or executor at {}: {:?}",- addr, e- ))- })?;+ let flight_client =+ FlightServiceClient::connect(addr.clone())+ .await+ .map_err(|e| {+ BallistaError::General(format!(+ "Error connecting to Ballista scheduler or executor at {}: {:?}",+ addr, e+ ))+ })?;debug!("BallistaClient connected OK");Ok(Self { flight_client })@@ -105,13 +106,17 @@ impl BallistaClient {.column(0).as_any().downcast_ref::<StringArray>()- .expect("execute_partition expected column 0 to be a StringArray");+ .expect(+ "execute_partition expected column 0 to be a StringArray",+ );let stats = batch.column(1).as_any().downcast_ref::<StructArray>()- .expect("execute_partition expected column 1 to be a StructArray");+ .expect(+ "execute_partition expected column 1 to be a StructArray",+ );Ok(ExecutePartitionResult::new(path.value(0),@@ -129,12 +134,16 @@ impl BallistaClient {stage_id: usize,partition_id: usize,) -> Result<SendableRecordBatchStream> {- let action = Action::FetchPartition(PartitionId::new(job_id, stage_id, partition_id));+ let action =+ Action::FetchPartition(PartitionId::new(job_id, stage_id, partition_id));self.execute_action(&action).await}/// Execute an action and retrieve the results- pub async fn execute_action(&mut self, action: &Action) -> Result<SendableRecordBatchStream> {+ pub async fn execute_action(+ &mut self,+ action: &Action,+ ) -> Result<SendableRecordBatchStream> {let serialized_action: protobuf::Action = action.to_owned().try_into()?;let mut buf: Vec<u8> = Vec::with_capacity(serialized_action.encoded_len());@@ -195,7 +204,11 @@ impl Stream for FlightDataStream {let converted_chunk = flight_data_chunk_result.map_err(|e| ArrowError::from_external_error(Box::new(e))).and_then(|flight_data_chunk| {- flight_data_to_arrow_batch(&flight_data_chunk, self.schema.clone(), &[])+ flight_data_to_arrow_batch(+ &flight_data_chunk,+ self.schema.clone(),+ &[],+ )});Some(converted_chunk)}diff --git a/rust/ballista/rust/core/src/error.rs b/rust/ballista/rust/core/src/error.rsindex 6d629b274f..d0155ce4b7 100644--- a/rust/ballista/rust/core/src/error.rs+++ b/rust/ballista/rust/core/src/error.rs@@ -140,10 +140,14 @@ impl From<tokio::task::JoinError> for BallistaError {impl Display for BallistaError {fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {match self {- BallistaError::NotImplemented(ref desc) => write!(f, "Not implemented: {}", desc),+ BallistaError::NotImplemented(ref desc) => {+ write!(f, "Not implemented: {}", desc)+ }BallistaError::General(ref desc) => write!(f, "General error: {}", desc),BallistaError::ArrowError(ref desc) => write!(f, "Arrow error: {}", desc),- BallistaError::DataFusionError(ref desc) => write!(f, "DataFusion error: {:?}", desc),+ BallistaError::DataFusionError(ref desc) => {+ write!(f, "DataFusion error: {:?}", desc)+ }BallistaError::SqlError(ref desc) => write!(f, "SQL error: {:?}", desc),BallistaError::IoError(ref desc) => write!(f, "IO error: {}", desc),// BallistaError::ReqwestError(ref desc) => write!(f, "Reqwest error: {}", desc),@@ -157,7 +161,9 @@ impl Display for BallistaError {// }BallistaError::TonicError(desc) => write!(f, "Tonic error: {}", desc),BallistaError::GrpcError(desc) => write!(f, "Grpc error: {}", desc),- BallistaError::Internal(desc) => write!(f, "Internal Ballista error: {}", desc),+ BallistaError::Internal(desc) => {+ write!(f, "Internal Ballista error: {}", desc)+ }BallistaError::TokioError(desc) => write!(f, "Tokio join error: {}", desc),}}diff --git a/rust/ballista/rust/core/src/execution_plans/query_stage.rs b/rust/ballista/rust/core/src/execution_plans/query_stage.rsindex bb5878b818..d8822ea313 100644--- a/rust/ballista/rust/core/src/execution_plans/query_stage.rs+++ b/rust/ballista/rust/core/src/execution_plans/query_stage.rs@@ -40,7 +40,11 @@ pub struct QueryStageExec {impl QueryStageExec {/// Create a new query stage- pub fn try_new(job_id: String, stage_id: usize, child: Arc<dyn ExecutionPlan>) -> Result<Self> {+ pub fn try_new(+ job_id: String,+ stage_id: usize,+ child: Arc<dyn ExecutionPlan>,+ ) -> Result<Self> {Ok(Self {job_id,stage_id,diff --git a/rust/ballista/rust/core/src/execution_plans/shuffle_reader.rs b/rust/ballista/rust/core/src/execution_plans/shuffle_reader.rsindex e473613860..bd8f6fdbbe 100644--- a/rust/ballista/rust/core/src/execution_plans/shuffle_reader.rs+++ b/rust/ballista/rust/core/src/execution_plans/shuffle_reader.rs@@ -42,7 +42,10 @@ pub struct ShuffleReaderExec {impl ShuffleReaderExec {/// Create a new ShuffleReaderExec- pub fn try_new(partition_meta: Vec<PartitionLocation>, schema: SchemaRef) -> Result<Self> {+ pub fn try_new(+ partition_meta: Vec<PartitionLocation>,+ schema: SchemaRef,+ ) -> Result<Self> {Ok(Self {partition_location: partition_meta,schema,diff --git a/rust/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs b/rust/ballista/rust/core/src/execution_plans/unresolved_shuffle.rsindex 7fe39375ae..a62a2513ff 100644--- a/rust/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs+++ b/rust/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs@@ -49,7 +49,11 @@ pub struct UnresolvedShuffleExec {impl UnresolvedShuffleExec {/// Create a new UnresolvedShuffleExec- pub fn new(query_stage_ids: Vec<usize>, schema: SchemaRef, partition_count: usize) -> Self {+ pub fn new(+ query_stage_ids: Vec<usize>,+ schema: SchemaRef,+ partition_count: usize,+ ) -> Self {Self {query_stage_ids,schema,@@ -81,7 +85,8 @@ impl ExecutionPlan for UnresolvedShuffleExec {_children: Vec<Arc<dyn ExecutionPlan>>,) -> Result<Arc<dyn ExecutionPlan>> {Err(DataFusionError::Plan(- "Ballista UnresolvedShuffleExec does not support with_new_children()".to_owned(),+ "Ballista UnresolvedShuffleExec does not support with_new_children()"+ .to_owned(),))}diff --git a/rust/ballista/rust/core/src/serde/logical_plan/from_proto.rs b/rust/ballista/rust/core/src/serde/logical_plan/from_proto.rsindex 53ffef4bf7..087ebdbf50 100644--- a/rust/ballista/rust/core/src/serde/logical_plan/from_proto.rs+++ b/rust/ballista/rust/core/src/serde/logical_plan/from_proto.rs@@ -28,8 +28,8 @@ use crate::{convert_box_required, convert_required};use arrow::datatypes::{DataType, Field, Schema};use datafusion::logical_plan::{- abs, acos, asin, atan, ceil, cos, exp, floor, log10, log2, round, signum, sin, sqrt, tan,- trunc, Expr, JoinType, LogicalPlan, LogicalPlanBuilder, Operator,+ abs, acos, asin, atan, ceil, cos, exp, floor, log10, log2, round, signum, sin, sqrt,+ tan, trunc, Expr, JoinType, LogicalPlan, LogicalPlanBuilder, Operator,};use datafusion::physical_plan::aggregates::AggregateFunction;use datafusion::physical_plan::csv::CsvReadOptions;@@ -195,7 +195,8 @@ impl TryInto<LogicalPlan> for &protobuf::LogicalPlanNode {))})?;- let pb_file_type: protobuf::FileType = create_extern_table.file_type.try_into()?;+ let pb_file_type: protobuf::FileType =+ create_extern_table.file_type.try_into()?;Ok(LogicalPlan::CreateExternalTable {schema: pb_schema.try_into()?,@@ -224,12 +225,13 @@ impl TryInto<LogicalPlan> for &protobuf::LogicalPlanNode {join.left_join_column.iter().map(|i| i.as_str()).collect();let right_keys: Vec<&str> =join.right_join_column.iter().map(|i| i.as_str()).collect();- let join_type = protobuf::JoinType::from_i32(join.join_type).ok_or_else(|| {- proto_error(format!(- "Received a JoinNode message with unknown JoinType {}",- join.join_type- ))- })?;+ let join_type =+ protobuf::JoinType::from_i32(join.join_type).ok_or_else(|| {+ proto_error(format!(+ "Received a JoinNode message with unknown JoinType {}",+ join.join_type+ ))+ })?;let join_type = match join_type {protobuf::JoinType::Inner => JoinType::Inner,protobuf::JoinType::Left => JoinType::Left,@@ -291,26 +293,27 @@ impl TryInto<arrow::datatypes::DataType> for &protobuf::scalar_type::Datatype {"Protobuf deserialization error: found no field names in ScalarListType message which requires at least one",));}- let pb_scalar_type = protobuf::PrimitiveScalarType::from_i32(*deepest_type)- .ok_or_else(|| {- proto_error(format!(- "Protobuf deserialization error: invalid i32 for scalar enum: {}",- *deepest_type- ))- })?;+ let pb_scalar_type = protobuf::PrimitiveScalarType::from_i32(+ *deepest_type,+ )+ .ok_or_else(|| {+ proto_error(format!(+ "Protobuf deserialization error: invalid i32 for scalar enum: {}",+ *deepest_type+ ))+ })?;//Because length is checked above it is safe to unwrap .last()- let mut scalar_type = arrow::datatypes::DataType::List(Box::new(Field::new(- field_names.last().unwrap().as_str(),- pb_scalar_type.into(),- true,- )));- //Iterate over field names in reverse order except for the last item in the vector- for name in field_names.iter().rev().skip(1) {- let new_datatype = arrow::datatypes::DataType::List(Box::new(Field::new(- name.as_str(),- scalar_type,+ let mut scalar_type =+ arrow::datatypes::DataType::List(Box::new(Field::new(+ field_names.last().unwrap().as_str(),+ pb_scalar_type.into(),true,)));+ //Iterate over field names in reverse order except for the last item in the vector+ for name in field_names.iter().rev().skip(1) {+ let new_datatype = arrow::datatypes::DataType::List(Box::new(+ Field::new(name.as_str(), scalar_type, true),+ ));scalar_type = new_datatype;}scalar_type@@ -341,7 +344,9 @@ impl TryInto<arrow::datatypes::DataType> for &protobuf::arrow_type::ArrowTypeEnuarrow_type::ArrowTypeEnum::Utf8(_) => DataType::Utf8,arrow_type::ArrowTypeEnum::LargeUtf8(_) => DataType::LargeUtf8,arrow_type::ArrowTypeEnum::Binary(_) => DataType::Binary,- arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => DataType::FixedSizeBinary(*size),+ arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => {+ DataType::FixedSizeBinary(*size)+ }arrow_type::ArrowTypeEnum::LargeBinary(_) => DataType::LargeBinary,arrow_type::ArrowTypeEnum::Date32(_) => DataType::Date32,arrow_type::ArrowTypeEnum::Date64(_) => DataType::Date64,@@ -364,12 +369,13 @@ impl TryInto<arrow::datatypes::DataType> for &protobuf::arrow_type::ArrowTypeEnuarrow_type::ArrowTypeEnum::Time64(time_unit) => {DataType::Time64(protobuf::TimeUnit::from_i32_to_arrow(*time_unit)?)}- arrow_type::ArrowTypeEnum::Interval(interval_unit) => {- DataType::Interval(protobuf::IntervalUnit::from_i32_to_arrow(*interval_unit)?)- }- arrow_type::ArrowTypeEnum::Decimal(protobuf::Decimal { whole, fractional }) => {- DataType::Decimal(*whole as usize, *fractional as usize)- }+ arrow_type::ArrowTypeEnum::Interval(interval_unit) => DataType::Interval(+ protobuf::IntervalUnit::from_i32_to_arrow(*interval_unit)?,+ ),+ arrow_type::ArrowTypeEnum::Decimal(protobuf::Decimal {+ whole,+ fractional,+ }) => DataType::Decimal(*whole as usize, *fractional as usize),arrow_type::ArrowTypeEnum::List(list) => {let list_type: &protobuf::Field = list.as_ref()@@ -468,27 +474,51 @@ fn typechecked_scalar_value_conversion(use protobuf::scalar_value::Value;use protobuf::PrimitiveScalarType;Ok(match (tested_type, &required_type) {- (Value::BoolValue(v), PrimitiveScalarType::Bool) => ScalarValue::Boolean(Some(*v)),- (Value::Int8Value(v), PrimitiveScalarType::Int8) => ScalarValue::Int8(Some(*v as i8)),- (Value::Int16Value(v), PrimitiveScalarType::Int16) => ScalarValue::Int16(Some(*v as i16)),- (Value::Int32Value(v), PrimitiveScalarType::Int32) => ScalarValue::Int32(Some(*v)),- (Value::Int64Value(v), PrimitiveScalarType::Int64) => ScalarValue::Int64(Some(*v)),- (Value::Uint8Value(v), PrimitiveScalarType::Uint8) => ScalarValue::UInt8(Some(*v as u8)),+ (Value::BoolValue(v), PrimitiveScalarType::Bool) => {+ ScalarValue::Boolean(Some(*v))+ }+ (Value::Int8Value(v), PrimitiveScalarType::Int8) => {+ ScalarValue::Int8(Some(*v as i8))+ }+ (Value::Int16Value(v), PrimitiveScalarType::Int16) => {+ ScalarValue::Int16(Some(*v as i16))+ }+ (Value::Int32Value(v), PrimitiveScalarType::Int32) => {+ ScalarValue::Int32(Some(*v))+ }+ (Value::Int64Value(v), PrimitiveScalarType::Int64) => {+ ScalarValue::Int64(Some(*v))+ }+ (Value::Uint8Value(v), PrimitiveScalarType::Uint8) => {+ ScalarValue::UInt8(Some(*v as u8))+ }(Value::Uint16Value(v), PrimitiveScalarType::Uint16) => {ScalarValue::UInt16(Some(*v as u16))}- (Value::Uint32Value(v), PrimitiveScalarType::Uint32) => ScalarValue::UInt32(Some(*v)),- (Value::Uint64Value(v), PrimitiveScalarType::Uint64) => ScalarValue::UInt64(Some(*v)),- (Value::Float32Value(v), PrimitiveScalarType::Float32) => ScalarValue::Float32(Some(*v)),- (Value::Float64Value(v), PrimitiveScalarType::Float64) => ScalarValue::Float64(Some(*v)),- (Value::Date32Value(v), PrimitiveScalarType::Date32) => ScalarValue::Date32(Some(*v)),+ (Value::Uint32Value(v), PrimitiveScalarType::Uint32) => {+ ScalarValue::UInt32(Some(*v))+ }+ (Value::Uint64Value(v), PrimitiveScalarType::Uint64) => {+ ScalarValue::UInt64(Some(*v))+ }+ (Value::Float32Value(v), PrimitiveScalarType::Float32) => {+ ScalarValue::Float32(Some(*v))+ }+ (Value::Float64Value(v), PrimitiveScalarType::Float64) => {+ ScalarValue::Float64(Some(*v))+ }+ (Value::Date32Value(v), PrimitiveScalarType::Date32) => {+ ScalarValue::Date32(Some(*v))+ }(Value::TimeMicrosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {ScalarValue::TimeMicrosecond(Some(*v))}(Value::TimeNanosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {ScalarValue::TimeNanosecond(Some(*v))}- (Value::Utf8Value(v), PrimitiveScalarType::Utf8) => ScalarValue::Utf8(Some(v.to_owned())),+ (Value::Utf8Value(v), PrimitiveScalarType::Utf8) => {+ ScalarValue::Utf8(Some(v.to_owned()))+ }(Value::LargeUtf8Value(v), PrimitiveScalarType::LargeUtf8) => {ScalarValue::LargeUtf8(Some(v.to_owned()))}@@ -516,8 +546,12 @@ fn typechecked_scalar_value_conversion(PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),PrimitiveScalarType::Date32 => ScalarValue::Date32(None),- PrimitiveScalarType::TimeMicrosecond => ScalarValue::TimeMicrosecond(None),- PrimitiveScalarType::TimeNanosecond => ScalarValue::TimeNanosecond(None),+ PrimitiveScalarType::TimeMicrosecond => {+ ScalarValue::TimeMicrosecond(None)+ }+ PrimitiveScalarType::TimeNanosecond => {+ ScalarValue::TimeNanosecond(None)+ }PrimitiveScalarType::Null => {return Err(proto_error("Untyped scalar null is not a valid scalar value",@@ -540,21 +574,41 @@ impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::scalar_value::Valueuse protobuf::PrimitiveScalarType;let scalar = match self {protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),- protobuf::scalar_value::Value::Utf8Value(v) => ScalarValue::Utf8(Some(v.to_owned())),+ protobuf::scalar_value::Value::Utf8Value(v) => {+ ScalarValue::Utf8(Some(v.to_owned()))+ }protobuf::scalar_value::Value::LargeUtf8Value(v) => {ScalarValue::LargeUtf8(Some(v.to_owned()))}- protobuf::scalar_value::Value::Int8Value(v) => ScalarValue::Int8(Some(*v as i8)),- protobuf::scalar_value::Value::Int16Value(v) => ScalarValue::Int16(Some(*v as i16)),+ protobuf::scalar_value::Value::Int8Value(v) => {+ ScalarValue::Int8(Some(*v as i8))+ }+ protobuf::scalar_value::Value::Int16Value(v) => {+ ScalarValue::Int16(Some(*v as i16))+ }protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),- protobuf::scalar_value::Value::Uint8Value(v) => ScalarValue::UInt8(Some(*v as u8)),- protobuf::scalar_value::Value::Uint16Value(v) => ScalarValue::UInt16(Some(*v as u16)),- protobuf::scalar_value::Value::Uint32Value(v) => ScalarValue::UInt32(Some(*v)),- protobuf::scalar_value::Value::Uint64Value(v) => ScalarValue::UInt64(Some(*v)),- protobuf::scalar_value::Value::Float32Value(v) => ScalarValue::Float32(Some(*v)),- protobuf::scalar_value::Value::Float64Value(v) => ScalarValue::Float64(Some(*v)),- protobuf::scalar_value::Value::Date32Value(v) => ScalarValue::Date32(Some(*v)),+ protobuf::scalar_value::Value::Uint8Value(v) => {+ ScalarValue::UInt8(Some(*v as u8))+ }+ protobuf::scalar_value::Value::Uint16Value(v) => {+ ScalarValue::UInt16(Some(*v as u16))+ }+ protobuf::scalar_value::Value::Uint32Value(v) => {+ ScalarValue::UInt32(Some(*v))+ }+ protobuf::scalar_value::Value::Uint64Value(v) => {+ ScalarValue::UInt64(Some(*v))+ }+ protobuf::scalar_value::Value::Float32Value(v) => {+ ScalarValue::Float32(Some(*v))+ }+ protobuf::scalar_value::Value::Float64Value(v) => {+ ScalarValue::Float64(Some(*v))+ }+ protobuf::scalar_value::Value::Date32Value(v) => {+ ScalarValue::Date32(Some(*v))+ }protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {ScalarValue::TimeMicrosecond(Some(*v))}@@ -590,8 +644,11 @@ impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarListValue {.ok_or_else(|| proto_error("Protobuf deserialization error: ScalarListValue.Datatype messsage missing required field 'datatype'"))?;let scalar_values = match scalar_type {Datatype::Scalar(scalar_type_i32) => {- let leaf_scalar_type = protobuf::PrimitiveScalarType::from_i32(*scalar_type_i32)- .ok_or_else(|| proto_error("Error converting i32 to basic scalar type"))?;+ let leaf_scalar_type =+ protobuf::PrimitiveScalarType::from_i32(*scalar_type_i32)+ .ok_or_else(|| {+ proto_error("Error converting i32 to basic scalar type")+ })?;let typechecked_values: Vec<datafusion::scalar::ScalarValue> = values.iter().map(|protobuf::ScalarValue { value: opt_value }| {@@ -613,11 +670,15 @@ impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarListValue {deepest_type,field_names,} = &list_type;- let leaf_type = PrimitiveScalarType::from_i32(*deepest_type)- .ok_or_else(|| proto_error("Error converting i32 to basic scalar type"))?;+ let leaf_type =+ PrimitiveScalarType::from_i32(*deepest_type).ok_or_else(|| {+ proto_error("Error converting i32 to basic scalar type")+ })?;let depth = field_names.len();- let typechecked_values: Vec<datafusion::scalar::ScalarValue> = if depth == 0 {+ let typechecked_values: Vec<datafusion::scalar::ScalarValue> = if depth+ == 0+ {return Err(proto_error("Protobuf deserialization error, ScalarListType had no field names, requires at least one",));@@ -675,14 +736,17 @@ impl TryInto<arrow::datatypes::DataType> for &protobuf::ScalarListType {//Since checked vector is not empty above this is safe to unwrapfield_names.last().unwrap(),PrimitiveScalarType::from_i32(*deepest_type)- .ok_or_else(|| proto_error("Could not convert to datafusion scalar type"))?+ .ok_or_else(|| {+ proto_error("Could not convert to datafusion scalar type")+ })?.into(),true,)));//Iterates over field names in reverse order except for the last item in the vectorfor name in field_names.iter().rev().skip(1) {- let temp_curr_type =- arrow::datatypes::DataType::List(Box::new(Field::new(name, curr_type, true)));+ let temp_curr_type = arrow::datatypes::DataType::List(Box::new(Field::new(+ name, curr_type, true,+ )));curr_type = temp_curr_type;}Ok(curr_type)@@ -711,8 +775,12 @@ impl TryInto<datafusion::scalar::ScalarValue> for protobuf::PrimitiveScalarTypeprotobuf::PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),protobuf::PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),protobuf::PrimitiveScalarType::Date32 => ScalarValue::Date32(None),- protobuf::PrimitiveScalarType::TimeMicrosecond => ScalarValue::TimeMicrosecond(None),- protobuf::PrimitiveScalarType::TimeNanosecond => ScalarValue::TimeNanosecond(None),+ protobuf::PrimitiveScalarType::TimeMicrosecond => {+ ScalarValue::TimeMicrosecond(None)+ }+ protobuf::PrimitiveScalarType::TimeNanosecond => {+ ScalarValue::TimeNanosecond(None)+ }})}}@@ -725,21 +793,41 @@ impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarValue {})?;Ok(match value {protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),- protobuf::scalar_value::Value::Utf8Value(v) => ScalarValue::Utf8(Some(v.to_owned())),+ protobuf::scalar_value::Value::Utf8Value(v) => {+ ScalarValue::Utf8(Some(v.to_owned()))+ }protobuf::scalar_value::Value::LargeUtf8Value(v) => {ScalarValue::LargeUtf8(Some(v.to_owned()))}- protobuf::scalar_value::Value::Int8Value(v) => ScalarValue::Int8(Some(*v as i8)),- protobuf::scalar_value::Value::Int16Value(v) => ScalarValue::Int16(Some(*v as i16)),+ protobuf::scalar_value::Value::Int8Value(v) => {+ ScalarValue::Int8(Some(*v as i8))+ }+ protobuf::scalar_value::Value::Int16Value(v) => {+ ScalarValue::Int16(Some(*v as i16))+ }protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),- protobuf::scalar_value::Value::Uint8Value(v) => ScalarValue::UInt8(Some(*v as u8)),- protobuf::scalar_value::Value::Uint16Value(v) => ScalarValue::UInt16(Some(*v as u16)),- protobuf::scalar_value::Value::Uint32Value(v) => ScalarValue::UInt32(Some(*v)),- protobuf::scalar_value::Value::Uint64Value(v) => ScalarValue::UInt64(Some(*v)),- protobuf::scalar_value::Value::Float32Value(v) => ScalarValue::Float32(Some(*v)),- protobuf::scalar_value::Value::Float64Value(v) => ScalarValue::Float64(Some(*v)),- protobuf::scalar_value::Value::Date32Value(v) => ScalarValue::Date32(Some(*v)),+ protobuf::scalar_value::Value::Uint8Value(v) => {+ ScalarValue::UInt8(Some(*v as u8))+ }+ protobuf::scalar_value::Value::Uint16Value(v) => {+ ScalarValue::UInt16(Some(*v as u16))+ }+ protobuf::scalar_value::Value::Uint32Value(v) => {+ ScalarValue::UInt32(Some(*v))+ }+ protobuf::scalar_value::Value::Uint64Value(v) => {+ ScalarValue::UInt64(Some(*v))+ }+ protobuf::scalar_value::Value::Float32Value(v) => {+ ScalarValue::Float32(Some(*v))+ }+ protobuf::scalar_value::Value::Float64Value(v) => {+ ScalarValue::Float64(Some(*v))+ }+ protobuf::scalar_value::Value::Date32Value(v) => {+ ScalarValue::Date32(Some(*v))+ }protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {ScalarValue::TimeMicrosecond(Some(*v))}@@ -758,7 +846,8 @@ impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarValue {.iter().map(|val| val.try_into()).collect::<Result<Vec<_>, _>>()?;- let scalar_type: arrow::datatypes::DataType = pb_scalar_type.try_into()?;+ let scalar_type: arrow::datatypes::DataType =+ pb_scalar_type.try_into()?;ScalarValue::List(Some(typechecked_values), scalar_type)}protobuf::scalar_value::Value::NullListValue(v) => {@@ -800,13 +889,14 @@ impl TryInto<Expr> for &protobuf::LogicalExprNode {Ok(Expr::Literal(scalar_value))}ExprType::AggregateExpr(expr) => {- let aggr_function = protobuf::AggregateFunction::from_i32(expr.aggr_function)- .ok_or_else(|| {- proto_error(format!(- "Received an unknown aggregate function: {}",- expr.aggr_function- ))- })?;+ let aggr_function =+ protobuf::AggregateFunction::from_i32(expr.aggr_function)+ .ok_or_else(|| {+ proto_error(format!(+ "Received an unknown aggregate function: {}",+ expr.aggr_function+ ))+ })?;let fun = match aggr_function {protobuf::AggregateFunction::Min => AggregateFunction::Min,protobuf::AggregateFunction::Max => AggregateFunction::Max,@@ -831,7 +921,9 @@ impl TryInto<Expr> for &protobuf::LogicalExprNode {ExprType::IsNotNullExpr(is_not_null) => Ok(Expr::IsNotNull(Box::new(parse_required_expr(&is_not_null.expr)?,))),- ExprType::NotExpr(not) => Ok(Expr::Not(Box::new(parse_required_expr(¬.expr)?))),+ ExprType::NotExpr(not) => {+ Ok(Expr::Not(Box::new(parse_required_expr(¬.expr)?)))+ }ExprType::Between(between) => Ok(Expr::Between {expr: Box::new(parse_required_expr(&between.expr)?),negated: between.negated,@@ -875,9 +967,9 @@ impl TryInto<Expr> for &protobuf::LogicalExprNode {asc: sort.asc,nulls_first: sort.nulls_first,}),- ExprType::Negative(negative) => Ok(Expr::Negative(Box::new(parse_required_expr(- &negative.expr,- )?))),+ ExprType::Negative(negative) => Ok(Expr::Negative(Box::new(+ parse_required_expr(&negative.expr)?,+ ))),ExprType::InList(in_list) => Ok(Expr::InList {expr: Box::new(parse_required_expr(&in_list.expr)?),list: in_list@@ -889,45 +981,84 @@ impl TryInto<Expr> for &protobuf::LogicalExprNode {}),ExprType::Wildcard(_) => Ok(Expr::Wildcard),ExprType::ScalarFunction(expr) => {- let scalar_function =- protobuf::ScalarFunction::from_i32(expr.fun).ok_or_else(|| {- proto_error(format!("Received an unknown scalar function: {}", expr.fun))+ let scalar_function = protobuf::ScalarFunction::from_i32(expr.fun)+ .ok_or_else(|| {+ proto_error(format!(+ "Received an unknown scalar function: {}",+ expr.fun+ ))})?;match scalar_function {- protobuf::ScalarFunction::Sqrt => Ok(sqrt((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Sqrt => {+ Ok(sqrt((&expr.expr[0]).try_into()?))+ }protobuf::ScalarFunction::Sin => Ok(sin((&expr.expr[0]).try_into()?)),protobuf::ScalarFunction::Cos => Ok(cos((&expr.expr[0]).try_into()?)),protobuf::ScalarFunction::Tan => Ok(tan((&expr.expr[0]).try_into()?)),// protobuf::ScalarFunction::Asin => Ok(asin(&expr.expr[0]).try_into()?)),// protobuf::ScalarFunction::Acos => Ok(acos(&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Atan => Ok(atan((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Atan => {+ Ok(atan((&expr.expr[0]).try_into()?))+ }protobuf::ScalarFunction::Exp => Ok(exp((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Log2 => Ok(log2((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Log10 => Ok(log10((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Floor => Ok(floor((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Ceil => Ok(ceil((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Round => Ok(round((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Trunc => Ok(trunc((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Log2 => {+ Ok(log2((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Log10 => {+ Ok(log10((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Floor => {+ Ok(floor((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Ceil => {+ Ok(ceil((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Round => {+ Ok(round((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Trunc => {+ Ok(trunc((&expr.expr[0]).try_into()?))+ }protobuf::ScalarFunction::Abs => Ok(abs((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Signum => Ok(signum((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Signum => {+ Ok(signum((&expr.expr[0]).try_into()?))+ }protobuf::ScalarFunction::Octetlength => {Ok(length((&expr.expr[0]).try_into()?))}// // protobuf::ScalarFunction::Concat => Ok(concat((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Lower => Ok(lower((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Upper => Ok(upper((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Trim => Ok(trim((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Ltrim => Ok(ltrim((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Rtrim => Ok(rtrim((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Lower => {+ Ok(lower((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Upper => {+ Ok(upper((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Trim => {+ Ok(trim((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Ltrim => {+ Ok(ltrim((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Rtrim => {+ Ok(rtrim((&expr.expr[0]).try_into()?))+ }// protobuf::ScalarFunction::Totimestamp => Ok(to_timestamp((&expr.expr[0]).try_into()?)),// protobuf::ScalarFunction::Array => Ok(array((&expr.expr[0]).try_into()?)),// // protobuf::ScalarFunction::Nullif => Ok(nulli((&expr.expr[0]).try_into()?)),// protobuf::ScalarFunction::Datetrunc => Ok(date_trunc((&expr.expr[0]).try_into()?)),// protobuf::ScalarFunction::Md5 => Ok(md5((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Sha224 => Ok(sha224((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Sha256 => Ok(sha256((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Sha384 => Ok(sha384((&expr.expr[0]).try_into()?)),- protobuf::ScalarFunction::Sha512 => Ok(sha512((&expr.expr[0]).try_into()?)),+ protobuf::ScalarFunction::Sha224 => {+ Ok(sha224((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Sha256 => {+ Ok(sha256((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Sha384 => {+ Ok(sha384((&expr.expr[0]).try_into()?))+ }+ protobuf::ScalarFunction::Sha512 => {+ Ok(sha512((&expr.expr[0]).try_into()?))+ }_ => Err(proto_error("Protobuf deserialization error: Unsupported scalar function",)),@@ -962,10 +1093,9 @@ fn from_proto_binary_op(op: &str) -> Result<Operator, BallistaError> {impl TryInto<arrow::datatypes::DataType> for &protobuf::ScalarType {type Error = BallistaError;fn try_into(self) -> Result<arrow::datatypes::DataType, Self::Error> {- let pb_scalartype = self- .datatype- .as_ref()- .ok_or_else(|| proto_error("ScalarType message missing required field 'datatype'"))?;+ let pb_scalartype = self.datatype.as_ref().ok_or_else(|| {+ proto_error("ScalarType message missing required field 'datatype'")+ })?;pb_scalartype.try_into()}}@@ -1043,7 +1173,9 @@ impl Into<datafusion::sql::parser::FileType> for protobuf::FileType {}}-fn parse_required_expr(p: &Option<Box<protobuf::LogicalExprNode>>) -> Result<Expr, BallistaError> {+fn parse_required_expr(+ p: &Option<Box<protobuf::LogicalExprNode>>,+) -> Result<Expr, BallistaError> {match p {Some(expr) => expr.as_ref().try_into(),None => Err(proto_error("Missing required expression")),diff --git a/rust/ballista/rust/core/src/serde/logical_plan/mod.rs b/rust/ballista/rust/core/src/serde/logical_plan/mod.rsindex ba4590a697..50a529b6fa 100644--- a/rust/ballista/rust/core/src/serde/logical_plan/mod.rs+++ b/rust/ballista/rust/core/src/serde/logical_plan/mod.rs@@ -119,7 +119,11 @@ mod roundtrip_tests {Ok(())}- fn new_box_field(name: &str, dt: DataType, nullable: bool) -> Box<arrow::datatypes::Field> {+ fn new_box_field(+ name: &str,+ dt: DataType,+ nullable: bool,+ ) -> Box<arrow::datatypes::Field> {Box::new(arrow::datatypes::Field::new(name, dt, nullable))}@@ -613,7 +617,8 @@ mod roundtrip_tests {for test_case in test_types.into_iter() {let proto_scalar: protobuf::ScalarValue = (&test_case).try_into()?;- let returned_scalar: datafusion::scalar::ScalarValue = (&proto_scalar).try_into()?;+ let returned_scalar: datafusion::scalar::ScalarValue =+ (&proto_scalar).try_into()?;assert_eq!(format!("{:?}", &test_case),format!("{:?}", returned_scalar)@@ -640,7 +645,8 @@ mod roundtrip_tests {use datafusion::sql::parser::FileType;- let filetypes: [FileType; 3] = [FileType::NdJson, FileType::Parquet, FileType::CSV];+ let filetypes: [FileType; 3] =+ [FileType::NdJson, FileType::Parquet, FileType::CSV];for file in filetypes.iter() {let create_table_node = LogicalPlan::CreateExternalTable {diff --git a/rust/ballista/rust/core/src/serde/logical_plan/to_proto.rs b/rust/ballista/rust/core/src/serde/logical_plan/to_proto.rsindex beee4182ff..69b53502fc 100644--- a/rust/ballista/rust/core/src/serde/logical_plan/to_proto.rs+++ b/rust/ballista/rust/core/src/serde/logical_plan/to_proto.rs@@ -33,17 +33,21 @@ use datafusion::logical_plan::{Expr, JoinType, LogicalPlan};use datafusion::physical_plan::aggregates::AggregateFunction;use datafusion::{datasource::parquet::ParquetTable, logical_plan::exprlist_to_fields};use protobuf::{- arrow_type, logical_expr_node::ExprType, scalar_type, DateUnit, Field, PrimitiveScalarType,- ScalarListValue, ScalarType,+ arrow_type, logical_expr_node::ExprType, scalar_type, DateUnit, Field,+ PrimitiveScalarType, ScalarListValue, ScalarType,};use super::super::proto_error;use datafusion::physical_plan::functions::BuiltinScalarFunction;impl protobuf::IntervalUnit {- pub fn from_arrow_interval_unit(interval_unit: &arrow::datatypes::IntervalUnit) -> Self {+ pub fn from_arrow_interval_unit(+ interval_unit: &arrow::datatypes::IntervalUnit,+ ) -> Self {match interval_unit {- arrow::datatypes::IntervalUnit::YearMonth => protobuf::IntervalUnit::YearMonth,+ arrow::datatypes::IntervalUnit::YearMonth => {+ protobuf::IntervalUnit::YearMonth+ }arrow::datatypes::IntervalUnit::DayTime => protobuf::IntervalUnit::DayTime,}}@@ -91,7 +95,9 @@ impl protobuf::TimeUnit {pub fn from_arrow_time_unit(val: &arrow::datatypes::TimeUnit) -> Self {match val {arrow::datatypes::TimeUnit::Second => protobuf::TimeUnit::Second,- arrow::datatypes::TimeUnit::Millisecond => protobuf::TimeUnit::TimeMillisecond,+ arrow::datatypes::TimeUnit::Millisecond => {+ protobuf::TimeUnit::TimeMillisecond+ }arrow::datatypes::TimeUnit::Microsecond => protobuf::TimeUnit::Microsecond,arrow::datatypes::TimeUnit::Nanosecond => protobuf::TimeUnit::Nanosecond,}@@ -169,22 +175,26 @@ impl TryInto<arrow::datatypes::DataType> for &protobuf::ArrowType {protobuf::arrow_type::ArrowTypeEnum::Duration(time_unit_i32) => {DataType::Duration(protobuf::TimeUnit::from_i32_to_arrow(*time_unit_i32)?)}- protobuf::arrow_type::ArrowTypeEnum::Timestamp(timestamp) => DataType::Timestamp(- protobuf::TimeUnit::from_i32_to_arrow(timestamp.time_unit)?,- match timestamp.timezone.is_empty() {- true => None,- false => Some(timestamp.timezone.to_owned()),- },- ),+ protobuf::arrow_type::ArrowTypeEnum::Timestamp(timestamp) => {+ DataType::Timestamp(+ protobuf::TimeUnit::from_i32_to_arrow(timestamp.time_unit)?,+ match timestamp.timezone.is_empty() {+ true => None,+ false => Some(timestamp.timezone.to_owned()),+ },+ )+ }protobuf::arrow_type::ArrowTypeEnum::Time32(time_unit_i32) => {DataType::Time32(protobuf::TimeUnit::from_i32_to_arrow(*time_unit_i32)?)}protobuf::arrow_type::ArrowTypeEnum::Time64(time_unit_i32) => {DataType::Time64(protobuf::TimeUnit::from_i32_to_arrow(*time_unit_i32)?)}- protobuf::arrow_type::ArrowTypeEnum::Interval(interval_unit_i32) => DataType::Interval(- protobuf::IntervalUnit::from_i32_to_arrow(*interval_unit_i32)?,- ),+ protobuf::arrow_type::ArrowTypeEnum::Interval(interval_unit_i32) => {+ DataType::Interval(protobuf::IntervalUnit::from_i32_to_arrow(+ *interval_unit_i32,+ )?)+ }protobuf::arrow_type::ArrowTypeEnum::Decimal(protobuf::Decimal {whole,fractional,@@ -295,15 +305,15 @@ impl From<&arrow::datatypes::DataType> for protobuf::arrow_type::ArrowTypeEnum {}DataType::Date32 => ArrowTypeEnum::Date32(EmptyMessage {}),DataType::Date64 => ArrowTypeEnum::Date64(EmptyMessage {}),- DataType::Time32(time_unit) => {- ArrowTypeEnum::Time32(protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32)- }- DataType::Time64(time_unit) => {- ArrowTypeEnum::Time64(protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32)- }- DataType::Duration(time_unit) => {- ArrowTypeEnum::Duration(protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32)- }+ DataType::Time32(time_unit) => ArrowTypeEnum::Time32(+ protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,+ ),+ DataType::Time64(time_unit) => ArrowTypeEnum::Time64(+ protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,+ ),+ DataType::Duration(time_unit) => ArrowTypeEnum::Duration(+ protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,+ ),DataType::Interval(interval_unit) => ArrowTypeEnum::Interval(protobuf::IntervalUnit::from_arrow_interval_unit(interval_unit) as i32,),@@ -321,9 +331,11 @@ impl From<&arrow::datatypes::DataType> for protobuf::arrow_type::ArrowTypeEnum {list_size: *size,}))}- DataType::LargeList(item_type) => ArrowTypeEnum::LargeList(Box::new(protobuf::List {- field_type: Some(Box::new(item_type.as_ref().into())),- })),+ DataType::LargeList(item_type) => {+ ArrowTypeEnum::LargeList(Box::new(protobuf::List {+ field_type: Some(Box::new(item_type.as_ref().into())),+ }))+ }DataType::Struct(struct_fields) => ArrowTypeEnum::Struct(protobuf::Struct {sub_field_types: struct_fields.iter()@@ -342,10 +354,12 @@ impl From<&arrow::datatypes::DataType> for protobuf::arrow_type::ArrowTypeEnum {value: Some(Box::new(value_type.as_ref().into())),}))}- DataType::Decimal(whole, fractional) => ArrowTypeEnum::Decimal(protobuf::Decimal {- whole: *whole as u64,- fractional: *fractional as u64,- }),+ DataType::Decimal(whole, fractional) => {+ ArrowTypeEnum::Decimal(protobuf::Decimal {+ whole: *whole as u64,+ fractional: *fractional as u64,+ })+ }}}}@@ -369,7 +383,8 @@ fn is_valid_scalar_type_no_list_check(datatype: &arrow::datatypes::DataType) ->| DataType::Date32 => true,DataType::Time64(time_unit) => matches!(time_unit,- arrow::datatypes::TimeUnit::Microsecond | arrow::datatypes::TimeUnit::Nanosecond+ arrow::datatypes::TimeUnit::Microsecond+ | arrow::datatypes::TimeUnit::Nanosecond),DataType::List(_) => true,@@ -663,7 +678,8 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {let schema = source.schema();// unwrap the DFTableAdapter to get to the real TableProvider- let source = if let Some(adapter) = source.as_any().downcast_ref::<DFTableAdapter>()+ let source = if let Some(adapter) =+ source.as_any().downcast_ref::<DFTableAdapter>(){match &adapter.logical_plan {LogicalPlan::TableScan { source, .. } => Ok(source.as_any()),@@ -708,8 +724,9 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {})} else if let Some(csv) = source.downcast_ref::<CsvFile>() {let delimiter = [csv.delimiter()];- let delimiter = std::str::from_utf8(&delimiter)- .map_err(|_| BallistaError::General("Invalid CSV delimiter".to_owned()))?;+ let delimiter = std::str::from_utf8(&delimiter).map_err(|_| {+ BallistaError::General("Invalid CSV delimiter".to_owned())+ })?;Ok(protobuf::LogicalPlanNode {logical_plan_type: Some(LogicalPlanType::CsvScan(protobuf::CsvTableScanNode {@@ -731,18 +748,19 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {)))}}- LogicalPlan::Projection { expr, input, .. } => Ok(protobuf::LogicalPlanNode {- logical_plan_type: Some(LogicalPlanType::Projection(Box::new(- protobuf::ProjectionNode {- input: Some(Box::new(input.as_ref().try_into()?)),- expr: expr.iter().map(|expr| expr.try_into()).collect::<Result<- Vec<_>,- BallistaError,- >>(- )?,- },- ))),- }),+ LogicalPlan::Projection { expr, input, .. } => {+ Ok(protobuf::LogicalPlanNode {+ logical_plan_type: Some(LogicalPlanType::Projection(Box::new(+ protobuf::ProjectionNode {+ input: Some(Box::new(input.as_ref().try_into()?)),+ expr: expr+ .iter()+ .map(|expr| expr.try_into())+ .collect::<Result<Vec<_>, BallistaError>>()?,+ },+ ))),+ })+ }LogicalPlan::Filter { predicate, input } => {let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;Ok(protobuf::LogicalPlanNode {@@ -794,13 +812,15 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {let left_join_column = on.iter().map(|on| on.0.to_owned()).collect();let right_join_column = on.iter().map(|on| on.1.to_owned()).collect();Ok(protobuf::LogicalPlanNode {- logical_plan_type: Some(LogicalPlanType::Join(Box::new(protobuf::JoinNode {- left: Some(Box::new(left)),- right: Some(Box::new(right)),- join_type: join_type.into(),- left_join_column,- right_join_column,- }))),+ logical_plan_type: Some(LogicalPlanType::Join(Box::new(+ protobuf::JoinNode {+ left: Some(Box::new(left)),+ right: Some(Box::new(right)),+ join_type: join_type.into(),+ left_join_column,+ right_join_column,+ },+ ))),})}LogicalPlan::Limit { input, n } => {@@ -821,10 +841,12 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {.map(|expr| expr.try_into()).collect::<Result<Vec<_>, BallistaError>>()?;Ok(protobuf::LogicalPlanNode {- logical_plan_type: Some(LogicalPlanType::Sort(Box::new(protobuf::SortNode {- input: Some(Box::new(input)),- expr: selection_expr,- }))),+ logical_plan_type: Some(LogicalPlanType::Sort(Box::new(+ protobuf::SortNode {+ input: Some(Box::new(input)),+ expr: selection_expr,+ },+ ))),})}LogicalPlan::Repartition {@@ -841,11 +863,10 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {let pb_partition_method = match partitioning_scheme {Partitioning::Hash(exprs, partition_count) => {PartitionMethod::Hash(protobuf::HashRepartition {- hash_expr: exprs.iter().map(|expr| expr.try_into()).collect::<Result<- Vec<_>,- BallistaError,- >>(- )?,+ hash_expr: exprs+ .iter()+ .map(|expr| expr.try_into())+ .collect::<Result<Vec<_>, BallistaError>>()?,partition_count: *partition_count as u64,})}@@ -1000,17 +1021,19 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {Expr::ScalarVariable(_) => unimplemented!(),Expr::ScalarFunction { ref fun, ref args } => {let fun: protobuf::ScalarFunction = fun.try_into()?;- let expr: Vec<protobuf::LogicalExprNode> =- args.iter()- .map(|e| Ok(e.try_into()?))- .collect::<Result<Vec<protobuf::LogicalExprNode>, BallistaError>>()?;+ let expr: Vec<protobuf::LogicalExprNode> = args+ .iter()+ .map(|e| Ok(e.try_into()?))+ .collect::<Result<Vec<protobuf::LogicalExprNode>, BallistaError>>()?;Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::ScalarFunction(- protobuf::ScalarFunctionNode {- fun: fun.into(),- expr,- },- )),+ expr_type: Some(+ protobuf::logical_expr_node::ExprType::ScalarFunction(+ protobuf::ScalarFunctionNode {+ fun: fun.into(),+ expr,+ },+ ),+ ),})}Expr::ScalarUDF { .. } => unimplemented!(),@@ -1112,7 +1135,9 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {expr: Some(Box::new(expr.as_ref().try_into()?)),});Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::Negative(expr)),+ expr_type: Some(protobuf::logical_expr_node::ExprType::Negative(+ expr,+ )),})}Expr::InList {@@ -1122,10 +1147,11 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {} => {let expr = Box::new(protobuf::InListNode {expr: Some(Box::new(expr.as_ref().try_into()?)),- list: list- .iter()- .map(|expr| expr.try_into())- .collect::<Result<Vec<_>, BallistaError>>()?,+ list: list.iter().map(|expr| expr.try_into()).collect::<Result<+ Vec<_>,+ BallistaError,+ >>(+ )?,negated: *negated,});Ok(protobuf::LogicalExprNode {@@ -1184,14 +1210,18 @@ impl TryInto<protobuf::ScalarFunction> for &BuiltinScalarFunction {BuiltinScalarFunction::Round => Ok(protobuf::ScalarFunction::Round),BuiltinScalarFunction::Trunc => Ok(protobuf::ScalarFunction::Trunc),BuiltinScalarFunction::Abs => Ok(protobuf::ScalarFunction::Abs),- BuiltinScalarFunction::OctetLength => Ok(protobuf::ScalarFunction::Octetlength),+ BuiltinScalarFunction::OctetLength => {+ Ok(protobuf::ScalarFunction::Octetlength)+ }BuiltinScalarFunction::Concat => Ok(protobuf::ScalarFunction::Concat),BuiltinScalarFunction::Lower => Ok(protobuf::ScalarFunction::Lower),BuiltinScalarFunction::Upper => Ok(protobuf::ScalarFunction::Upper),BuiltinScalarFunction::Trim => Ok(protobuf::ScalarFunction::Trim),BuiltinScalarFunction::Ltrim => Ok(protobuf::ScalarFunction::Ltrim),BuiltinScalarFunction::Rtrim => Ok(protobuf::ScalarFunction::Rtrim),- BuiltinScalarFunction::ToTimestamp => Ok(protobuf::ScalarFunction::Totimestamp),+ BuiltinScalarFunction::ToTimestamp => {+ Ok(protobuf::ScalarFunction::Totimestamp)+ }BuiltinScalarFunction::Array => Ok(protobuf::ScalarFunction::Array),BuiltinScalarFunction::NullIf => Ok(protobuf::ScalarFunction::Nullif),BuiltinScalarFunction::DateTrunc => Ok(protobuf::ScalarFunction::Datetrunc),diff --git a/rust/ballista/rust/core/src/serde/physical_plan/from_proto.rs b/rust/ballista/rust/core/src/serde/physical_plan/from_proto.rsindex 2b82706db9..cb04a3e819 100644--- a/rust/ballista/rust/core/src/serde/physical_plan/from_proto.rs+++ b/rust/ballista/rust/core/src/serde/physical_plan/from_proto.rs@@ -70,7 +70,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {})?;match plan {PhysicalPlanType::Projection(projection) => {- let input: Arc<dyn ExecutionPlan> = convert_box_required!(projection.input)?;+ let input: Arc<dyn ExecutionPlan> =+ convert_box_required!(projection.input)?;let exprs = projection.expr.iter()@@ -86,7 +87,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {let predicate = compile_expr(filter.expr.as_ref().ok_or_else(|| {BallistaError::General(- "filter (FilterExecNode) in PhysicalPlanNode is missing.".to_owned(),+ "filter (FilterExecNode) in PhysicalPlanNode is missing."+ .to_owned(),)})?,&input.schema(),@@ -113,7 +115,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {}PhysicalPlanType::ParquetScan(scan) => {let projection = scan.projection.iter().map(|i| *i as usize).collect();- let filenames: Vec<&str> = scan.filename.iter().map(|s| s.as_str()).collect();+ let filenames: Vec<&str> =+ scan.filename.iter().map(|s| s.as_str()).collect();Ok(Arc::new(ParquetExec::try_from_files(&filenames,Some(projection),@@ -123,7 +126,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {)?))}PhysicalPlanType::CoalesceBatches(coalesce_batches) => {- let input: Arc<dyn ExecutionPlan> = convert_box_required!(coalesce_batches.input)?;+ let input: Arc<dyn ExecutionPlan> =+ convert_box_required!(coalesce_batches.input)?;Ok(Arc::new(CoalesceBatchesExec::new(input,coalesce_batches.target_batch_size as usize,@@ -145,19 +149,26 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {Ok(Arc::new(RepartitionExec::try_new(input,- Partitioning::Hash(expr, hash_part.partition_count.try_into().unwrap()),+ Partitioning::Hash(+ expr,+ hash_part.partition_count.try_into().unwrap(),+ ),)?))}Some(PartitionMethod::RoundRobin(partition_count)) => {Ok(Arc::new(RepartitionExec::try_new(input,- Partitioning::RoundRobinBatch(partition_count.try_into().unwrap()),+ Partitioning::RoundRobinBatch(+ partition_count.try_into().unwrap(),+ ),)?))}Some(PartitionMethod::Unknown(partition_count)) => {Ok(Arc::new(RepartitionExec::try_new(input,- Partitioning::UnknownPartitioning(partition_count.try_into().unwrap()),+ Partitioning::UnknownPartitioning(+ partition_count.try_into().unwrap(),+ ),)?))}_ => Err(BallistaError::General(@@ -174,7 +185,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {Ok(Arc::new(LocalLimitExec::new(input, limit.limit as usize)))}PhysicalPlanType::HashAggregate(hash_agg) => {- let input: Arc<dyn ExecutionPlan> = convert_box_required!(hash_agg.input)?;+ let input: Arc<dyn ExecutionPlan> =+ convert_box_required!(hash_agg.input)?;let mode = protobuf::AggregateMode::from_i32(hash_agg.mode).ok_or_else(|| {proto_error(format!("Received a HashAggregateNode message with unknown AggregateMode {}",@@ -220,7 +232,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {)})?.clone();- let physical_schema: SchemaRef = SchemaRef::new((&input_schema).try_into()?);+ let physical_schema: SchemaRef =+ SchemaRef::new((&input_schema).try_into()?);let mut physical_aggr_expr = vec![];@@ -228,8 +241,14 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {match expr {Expr::AggregateFunction { fun, args, .. } => {let arg = df_planner- .create_physical_expr(&args[0], &physical_schema, &ctx_state)- .map_err(|e| BallistaError::General(format!("{:?}", e)))?;+ .create_physical_expr(+ &args[0],+ &physical_schema,+ &ctx_state,+ )+ .map_err(|e| {+ BallistaError::General(format!("{:?}", e))+ })?;physical_aggr_expr.push(create_aggregate_expr(&fun,false,@@ -255,14 +274,15 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {}PhysicalPlanType::HashJoin(hashjoin) => {let left: Arc<dyn ExecutionPlan> = convert_box_required!(hashjoin.left)?;- let right: Arc<dyn ExecutionPlan> = convert_box_required!(hashjoin.right)?;+ let right: Arc<dyn ExecutionPlan> =+ convert_box_required!(hashjoin.right)?;let on: Vec<(String, String)> = hashjoin.on.iter().map(|col| (col.left.clone(), col.right.clone())).collect();- let join_type =- protobuf::JoinType::from_i32(hashjoin.join_type).ok_or_else(|| {+ let join_type = protobuf::JoinType::from_i32(hashjoin.join_type)+ .ok_or_else(|| {proto_error(format!("Received a HashJoinNode message with unknown JoinType {}",hashjoin.join_type@@ -284,7 +304,8 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {.iter().map(|p| p.clone().try_into()).collect::<Result<Vec<_>, BallistaError>>()?;- let shuffle_reader = ShuffleReaderExec::try_new(partition_location, schema)?;+ let shuffle_reader =+ ShuffleReaderExec::try_new(partition_location, schema)?;Ok(Arc::new(shuffle_reader))}PhysicalPlanType::Empty(empty) => {diff --git a/rust/ballista/rust/core/src/serde/physical_plan/mod.rs b/rust/ballista/rust/core/src/serde/physical_plan/mod.rsindex 4d8a189ab7..a6f146c738 100644--- a/rust/ballista/rust/core/src/serde/physical_plan/mod.rs+++ b/rust/ballista/rust/core/src/serde/physical_plan/mod.rs@@ -34,7 +34,9 @@ mod roundtrip_tests {sort::SortExec,ExecutionPlan,};- use datafusion::physical_plan::{AggregateExpr, Distribution, Partitioning, PhysicalExpr};+ use datafusion::physical_plan::{+ AggregateExpr, Distribution, Partitioning, PhysicalExpr,+ };use super::super::super::error::Result;use super::super::protobuf;@@ -92,7 +94,8 @@ mod roundtrip_tests {#[test]fn rountrip_hash_aggregate() -> Result<()> {use arrow::datatypes::{DataType, Field, Schema};- let groups: Vec<(Arc<dyn PhysicalExpr>, String)> = vec![(col("a"), "unused".to_string())];+ let groups: Vec<(Arc<dyn PhysicalExpr>, String)> =+ vec![(col("a"), "unused".to_string())];let aggregates: Vec<Arc<dyn AggregateExpr>> = vec![Arc::new(Avg::new(col("b"),diff --git a/rust/ballista/rust/core/src/serde/physical_plan/to_proto.rs b/rust/ballista/rust/core/src/serde/physical_plan/to_proto.rsindex 3aab3d2bc8..24c69c4692 100644--- a/rust/ballista/rust/core/src/serde/physical_plan/to_proto.rs+++ b/rust/ballista/rust/core/src/serde/physical_plan/to_proto.rs@@ -96,7 +96,8 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {))),})} else if let Some(limit) = plan.downcast_ref::<GlobalLimitExec>() {- let input: protobuf::PhysicalPlanNode = limit.input().to_owned().try_into()?;+ let input: protobuf::PhysicalPlanNode =+ limit.input().to_owned().try_into()?;Ok(protobuf::PhysicalPlanNode {physical_plan_type: Some(PhysicalPlanType::GlobalLimit(Box::new(protobuf::GlobalLimitExecNode {@@ -106,7 +107,8 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {))),})} else if let Some(limit) = plan.downcast_ref::<LocalLimitExec>() {- let input: protobuf::PhysicalPlanNode = limit.input().to_owned().try_into()?;+ let input: protobuf::PhysicalPlanNode =+ limit.input().to_owned().try_into()?;Ok(protobuf::PhysicalPlanNode {physical_plan_type: Some(PhysicalPlanType::LocalLimit(Box::new(protobuf::LocalLimitExecNode {@@ -188,12 +190,15 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {} else if let Some(empty) = plan.downcast_ref::<EmptyExec>() {let schema = empty.schema().as_ref().into();Ok(protobuf::PhysicalPlanNode {- physical_plan_type: Some(PhysicalPlanType::Empty(protobuf::EmptyExecNode {- produce_one_row: empty.produce_one_row(),- schema: Some(schema),- })),+ physical_plan_type: Some(PhysicalPlanType::Empty(+ protobuf::EmptyExecNode {+ produce_one_row: empty.produce_one_row(),+ schema: Some(schema),+ },+ )),})- } else if let Some(coalesce_batches) = plan.downcast_ref::<CoalesceBatchesExec>() {+ } else if let Some(coalesce_batches) = plan.downcast_ref::<CoalesceBatchesExec>()+ {let input: protobuf::PhysicalPlanNode =coalesce_batches.input().to_owned().try_into()?;Ok(protobuf::PhysicalPlanNode {@@ -208,29 +213,32 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {let delimiter = [*exec.delimiter().ok_or_else(|| {BallistaError::General("Delimeter is not set for CsvExec".to_owned())})?];- let delimiter = std::str::from_utf8(&delimiter)- .map_err(|_| BallistaError::General("Invalid CSV delimiter".to_owned()))?;+ let delimiter = std::str::from_utf8(&delimiter).map_err(|_| {+ BallistaError::General("Invalid CSV delimiter".to_owned())+ })?;Ok(protobuf::PhysicalPlanNode {- physical_plan_type: Some(PhysicalPlanType::CsvScan(protobuf::CsvScanExecNode {- path: exec.path().to_owned(),- filename: exec.filenames().to_vec(),- projection: exec- .projection()- .ok_or_else(|| {- BallistaError::General(- "projection in CsvExec dosn not exist.".to_owned(),- )- })?- .iter()- .map(|n| *n as u32)- .collect(),- file_extension: exec.file_extension().to_owned(),- schema: Some(exec.file_schema().as_ref().into()),- has_header: exec.has_header(),- delimiter: delimiter.to_string(),- batch_size: 32768,- })),+ physical_plan_type: Some(PhysicalPlanType::CsvScan(+ protobuf::CsvScanExecNode {+ path: exec.path().to_owned(),+ filename: exec.filenames().to_vec(),+ projection: exec+ .projection()+ .ok_or_else(|| {+ BallistaError::General(+ "projection in CsvExec dosn not exist.".to_owned(),+ )+ })?+ .iter()+ .map(|n| *n as u32)+ .collect(),+ file_extension: exec.file_extension().to_owned(),+ schema: Some(exec.file_schema().as_ref().into()),+ has_header: exec.has_header(),+ delimiter: delimiter.to_string(),+ batch_size: 32768,+ },+ )),})} else if let Some(exec) = plan.downcast_ref::<ParquetExec>() {let filenames = exec@@ -318,7 +326,9 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {nulls_first: expr.options.nulls_first,});Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::Sort(sort_expr)),+ expr_type: Some(protobuf::logical_expr_node::ExprType::Sort(+ sort_expr,+ )),})}).collect::<Result<Vec<_>, Self::Error>>()?;@@ -334,7 +344,11 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {Ok(protobuf::PhysicalPlanNode {physical_plan_type: Some(PhysicalPlanType::Unresolved(protobuf::UnresolvedShuffleExecNode {- query_stage_ids: exec.query_stage_ids.iter().map(|id| *id as u32).collect(),+ query_stage_ids: exec+ .query_stage_ids+ .iter()+ .map(|id| *id as u32)+ .collect(),schema: Some(exec.schema().as_ref().into()),partition_count: exec.partition_count as u32,},@@ -430,19 +444,19 @@ impl TryFrom<Arc<dyn PhysicalExpr>> for protobuf::LogicalExprNode {})} else if let Some(expr) = expr.downcast_ref::<NotExpr>() {Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::NotExpr(Box::new(- protobuf::Not {+ expr_type: Some(protobuf::logical_expr_node::ExprType::NotExpr(+ Box::new(protobuf::Not {expr: Some(Box::new(expr.arg().to_owned().try_into()?)),- },- ))),+ }),+ )),})} else if let Some(expr) = expr.downcast_ref::<IsNullExpr>() {Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::IsNullExpr(Box::new(- protobuf::IsNull {+ expr_type: Some(protobuf::logical_expr_node::ExprType::IsNullExpr(+ Box::new(protobuf::IsNull {expr: Some(Box::new(expr.arg().to_owned().try_into()?)),- },- ))),+ }),+ )),})} else if let Some(expr) = expr.downcast_ref::<IsNotNullExpr>() {Ok(protobuf::LogicalExprNode {@@ -454,25 +468,32 @@ impl TryFrom<Arc<dyn PhysicalExpr>> for protobuf::LogicalExprNode {})} else if let Some(expr) = expr.downcast_ref::<InListExpr>() {Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::InList(Box::new(- protobuf::InListNode {- expr: Some(Box::new(expr.expr().to_owned().try_into()?)),- list: expr- .list()- .iter()- .map(|a| a.clone().try_into())- .collect::<Result<Vec<protobuf::LogicalExprNode>, Self::Error>>()?,- negated: expr.negated(),- },- ))),+ expr_type: Some(+ protobuf::logical_expr_node::ExprType::InList(+ Box::new(+ protobuf::InListNode {+ expr: Some(Box::new(expr.expr().to_owned().try_into()?)),+ list: expr+ .list()+ .iter()+ .map(|a| a.clone().try_into())+ .collect::<Result<+ Vec<protobuf::LogicalExprNode>,+ Self::Error,+ >>()?,+ negated: expr.negated(),+ },+ ),+ ),+ ),})} else if let Some(expr) = expr.downcast_ref::<NegativeExpr>() {Ok(protobuf::LogicalExprNode {- expr_type: Some(protobuf::logical_expr_node::ExprType::Negative(Box::new(- protobuf::NegativeNode {+ expr_type: Some(protobuf::logical_expr_node::ExprType::Negative(+ Box::new(protobuf::NegativeNode {expr: Some(Box::new(expr.arg().to_owned().try_into()?)),- },- ))),+ }),+ )),})} else if let Some(lit) = expr.downcast_ref::<Literal>() {Ok(protobuf::LogicalExprNode {@@ -490,7 +511,8 @@ impl TryFrom<Arc<dyn PhysicalExpr>> for protobuf::LogicalExprNode {))),})} else if let Some(expr) = expr.downcast_ref::<ScalarFunctionExpr>() {- let fun: BuiltinScalarFunction = BuiltinScalarFunction::from_str(expr.name())?;+ let fun: BuiltinScalarFunction =+ BuiltinScalarFunction::from_str(expr.name())?;let fun: protobuf::ScalarFunction = (&fun).try_into()?;let expr: Vec<protobuf::LogicalExprNode> = expr.args()diff --git a/rust/ballista/rust/core/src/serde/scheduler/from_proto.rs b/rust/ballista/rust/core/src/serde/scheduler/from_proto.rsindex 0ba7abd2bd..fb1e4f812d 100644--- a/rust/ballista/rust/core/src/serde/scheduler/from_proto.rs+++ b/rust/ballista/rust/core/src/serde/scheduler/from_proto.rs@@ -42,7 +42,8 @@ impl TryInto<Action> for protobuf::Action {.as_ref().ok_or_else(|| {BallistaError::General(- "PhysicalPlanNode in ExecutePartition is missing".to_owned(),+ "PhysicalPlanNode in ExecutePartition is missing"+ .to_owned(),)})?.try_into()?,diff --git a/rust/ballista/rust/core/src/serde/scheduler/mod.rs b/rust/ballista/rust/core/src/serde/scheduler/mod.rsindex 40c200f151..efee82dbdf 100644--- a/rust/ballista/rust/core/src/serde/scheduler/mod.rs+++ b/rust/ballista/rust/core/src/serde/scheduler/mod.rs@@ -113,7 +113,11 @@ impl Default for PartitionStats {}impl PartitionStats {- pub fn new(num_rows: Option<u64>, num_batches: Option<u64>, num_bytes: Option<u64>) -> Self {+ pub fn new(+ num_rows: Option<u64>,+ num_batches: Option<u64>,+ num_bytes: Option<u64>,+ ) -> Self {Self {num_rows,num_batches,@@ -160,7 +164,8 @@ impl PartitionStats {}field_builders.push(Box::new(num_bytes_builder) as Box<dyn ArrayBuilder>);- let mut struct_builder = StructBuilder::new(self.arrow_struct_fields(), field_builders);+ let mut struct_builder =+ StructBuilder::new(self.arrow_struct_fields(), field_builders);struct_builder.append(true)?;Ok(Arc::new(struct_builder.finish()))}diff --git a/rust/ballista/rust/core/src/utils.rs b/rust/ballista/rust/core/src/utils.rsindex 9814901bd2..d1c239a585 100644--- a/rust/ballista/rust/core/src/utils.rs+++ b/rust/ballista/rust/core/src/utils.rs@@ -44,7 +44,9 @@ use datafusion::physical_plan::merge::MergeExec;use datafusion::physical_plan::parquet::ParquetExec;use datafusion::physical_plan::projection::ProjectionExec;use datafusion::physical_plan::sort::SortExec;-use datafusion::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, RecordBatchStream};+use datafusion::physical_plan::{+ AggregateExpr, ExecutionPlan, PhysicalExpr, RecordBatchStream,+};use futures::StreamExt;/// Stream data to disk in Arrow IPC format@@ -97,60 +99,61 @@ pub async fn collect_stream(}pub fn format_plan(plan: &dyn ExecutionPlan, indent: usize) -> Result<String> {- let operator_str = if let Some(exec) = plan.as_any().downcast_ref::<HashAggregateExec>() {- format!(- "HashAggregateExec: groupBy={:?}, aggrExpr={:?}",- exec.group_expr()- .iter()- .map(|e| format_expr(e.0.as_ref()))- .collect::<Vec<String>>(),- exec.aggr_expr()- .iter()- .map(|e| format_agg_expr(e.as_ref()))- .collect::<Result<Vec<String>>>()?- )- } else if let Some(exec) = plan.as_any().downcast_ref::<HashJoinExec>() {- format!(- "HashJoinExec: joinType={:?}, on={:?}",- exec.join_type(),- exec.on()- )- } else if let Some(exec) = plan.as_any().downcast_ref::<ParquetExec>() {- let mut num_files = 0;- for part in exec.partitions() {- num_files += part.filenames().len();- }- format!(- "ParquetExec: partitions={}, files={}",- exec.partitions().len(),- num_files- )- } else if let Some(exec) = plan.as_any().downcast_ref::<CsvExec>() {- format!(- "CsvExec: {}; partitions={}",- &exec.path(),- exec.output_partitioning().partition_count()- )- } else if let Some(exec) = plan.as_any().downcast_ref::<FilterExec>() {- format!("FilterExec: {}", format_expr(exec.predicate().as_ref()))- } else if let Some(exec) = plan.as_any().downcast_ref::<QueryStageExec>() {- format!(- "QueryStageExec: job={}, stage={}",- exec.job_id, exec.stage_id- )- } else if let Some(exec) = plan.as_any().downcast_ref::<UnresolvedShuffleExec>() {- format!("UnresolvedShuffleExec: stages={:?}", exec.query_stage_ids)- } else if let Some(exec) = plan.as_any().downcast_ref::<CoalesceBatchesExec>() {- format!(- "CoalesceBatchesExec: batchSize={}",- exec.target_batch_size()- )- } else if plan.as_any().downcast_ref::<MergeExec>().is_some() {- "MergeExec".to_string()- } else {- let str = format!("{:?}", plan);- String::from(&str[0..120])- };+ let operator_str =+ if let Some(exec) = plan.as_any().downcast_ref::<HashAggregateExec>() {+ format!(+ "HashAggregateExec: groupBy={:?}, aggrExpr={:?}",+ exec.group_expr()+ .iter()+ .map(|e| format_expr(e.0.as_ref()))+ .collect::<Vec<String>>(),+ exec.aggr_expr()+ .iter()+ .map(|e| format_agg_expr(e.as_ref()))+ .collect::<Result<Vec<String>>>()?+ )+ } else if let Some(exec) = plan.as_any().downcast_ref::<HashJoinExec>() {+ format!(+ "HashJoinExec: joinType={:?}, on={:?}",+ exec.join_type(),+ exec.on()+ )+ } else if let Some(exec) = plan.as_any().downcast_ref::<ParquetExec>() {+ let mut num_files = 0;+ for part in exec.partitions() {+ num_files += part.filenames().len();+ }+ format!(+ "ParquetExec: partitions={}, files={}",+ exec.partitions().len(),+ num_files+ )+ } else if let Some(exec) = plan.as_any().downcast_ref::<CsvExec>() {+ format!(+ "CsvExec: {}; partitions={}",+ &exec.path(),+ exec.output_partitioning().partition_count()+ )+ } else if let Some(exec) = plan.as_any().downcast_ref::<FilterExec>() {+ format!("FilterExec: {}", format_expr(exec.predicate().as_ref()))+ } else if let Some(exec) = plan.as_any().downcast_ref::<QueryStageExec>() {+ format!(+ "QueryStageExec: job={}, stage={}",+ exec.job_id, exec.stage_id+ )+ } else if let Some(exec) = plan.as_any().downcast_ref::<UnresolvedShuffleExec>() {+ format!("UnresolvedShuffleExec: stages={:?}", exec.query_stage_ids)+ } else if let Some(exec) = plan.as_any().downcast_ref::<CoalesceBatchesExec>() {+ format!(+ "CoalesceBatchesExec: batchSize={}",+ exec.target_batch_size()+ )+ } else if plan.as_any().downcast_ref::<MergeExec>().is_some() {+ "MergeExec".to_string()+ } else {+ let str = format!("{:?}", plan);+ String::from(&str[0..120])+ };let children_str = plan.children()@@ -200,14 +203,26 @@ pub fn produce_diagram(filename: &str, stages: &[Arc<QueryStageExec>]) -> Resultwriteln!(w, "\tsubgraph cluster{} {{", stage.stage_id)?;writeln!(w, "\t\tlabel = \"Stage {}\";", stage.stage_id)?;let mut id = AtomicUsize::new(0);- build_exec_plan_diagram(&mut w, stage.child.as_ref(), stage.stage_id, &mut id, true)?;+ build_exec_plan_diagram(+ &mut w,+ stage.child.as_ref(),+ stage.stage_id,+ &mut id,+ true,+ )?;writeln!(w, "\t}}")?;}// draw relationshipsfor stage in stages {let mut id = AtomicUsize::new(0);- build_exec_plan_diagram(&mut w, stage.child.as_ref(), stage.stage_id, &mut id, false)?;+ build_exec_plan_diagram(+ &mut w,+ stage.child.as_ref(),+ stage.stage_id,+ &mut id,+ false,+ )?;}write!(w, "}}")?;@@ -279,7 +294,8 @@ fn build_exec_plan_diagram(}} else {// relationships within same entity- let child_id = build_exec_plan_diagram(w, child.as_ref(), stage_id, id, draw_entity)?;+ let child_id =+ build_exec_plan_diagram(w, child.as_ref(), stage_id, id, draw_entity)?;if draw_entity {writeln!(w,diff --git a/rust/ballista/rust/executor/src/collect.rs b/rust/ballista/rust/executor/src/collect.rsindex 0c65d9394c..a2f9d4c636 100644--- a/rust/ballista/rust/executor/src/collect.rs+++ b/rust/ballista/rust/executor/src/collect.rs@@ -112,7 +112,10 @@ struct MergedRecordBatchStream {impl Stream for MergedRecordBatchStream {type Item = ArrowResult<RecordBatch>;- fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {+ fn poll_next(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Self::Item>> {self.select_all.as_mut().poll_next(cx)}}diff --git a/rust/ballista/rust/executor/src/execution_loop.rs b/rust/ballista/rust/executor/src/execution_loop.rsindex 5be236f82e..cf641ddcc5 100644--- a/rust/ballista/rust/executor/src/execution_loop.rs+++ b/rust/ballista/rust/executor/src/execution_loop.rs@@ -28,8 +28,8 @@ use ballista_core::serde::scheduler::ExecutorMeta;use ballista_core::{client::BallistaClient,serde::protobuf::{- self, scheduler_grpc_client::SchedulerGrpcClient, task_status, FailedTask, PartitionId,- PollWorkParams, PollWorkResult, TaskDefinition, TaskStatus,+ self, scheduler_grpc_client::SchedulerGrpcClient, task_status, FailedTask,+ PartitionId, PollWorkParams, PollWorkResult, TaskDefinition, TaskStatus,},};use protobuf::CompletedTask;@@ -42,21 +42,25 @@ pub async fn poll_loop() {let executor_meta: protobuf::ExecutorMetadata = executor_meta.into();let available_tasks_slots = Arc::new(AtomicUsize::new(concurrent_tasks));- let (task_status_sender, mut task_status_receiver) = std::sync::mpsc::channel::<TaskStatus>();+ let (task_status_sender, mut task_status_receiver) =+ std::sync::mpsc::channel::<TaskStatus>();loop {debug!("Starting registration loop with scheduler");- let task_status: Vec<TaskStatus> = sample_tasks_status(&mut task_status_receiver).await;-- let poll_work_result: anyhow::Result<tonic::Response<PollWorkResult>, tonic::Status> =- scheduler- .poll_work(PollWorkParams {- metadata: Some(executor_meta.clone()),- can_accept_task: available_tasks_slots.load(Ordering::SeqCst) > 0,- task_status,- })- .await;+ let task_status: Vec<TaskStatus> =+ sample_tasks_status(&mut task_status_receiver).await;++ let poll_work_result: anyhow::Result<+ tonic::Response<PollWorkResult>,+ tonic::Status,+ > = scheduler+ .poll_work(PollWorkParams {+ metadata: Some(executor_meta.clone()),+ can_accept_task: available_tasks_slots.load(Ordering::SeqCst) > 0,+ task_status,+ })+ .await;let task_status_sender = task_status_sender.clone();@@ -145,7 +149,9 @@ fn as_task_status(}}-async fn sample_tasks_status(task_status_receiver: &mut Receiver<TaskStatus>) -> Vec<TaskStatus> {+async fn sample_tasks_status(+ task_status_receiver: &mut Receiver<TaskStatus>,+) -> Vec<TaskStatus> {let mut task_status: Vec<TaskStatus> = vec![];loop {diff --git a/rust/ballista/rust/executor/src/flight_service.rs b/rust/ballista/rust/executor/src/flight_service.rsindex f29bce654c..8fff3dbcad 100644--- a/rust/ballista/rust/executor/src/flight_service.rs+++ b/rust/ballista/rust/executor/src/flight_service.rs@@ -36,9 +36,9 @@ use arrow::ipc::reader::FileReader;use arrow::ipc::writer::IpcWriteOptions;use arrow::record_batch::RecordBatch;use arrow_flight::{- flight_service_server::FlightService, Action, ActionType, Criteria, Empty, FlightData,- FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse, PutResult, SchemaResult,- Ticket,+ flight_service_server::FlightService, Action, ActionType, Criteria, Empty,+ FlightData, FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse,+ PutResult, SchemaResult, Ticket,};use datafusion::error::DataFusionError;use futures::{Stream, StreamExt};@@ -68,7 +68,8 @@ impl BallistaFlightService {}}-type BoxedFlightStream<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send + Sync + 'static>>;+type BoxedFlightStream<T> =+ Pin<Box<dyn Stream<Item = Result<T, Status>> + Send + Sync + 'static>>;#[tonic::async_trait]impl FlightService for BallistaFlightService {@@ -87,7 +88,8 @@ impl FlightService for BallistaFlightService {let ticket = request.into_inner();info!("Received do_get request");- let action = decode_protobuf(&ticket.ticket).map_err(|e| from_ballista_err(&e))?;+ let action =+ decode_protobuf(&ticket.ticket).map_err(|e| from_ballista_err(&e))?;match &action {BallistaAction::ExecutePartition(partition) => {@@ -96,7 +98,8 @@ impl FlightService for BallistaFlightService {partition.job_id,partition.stage_id,partition.partition_id,- format_plan(partition.plan.as_ref(), 0).map_err(|e| from_ballista_err(&e))?+ format_plan(partition.plan.as_ref(), 0)+ .map_err(|e| from_ballista_err(&e))?);let mut tasks: Vec<JoinHandle<Result<_, BallistaError>>> = vec![];@@ -149,8 +152,11 @@ impl FlightService for BallistaFlightService {let path: ArrayRef = Arc::new(c0.finish());let stats: ArrayRef = stats.to_arrow_arrayref()?;- let results =- vec![RecordBatch::try_new(schema, vec![path, stats]).unwrap()];+ let results = vec![RecordBatch::try_new(+ schema,+ vec![path, stats],+ )+ .unwrap()];let mut batches: Vec<Result<FlightData, Status>> = results.iter()@@ -178,15 +184,20 @@ impl FlightService for BallistaFlightService {stats.arrow_struct_repr(),]));let schema_flight_data =- arrow_flight::utils::flight_data_from_arrow_schema(schema.as_ref(), &options);+ arrow_flight::utils::flight_data_from_arrow_schema(+ schema.as_ref(),+ &options,+ );flights.push(Ok(schema_flight_data));// collect statistics from each executed partitionfor result in results {- let result =- result.map_err(|e| Status::internal(format!("Ballista Error: {:?}", e)))?;- let batches =- result.map_err(|e| Status::internal(format!("Ballista Error: {:?}", e)))?;+ let result = result.map_err(|e| {+ Status::internal(format!("Ballista Error: {:?}", e))+ })?;+ let batches = result.map_err(|e| {+ Status::internal(format!("Ballista Error: {:?}", e))+ })?;flights.extend_from_slice(&batches);}@@ -279,7 +290,8 @@ impl FlightService for BallistaFlightService {) -> Result<Response<Self::DoActionStream>, Status> {let action = request.into_inner();- let _action = decode_protobuf(&action.body.to_vec()).map_err(|e| from_ballista_err(&e))?;+ let _action =+ decode_protobuf(&action.body.to_vec()).map_err(|e| from_ballista_err(&e))?;Err(Status::unimplemented("do_action"))}@@ -315,13 +327,18 @@ fn create_flight_iter()}-async fn stream_flight_data<T>(reader: FileReader<T>, tx: FlightDataSender) -> Result<(), Status>+async fn stream_flight_data<T>(+ reader: FileReader<T>,+ tx: FlightDataSender,+) -> Result<(), Status>whereT: Read + Seek,{let options = arrow::ipc::writer::IpcWriteOptions::default();- let schema_flight_data =- arrow_flight::utils::flight_data_from_arrow_schema(reader.schema().as_ref(), &options);+ let schema_flight_data = arrow_flight::utils::flight_data_from_arrow_schema(+ reader.schema().as_ref(),+ &options,+ );send_response(&tx, Ok(schema_flight_data)).await?;for batch in reader {diff --git a/rust/ballista/rust/executor/src/main.rs b/rust/ballista/rust/executor/src/main.rsindex 7e7877a0ce..2718ea3542 100644--- a/rust/ballista/rust/executor/src/main.rs+++ b/rust/ballista/rust/executor/src/main.rs@@ -34,7 +34,9 @@ use ballista_core::{print_version, serde::protobuf::scheduler_grpc_server::SchedulerGrpcServer,serde::scheduler::ExecutorMeta, BALLISTA_VERSION,};-use ballista_executor::{flight_service::BallistaFlightService, BallistaExecutor, ExecutorConfig};+use ballista_executor::{+ flight_service::BallistaFlightService, BallistaExecutor, ExecutorConfig,+};use ballista_scheduler::{state::StandaloneClient, SchedulerServer};use config::prelude::*;@@ -60,7 +62,8 @@ async fn main() -> Result<()> {// parse command-line argumentslet (opt, _remaining_args) =- Config::including_optional_config_files(&["/etc/ballista/executor.toml"]).unwrap_or_exit();+ Config::including_optional_config_files(&["/etc/ballista/executor.toml"])+ .unwrap_or_exit();if opt.version {print_version();@@ -92,7 +95,8 @@ async fn main() -> Result<()> {.into_string().unwrap(),);- let config = ExecutorConfig::new(&external_host, port, &work_dir, opt.concurrent_tasks);+ let config =+ ExecutorConfig::new(&external_host, port, &work_dir, opt.concurrent_tasks);info!("Running with config: {:?}", config);let executor_meta = ExecutorMeta {@@ -105,7 +109,8 @@ async fn main() -> Result<()> {info!("Running in local mode. Scheduler will be run in-proc");let client = StandaloneClient::try_new_temporary().context("Could not create standalone config backend")?;- let server = SchedulerGrpcServer::new(SchedulerServer::new(Arc::new(client), namespace));+ let server =+ SchedulerGrpcServer::new(SchedulerServer::new(Arc::new(client), namespace));let addr = format!("{}:{}", bind_host, scheduler_port);let addr = addr.parse()@@ -114,7 +119,8 @@ async fn main() -> Result<()> {"Ballista v{} Rust Scheduler listening on {:?}",BALLISTA_VERSION, addr);- let scheduler_future = tokio::spawn(Server::builder().add_service(server).serve(addr));+ let scheduler_future =+ tokio::spawn(Server::builder().add_service(server).serve(addr));let mut scheduler_result = futures::future::maybe_done(scheduler_future);// Ensure scheduler is ready to receive connections@@ -133,7 +139,9 @@ async fn main() -> Result<()> {"Scheduler unexpectedly finished successfully"))}- MaybeDone::Gone => panic!("Received Gone from recently created MaybeDone"),+ MaybeDone::Gone => {+ panic!("Received Gone from recently created MaybeDone")+ }};tokio::time::sleep(std::time::Duration::from_millis(100)).await;scheduler_result = futures::future::maybe_done(scheduler_future);diff --git a/rust/ballista/rust/scheduler/src/lib.rs b/rust/ballista/rust/scheduler/src/lib.rsindex 39c56b680d..8ad2cc7a44 100644--- a/rust/ballista/rust/scheduler/src/lib.rs+++ b/rust/ballista/rust/scheduler/src/lib.rs@@ -30,8 +30,9 @@ use ballista_core::serde::protobuf::{execute_query_params::Query, job_status, scheduler_grpc_server::SchedulerGrpc,ExecuteQueryParams, ExecuteQueryResult, FailedJob, FilePartitionMetadata, FileType,GetExecutorMetadataParams, GetExecutorMetadataResult, GetFileMetadataParams,- GetFileMetadataResult, GetJobStatusParams, GetJobStatusResult, JobStatus, PartitionId,- PollWorkParams, PollWorkResult, QueuedJob, RunningJob, TaskDefinition, TaskStatus,+ GetFileMetadataResult, GetJobStatusParams, GetJobStatusResult, JobStatus,+ PartitionId, PollWorkParams, PollWorkResult, QueuedJob, RunningJob, TaskDefinition,+ TaskStatus,};use ballista_core::serde::scheduler::ExecutorMeta;@@ -198,8 +199,8 @@ impl SchedulerGrpc for SchedulerServer {match file_type {FileType::Parquet => {- let parquet_exec =- ParquetExec::try_from_path(&path, None, None, 1024, 1).map_err(|e| {+ let parquet_exec = ParquetExec::try_from_path(&path, None, None, 1024, 1)+ .map_err(|e| {let msg = format!("Error opening parquet files: {}", e);error!("{}", msg);tonic::Status::internal(msg)@@ -301,9 +302,11 @@ impl SchedulerGrpc for SchedulerServer {&namespace,&job_id_spawn,&JobStatus {- status: Some(job_status::Status::Failed(FailedJob {- error: format!("{}", error),- })),+ status: Some(job_status::Status::Failed(+ FailedJob {+ error: format!("{}", error),+ },+ )),},).await@@ -313,15 +316,17 @@ impl SchedulerGrpc for SchedulerServer {Ok(value) => value,}}};- };+ }let start = Instant::now();- let optimized_plan = fail_job!(datafusion_ctx.optimize(&plan).map_err(|e| {- let msg = format!("Could not create optimized logical plan: {}", e);- error!("{}", msg);- tonic::Status::internal(msg)- }));+ let optimized_plan =+ fail_job!(datafusion_ctx.optimize(&plan).map_err(|e| {+ let msg =+ format!("Could not create optimized logical plan: {}", e);+ error!("{}", msg);+ tonic::Status::internal(msg)+ }));debug!("Calculated optimized plan: {:?}", optimized_plan);@@ -354,13 +359,15 @@ impl SchedulerGrpc for SchedulerServer {job_id_spawn, e);}- let mut planner = fail_job!(DistributedPlanner::try_new(executors).map_err(|e| {- let msg = format!("Could not create distributed planner: {}", e);- error!("{}", msg);- tonic::Status::internal(msg)- }));- let stages =- fail_job!(planner.plan_query_stages(&job_id_spawn, plan).map_err(|e| {+ let mut planner = fail_job!(DistributedPlanner::try_new(executors)+ .map_err(|e| {+ let msg = format!("Could not create distributed planner: {}", e);+ error!("{}", msg);+ tonic::Status::internal(msg)+ }));+ let stages = fail_job!(planner+ .plan_query_stages(&job_id_spawn, plan)+ .map_err(|e| {let msg = format!("Could not plan query stages: {}", e);error!("{}", msg);tonic::Status::internal(msg)diff --git a/rust/ballista/rust/scheduler/src/main.rs b/rust/ballista/rust/scheduler/src/main.rsindex 2a569bee51..785ffb47b1 100644--- a/rust/ballista/rust/scheduler/src/main.rs+++ b/rust/ballista/rust/scheduler/src/main.rs@@ -21,7 +21,9 @@ use std::{net::SocketAddr, sync::Arc};use anyhow::{Context, Result};use ballista_core::BALLISTA_VERSION;-use ballista_core::{print_version, serde::protobuf::scheduler_grpc_server::SchedulerGrpcServer};+use ballista_core::{+ print_version, serde::protobuf::scheduler_grpc_server::SchedulerGrpcServer,+};#[cfg(feature = "etcd")]use ballista_scheduler::state::EtcdClient;#[cfg(feature = "sled")]@@ -54,7 +56,8 @@ async fn start_server("Ballista v{} Scheduler listening on {:?}",BALLISTA_VERSION, addr);- let server = SchedulerGrpcServer::new(SchedulerServer::new(config_backend, namespace));+ let server =+ SchedulerGrpcServer::new(SchedulerServer::new(config_backend, namespace));Ok(Server::builder().add_service(server).serve(addr)@@ -68,7 +71,8 @@ async fn main() -> Result<()> {// parse optionslet (opt, _remaining_args) =- Config::including_optional_config_files(&["/etc/ballista/scheduler.toml"]).unwrap_or_exit();+ Config::including_optional_config_files(&["/etc/ballista/scheduler.toml"])+ .unwrap_or_exit();if opt.version {print_version();diff --git a/rust/ballista/rust/scheduler/src/planner.rs b/rust/ballista/rust/scheduler/src/planner.rsindex 414b521c49..f06dcfdfce 100644--- a/rust/ballista/rust/scheduler/src/planner.rs+++ b/rust/ballista/rust/scheduler/src/planner.rs@@ -42,7 +42,8 @@ use datafusion::physical_plan::ExecutionPlan;use log::{debug, info};use tokio::task::JoinHandle;-type SendableExecutionPlan = Pin<Box<dyn Future<Output = Result<Arc<dyn ExecutionPlan>>> + Send>>;+type SendableExecutionPlan =+ Pin<Box<dyn Future<Output = Result<Arc<dyn ExecutionPlan>>> + Send>>;type PartialQueryStageResult = (Arc<dyn ExecutionPlan>, Vec<Arc<QueryStageExec>>);pub struct DistributedPlanner {@@ -102,7 +103,8 @@ impl DistributedPlanner {execution_plan: Arc<dyn ExecutionPlan>,) -> Result<Vec<Arc<QueryStageExec>>> {info!("planning query stages");- let (new_plan, mut stages) = self.plan_query_stages_internal(job_id, execution_plan)?;+ let (new_plan, mut stages) =+ self.plan_query_stages_internal(job_id, execution_plan)?;stages.push(create_query_stage(job_id.to_string(),self.next_stage_id(),@@ -149,7 +151,9 @@ impl DistributedPlanner {));stages.push(query_stage);Ok((merge.with_new_children(vec![unresolved_shuffle])?, stages))- } else if let Some(agg) = execution_plan.as_any().downcast_ref::<HashAggregateExec>() {+ } else if let Some(agg) =+ execution_plan.as_any().downcast_ref::<HashAggregateExec>()+ {//TODO should insert query stages in more generic way based on partitioning metadata// and not specifically for this operatormatch agg.mode() {@@ -172,7 +176,8 @@ impl DistributedPlanner {}AggregateMode::Partial => Ok((agg.with_new_children(children)?, stages)),}- } else if let Some(join) = execution_plan.as_any().downcast_ref::<HashJoinExec>() {+ } else if let Some(join) = execution_plan.as_any().downcast_ref::<HashJoinExec>()+ {Ok((join.with_new_children(children)?, stages))} else {// TODO check for compatible partitioning schema, not just count@@ -212,7 +217,8 @@ fn execute(executors: Vec<ExecutorMeta>,) -> SendableExecutionPlan {Box::pin(async move {- let mut partition_locations: HashMap<usize, Vec<PartitionLocation>> = HashMap::new();+ let mut partition_locations: HashMap<usize, Vec<PartitionLocation>> =+ HashMap::new();let mut result_partition_locations = vec![];for stage in &stages {debug!("execute() {}", &format!("{:?}", stage)[0..60]);@@ -225,13 +231,15 @@ fn execute(executors.clone(),).await?;- partition_locations.insert(stage.stage_id, result_partition_locations.clone());+ partition_locations+ .insert(stage.stage_id, result_partition_locations.clone());}- let shuffle_reader: Arc<dyn ExecutionPlan> = Arc::new(ShuffleReaderExec::try_new(- result_partition_locations,- stages.last().unwrap().schema(),- )?);+ let shuffle_reader: Arc<dyn ExecutionPlan> =+ Arc::new(ShuffleReaderExec::try_new(+ result_partition_locations,+ stages.last().unwrap().schema(),+ )?);Ok(shuffle_reader)})}@@ -242,7 +250,9 @@ pub fn remove_unresolved_shuffles() -> Result<Arc<dyn ExecutionPlan>> {let mut new_children: Vec<Arc<dyn ExecutionPlan>> = vec![];for child in stage.children() {- if let Some(unresolved_shuffle) = child.as_any().downcast_ref::<UnresolvedShuffleExec>() {+ if let Some(unresolved_shuffle) =+ child.as_any().downcast_ref::<UnresolvedShuffleExec>()+ {let mut relevant_locations = vec![];for id in &unresolved_shuffle.query_stage_ids {relevant_locations.append(@@ -439,14 +449,16 @@ mod test {let final_hash = downcast_exec!(final_hash, HashAggregateExec);let unresolved_shuffle = final_hash.children()[0].clone();- let unresolved_shuffle = downcast_exec!(unresolved_shuffle, UnresolvedShuffleExec);+ let unresolved_shuffle =+ downcast_exec!(unresolved_shuffle, UnresolvedShuffleExec);assert_eq!(unresolved_shuffle.query_stage_ids, vec![2]);let merge_exec = stages[1].children()[0].clone();let merge_exec = downcast_exec!(merge_exec, MergeExec);let unresolved_shuffle = merge_exec.children()[0].clone();- let unresolved_shuffle = downcast_exec!(unresolved_shuffle, UnresolvedShuffleExec);+ let unresolved_shuffle =+ downcast_exec!(unresolved_shuffle, UnresolvedShuffleExec);assert_eq!(unresolved_shuffle.query_stage_ids, vec![1]);let partial_hash = stages[0].children()[0].clone();diff --git a/rust/ballista/rust/scheduler/src/state/etcd.rs b/rust/ballista/rust/scheduler/src/state/etcd.rsindex 1aaf543e38..ced24613eb 100644--- a/rust/ballista/rust/scheduler/src/state/etcd.rs+++ b/rust/ballista/rust/scheduler/src/state/etcd.rs@@ -67,7 +67,12 @@ impl ConfigBackendClient for EtcdClient {.collect())}- async fn put(&self, key: String, value: Vec<u8>, lease_time: Option<Duration>) -> Result<()> {+ async fn put(+ &self,+ key: String,+ value: Vec<u8>,+ lease_time: Option<Duration>,+ ) -> Result<()> {let mut etcd = self.etcd.clone();let put_options = if let Some(lease_time) = lease_time {etcd.lease_grant(lease_time.as_secs() as i64, None)diff --git a/rust/ballista/rust/scheduler/src/state/mod.rs b/rust/ballista/rust/scheduler/src/state/mod.rsindex bcefc707c0..614da05c0a 100644--- a/rust/ballista/rust/scheduler/src/state/mod.rs+++ b/rust/ballista/rust/scheduler/src/state/mod.rs@@ -15,7 +15,9 @@// specific language governing permissions and limitations// under the License.-use std::{any::type_name, collections::HashMap, convert::TryInto, sync::Arc, time::Duration};+use std::{+ any::type_name, collections::HashMap, convert::TryInto, sync::Arc, time::Duration,+};use datafusion::physical_plan::ExecutionPlan;use log::{debug, info};@@ -23,13 +25,14 @@ use prost::Message;use tokio::sync::OwnedMutexGuard;use ballista_core::serde::protobuf::{- job_status, task_status, CompletedJob, CompletedTask, ExecutorMetadata, FailedJob, FailedTask,- JobStatus, PhysicalPlanNode, RunningJob, RunningTask, TaskStatus,+ job_status, task_status, CompletedJob, CompletedTask, ExecutorMetadata, FailedJob,+ FailedTask, JobStatus, PhysicalPlanNode, RunningJob, RunningTask, TaskStatus,};use ballista_core::serde::scheduler::PartitionStats;use ballista_core::{error::BallistaError, serde::scheduler::ExecutorMeta};use ballista_core::{- error::Result, execution_plans::UnresolvedShuffleExec, serde::protobuf::PartitionLocation,+ error::Result, execution_plans::UnresolvedShuffleExec,+ serde::protobuf::PartitionLocation,};use super::planner::remove_unresolved_shuffles;@@ -58,7 +61,12 @@ pub trait ConfigBackendClient: Send + Sync {async fn get_from_prefix(&self, prefix: &str) -> Result<Vec<(String, Vec<u8>)>>;/// Saves the value into the provided key, overriding any previous data that might have been associated to that key.- async fn put(&self, key: String, value: Vec<u8>, lease_time: Option<Duration>) -> Result<()>;+ async fn put(+ &self,+ key: String,+ value: Vec<u8>,+ lease_time: Option<Duration>,+ ) -> Result<()>;async fn lock(&self) -> Result<Box<dyn Lock>>;}@@ -73,7 +81,10 @@ impl SchedulerState {Self { config_client }}- pub async fn get_executors_metadata(&self, namespace: &str) -> Result<Vec<ExecutorMeta>> {+ pub async fn get_executors_metadata(+ &self,+ namespace: &str,+ ) -> Result<Vec<ExecutorMeta>> {let mut result = vec![];let entries = self@@ -87,7 +98,11 @@ impl SchedulerState {Ok(result)}- pub async fn save_executor_metadata(&self, namespace: &str, meta: ExecutorMeta) -> Result<()> {+ pub async fn save_executor_metadata(+ &self,+ namespace: &str,+ meta: ExecutorMeta,+ ) -> Result<()> {let key = get_executor_key(namespace, &meta.id);let meta: ExecutorMetadata = meta.into();let value: Vec<u8> = encode_protobuf(&meta)?;@@ -106,7 +121,11 @@ impl SchedulerState {self.config_client.put(key, value, None).await}- pub async fn get_job_metadata(&self, namespace: &str, job_id: &str) -> Result<JobStatus> {+ pub async fn get_job_metadata(+ &self,+ namespace: &str,+ job_id: &str,+ ) -> Result<JobStatus> {let key = get_job_key(namespace, job_id);let value = &self.config_client.get(&key).await?;if value.is_empty() {@@ -119,7 +138,11 @@ impl SchedulerState {Ok(value)}- pub async fn save_task_status(&self, namespace: &str, status: &TaskStatus) -> Result<()> {+ pub async fn save_task_status(+ &self,+ namespace: &str,+ status: &TaskStatus,+ ) -> Result<()> {let partition_id = status.partition_id.as_ref().unwrap();let key = get_task_status_key(namespace,@@ -201,7 +224,11 @@ impl SchedulerState {if status.status.is_none() {let partition = status.partition_id.as_ref().unwrap();let plan = self- .get_stage_plan(namespace, &partition.job_id, partition.stage_id as usize)+ .get_stage_plan(+ namespace,+ &partition.job_id,+ partition.stage_id as usize,+ ).await?;// Let's try to resolve any unresolved shuffles we find@@ -221,7 +248,8 @@ impl SchedulerState {partition_id,)).unwrap();- let referenced_task: TaskStatus = decode_protobuf(referenced_task)?;+ let referenced_task: TaskStatus =+ decode_protobuf(referenced_task)?;if let Some(task_status::Status::Completed(CompletedTask {executor_id,})) = referenced_task.status@@ -251,7 +279,8 @@ impl SchedulerState {}}}- let plan = remove_unresolved_shuffles(plan.as_ref(), &partition_locations)?;+ let plan =+ remove_unresolved_shuffles(plan.as_ref(), &partition_locations)?;// If we get here, there are no more unresolved shuffled and the task can be runstatus.status = Some(task_status::Status::Running(RunningTask {@@ -335,7 +364,9 @@ impl SchedulerState {.into_iter().map(|(status, execution_id)| PartitionLocation {partition_id: status.partition_id.to_owned(),- executor_meta: executors.get(execution_id).map(|e| e.clone().into()),+ executor_meta: executors+ .get(execution_id)+ .map(|e| e.clone().into()),partition_stats: None,}).collect();@@ -347,7 +378,8 @@ impl SchedulerState {for status in statuses {match status.status {Some(task_status::Status::Failed(FailedTask { error })) => {- job_status = Some(job_status::Status::Failed(FailedJob { error }));+ job_status =+ Some(job_status::Status::Failed(FailedJob { error }));break;}Some(task_status::Status::Running(_)) if job_status == None => {@@ -374,8 +406,12 @@ impl<T: Send + Sync> Lock for OwnedMutexGuard<T> {}/// Returns the the unresolved shuffles in the execution plan-fn find_unresolved_shuffles(plan: &Arc<dyn ExecutionPlan>) -> Result<Vec<UnresolvedShuffleExec>> {- if let Some(unresolved_shuffle) = plan.as_any().downcast_ref::<UnresolvedShuffleExec>() {+fn find_unresolved_shuffles(+ plan: &Arc<dyn ExecutionPlan>,+) -> Result<Vec<UnresolvedShuffleExec>> {+ if let Some(unresolved_shuffle) =+ plan.as_any().downcast_ref::<UnresolvedShuffleExec>()+ {Ok(vec![unresolved_shuffle.clone()])} else {Ok(plan@@ -402,10 +438,9 @@ fn get_job_prefix(namespace: &str) -> String {}fn extract_job_id_from_key(job_key: &str) -> Result<&str> {- job_key- .split('/')- .nth(4)- .ok_or_else(|| BallistaError::Internal(format!("Unexpected job key: {}", job_key)))+ job_key.split('/').nth(4).ok_or_else(|| {+ BallistaError::Internal(format!("Unexpected job key: {}", job_key))+ })}fn get_job_key(namespace: &str, id: &str) -> String {@@ -440,14 +475,22 @@ fn get_stage_plan_key(namespace: &str, job_id: &str, stage_id: usize) -> Stringfn decode_protobuf<T: Message + Default>(bytes: &[u8]) -> Result<T> {T::decode(bytes).map_err(|e| {- BallistaError::Internal(format!("Could not deserialize {}: {}", type_name::<T>(), e))+ BallistaError::Internal(format!(+ "Could not deserialize {}: {}",+ type_name::<T>(),+ e+ ))})}fn encode_protobuf<T: Message + Default>(msg: &T) -> Result<Vec<u8>> {let mut value: Vec<u8> = Vec::with_capacity(msg.encoded_len());msg.encode(&mut value).map_err(|e| {- BallistaError::Internal(format!("Could not serialize {}: {}", type_name::<T>(), e))+ BallistaError::Internal(format!(+ "Could not serialize {}: {}",+ type_name::<T>(),+ e+ ))})?;Ok(value)}@@ -457,8 +500,8 @@ mod test {use std::sync::Arc;use ballista_core::serde::protobuf::{- job_status, task_status, CompletedTask, FailedTask, JobStatus, PartitionId, QueuedJob,- RunningJob, RunningTask, TaskStatus,+ job_status, task_status, CompletedTask, FailedTask, JobStatus, PartitionId,+ QueuedJob, RunningJob, RunningTask, TaskStatus,};use ballista_core::{error::BallistaError, serde::scheduler::ExecutorMeta};diff --git a/rust/ballista/rust/scheduler/src/state/standalone.rs b/rust/ballista/rust/scheduler/src/state/standalone.rsindex 0c7a5ae888..e07d45ece6 100644--- a/rust/ballista/rust/scheduler/src/state/standalone.rs+++ b/rust/ballista/rust/scheduler/src/state/standalone.rs@@ -88,7 +88,12 @@ impl ConfigBackendClient for StandaloneClient {}// TODO: support lease_time. See https://github.com/spacejam/sled/issues/1119 for how to approach this- async fn put(&self, key: String, value: Vec<u8>, _lease_time: Option<Duration>) -> Result<()> {+ async fn put(+ &self,+ key: String,+ value: Vec<u8>,+ _lease_time: Option<Duration>,+ ) -> Result<()> {self.db.insert(key, value).map_err(|e| {