diff --git a/datafusion/proto/src/logical_plan/composed.rs b/datafusion/proto/src/logical_plan/composed.rs new file mode 100644 index 0000000000000..9fccd93529dee --- /dev/null +++ b/datafusion/proto/src/logical_plan/composed.rs @@ -0,0 +1,841 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +use std::sync::Arc; + +use arrow::datatypes::SchemaRef; +use datafusion_catalog::TableProvider; +use datafusion_common::{ + DataFusionError, Result, TableReference, config_datafusion_err, config_err, + exec_datafusion_err, internal_datafusion_err, +}; +use datafusion_datasource::file_format::FileFormatFactory; +use datafusion_execution::TaskContext; +use datafusion_expr::{ + AggregateUDF, Extension, HigherOrderUDF, LogicalPlan, ScalarUDF, WindowUDF, +}; +use prost::Message; + +use super::LogicalExtensionCodec; +use crate::physical_plan::DataEncoderTuple; + +/// A [`LogicalExtensionCodec`] that combines several codecs, such as one per +/// table format, the way [`ComposedPhysicalExtensionCodec`] does for physical +/// plans. +/// +/// Encoding uses the first codec that succeeds and records its position in the +/// payload, and decoding uses only the codec at that position. Both sides must +/// therefore compose the same codecs in the same order, so add new codecs at +/// the end. +/// +/// Functions and file formats are the exception, because the trait's default +/// encoders for them succeed without writing anything. For these, the first +/// codec that writes something is used. If none does, a function is sent by +/// name, and resolved from the function registry or else by the first codec +/// that can decode it, while a file format stays with the first codec that +/// succeeded. +/// +/// # Example +/// +/// ``` +/// # use std::sync::Arc; +/// # use arrow::datatypes::SchemaRef; +/// # use datafusion::catalog::TableProvider; +/// # use datafusion::datasource::file_format::csv::CsvFormatFactory; +/// # use datafusion::datasource::file_format::format_as_file_type; +/// # use datafusion::execution::TaskContext; +/// # use datafusion::prelude::SessionContext; +/// # use datafusion_common::{Result, TableReference, not_impl_err}; +/// # use datafusion_expr::{Extension, LogicalPlan, LogicalPlanBuilder}; +/// # use datafusion_proto::bytes::{ +/// # logical_plan_from_bytes_with_extension_codec, +/// # logical_plan_to_bytes_with_extension_codec, +/// # }; +/// # use datafusion_proto::logical_plan::{ +/// # ComposedLogicalExtensionCodec, DefaultLogicalExtensionCodec, +/// # LogicalExtensionCodec, +/// # }; +/// # #[derive(Debug)] +/// # struct MyTableCodec; +/// # impl LogicalExtensionCodec for MyTableCodec { +/// # fn try_decode(&self, _: &[u8], _: &[LogicalPlan], _: &TaskContext) -> Result { +/// # not_impl_err!("no extension nodes") +/// # } +/// # fn try_encode(&self, _: &Extension, _: &mut Vec) -> Result<()> { +/// # not_impl_err!("no extension nodes") +/// # } +/// # fn try_decode_table_provider( +/// # &self, _: &[u8], _: &TableReference, _: SchemaRef, _: &TaskContext, +/// # ) -> Result> { +/// # not_impl_err!("no tables") +/// # } +/// # fn try_encode_table_provider( +/// # &self, _: &TableReference, _: Arc, _: &mut Vec, +/// # ) -> Result<()> { +/// # not_impl_err!("no tables") +/// # } +/// # } +/// # fn main() -> Result<()> { +/// // `MyTableCodec` encodes the application's table providers, and the +/// // default codec the built-in file formats. +/// let codec = ComposedLogicalExtensionCodec::new(vec![ +/// Arc::new(MyTableCodec), +/// Arc::new(DefaultLogicalExtensionCodec {}), +/// ]); +/// +/// let plan = LogicalPlanBuilder::copy_to( +/// LogicalPlanBuilder::empty(true).build()?, +/// "out.csv".to_string(), +/// format_as_file_type(Arc::new(CsvFormatFactory::new())), +/// Default::default(), +/// vec![], +/// )? +/// .build()?; +/// let bytes = logical_plan_to_bytes_with_extension_codec(&plan, &codec)?; +/// let ctx = SessionContext::new(); +/// let decoded = +/// logical_plan_from_bytes_with_extension_codec(&bytes, &ctx.task_ctx(), &codec)?; +/// assert_eq!(decoded, plan); +/// # Ok(()) +/// # } +/// ``` +/// +/// [`ComposedPhysicalExtensionCodec`]: crate::physical_plan::ComposedPhysicalExtensionCodec +#[derive(Debug)] +pub struct ComposedLogicalExtensionCodec { + codecs: Vec>, +} + +impl ComposedLogicalExtensionCodec { + /// Combines `codecs`, trying them in order when encoding. + pub fn new(codecs: Vec>) -> Self { + Self { codecs } + } + + fn encode_protobuf( + &self, + buf: &mut Vec, + empty: EmptyBlob, + encode: impl Fn(&dyn LogicalExtensionCodec, &mut Vec) -> Result<()>, + ) -> Result<()> { + let mut errors = Vec::new(); + let mut first_empty = None; + for (position, codec) in self.codecs.iter().enumerate() { + // A fresh buffer per codec drops what a failed codec wrote. + let mut blob = Vec::new(); + match encode(codec.as_ref(), &mut blob) { + Ok(()) if blob.is_empty() && !matches!(empty, EmptyBlob::Claims) => { + first_empty.get_or_insert(position); + } + Ok(()) => return encode_tuple(position, blob, buf), + Err(e) => errors.push(e), + } + } + match (first_empty, empty) { + (Some(_), EmptyBlob::ByName) => Ok(()), + (Some(position), _) => encode_tuple(position, Vec::new(), buf), + (None, _) => Err(combine_errors(errors, "encode it")), + } + } + + fn decode_protobuf( + &self, + buf: &[u8], + decode: impl FnOnce(&dyn LogicalExtensionCodec, &[u8]) -> Result, + ) -> Result { + let proto = DataEncoderTuple::decode(buf).map_err(|e| { + config_datafusion_err!( + "Invalid composed codec payload: {e}. {SAME_CODECS_HINT}" + ) + })?; + let Some(codec) = self.codecs.get(proto.encoder_position as usize) else { + return config_err!( + "Payload was encoded by composed codec {}, but only {} are composed \ + here. {SAME_CODECS_HINT}", + proto.encoder_position, + self.codecs.len() + ); + }; + decode(codec.as_ref(), &proto.blob) + } + + /// Like [`Self::decode_protobuf`], except that an empty `buf` means the + /// function was sent by name ([`EmptyBlob::ByName`]), so no codec claimed + /// it and each is tried in turn. + fn decode_function( + &self, + name: &str, + buf: &[u8], + decode: impl Fn(&dyn LogicalExtensionCodec, &[u8]) -> Result, + ) -> Result { + if !buf.is_empty() { + return self.decode_protobuf(buf, decode); + } + let mut errors = Vec::new(); + for codec in &self.codecs { + match decode(codec.as_ref(), buf) { + Ok(decoded) => return Ok(decoded), + Err(e) => errors.push(e), + } + } + Err(combine_errors(errors, &format!("decode '{name}' by name"))) + } +} + +const SAME_CODECS_HINT: &str = + "The encoding and decoding sides must compose the same codecs in the same order"; + +/// What a codec that succeeds without writing anything means. +#[derive(Clone, Copy)] +enum EmptyBlob { + /// It claims the node: zero bytes is a real encoding, such as that of an + /// all-default protobuf message. Used for plan nodes and table providers. + Claims, + /// A later codec that writes a payload claims the function. If none does, + /// nothing is written, so the function is sent by name. + ByName, + /// A later codec that writes a payload claims the file format. If none + /// does, the first codec that succeeded claims it: a file format has no + /// name to fall back on. + Defers, +} + +fn encode_tuple(position: usize, blob: Vec, buf: &mut Vec) -> Result<()> { + let encoder_position = + u32::try_from(position).map_err(|e| internal_datafusion_err!("{e}"))?; + DataEncoderTuple { + encoder_position, + blob, + } + .encode(buf) + .map_err(|e| internal_datafusion_err!("{e}")) +} + +/// Combines the errors of codecs that all failed. +/// +/// A codec that returned anything but `NotImplemented` recognised the node, so +/// if exactly one did, its error is returned unchanged, keeping its kind and +/// source chain. Otherwise every error is listed, as `NotImplemented` if every +/// codec declined, so a composed codec nested in another still declines. +fn combine_errors(mut errors: Vec, action: &str) -> DataFusionError { + let declined = |e: &DataFusionError| matches!(e, DataFusionError::NotImplemented(_)); + let recognised: Vec = (0..errors.len()) + .filter(|&position| !declined(&errors[position])) + .collect(); + match (errors.len(), recognised.as_slice()) { + (0, _) => { + DataFusionError::NotImplemented("Empty list of composed codecs".to_owned()) + } + (1, _) => errors.remove(0), + (_, &[position]) => errors.remove(position), + (_, recognised) => { + let listed = errors + .iter() + .enumerate() + .map(|(position, e)| match e { + DataFusionError::NotImplemented(message) => { + format!("codec {position}: {message}") + } + e => format!("codec {position}: {e}"), + }) + .collect::>() + .join("; "); + let message = format!( + "None of the {} composed codecs could {action}: {listed}", + errors.len() + ); + if recognised.is_empty() { + DataFusionError::NotImplemented(message) + } else { + exec_datafusion_err!("{message}") + } + } + } +} + +impl LogicalExtensionCodec for ComposedLogicalExtensionCodec { + fn try_decode( + &self, + buf: &[u8], + inputs: &[LogicalPlan], + ctx: &TaskContext, + ) -> Result { + self.decode_protobuf(buf, |codec, data| codec.try_decode(data, inputs, ctx)) + } + + fn try_encode(&self, node: &Extension, buf: &mut Vec) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::Claims, |codec, data| { + codec.try_encode(node, data) + }) + } + + fn try_decode_table_provider( + &self, + buf: &[u8], + table_ref: &TableReference, + schema: SchemaRef, + ctx: &TaskContext, + ) -> Result> { + self.decode_protobuf(buf, |codec, data| { + codec.try_decode_table_provider(data, table_ref, Arc::clone(&schema), ctx) + }) + } + + fn try_encode_table_provider( + &self, + table_ref: &TableReference, + node: Arc, + buf: &mut Vec, + ) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::Claims, |codec, data| { + codec.try_encode_table_provider(table_ref, Arc::clone(&node), data) + }) + } + + fn try_decode_file_format( + &self, + buf: &[u8], + ctx: &TaskContext, + ) -> Result> { + self.decode_protobuf(buf, |codec, data| codec.try_decode_file_format(data, ctx)) + } + + fn try_encode_file_format( + &self, + buf: &mut Vec, + node: Arc, + ) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::Defers, |codec, data| { + codec.try_encode_file_format(data, Arc::clone(&node)) + }) + } + + fn try_decode_udf(&self, name: &str, buf: &[u8]) -> Result> { + self.decode_function(name, buf, |codec, data| codec.try_decode_udf(name, data)) + } + + fn try_encode_udf(&self, node: &ScalarUDF, buf: &mut Vec) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::ByName, |codec, data| { + codec.try_encode_udf(node, data) + }) + } + + fn try_decode_higher_order_function( + &self, + name: &str, + buf: &[u8], + ) -> Result> { + self.decode_function(name, buf, |codec, data| { + codec.try_decode_higher_order_function(name, data) + }) + } + + fn try_encode_higher_order_function( + &self, + node: &HigherOrderUDF, + buf: &mut Vec, + ) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::ByName, |codec, data| { + codec.try_encode_higher_order_function(node, data) + }) + } + + fn try_decode_udaf(&self, name: &str, buf: &[u8]) -> Result> { + self.decode_function(name, buf, |codec, data| codec.try_decode_udaf(name, data)) + } + + fn try_encode_udaf(&self, node: &AggregateUDF, buf: &mut Vec) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::ByName, |codec, data| { + codec.try_encode_udaf(node, data) + }) + } + + fn try_decode_udwf(&self, name: &str, buf: &[u8]) -> Result> { + self.decode_function(name, buf, |codec, data| codec.try_decode_udwf(name, data)) + } + + fn try_encode_udwf(&self, node: &WindowUDF, buf: &mut Vec) -> Result<()> { + self.encode_protobuf(buf, EmptyBlob::ByName, |codec, data| { + codec.try_encode_udwf(node, data) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bytes::{ + logical_plan_from_bytes_with_extension_codec, + logical_plan_to_bytes_with_extension_codec, + }; + use crate::logical_plan::DefaultLogicalExtensionCodec; + use crate::logical_plan::file_formats::CsvLogicalExtensionCodec; + use arrow::datatypes::{DataType, Field, Schema}; + use datafusion::functions_aggregate::count::count_udaf; + use datafusion::functions_nested::array_transform::array_transform_higher_order_function; + use datafusion::functions_window::row_number::row_number_udwf; + use datafusion::prelude::SessionContext; + use datafusion_catalog::empty::EmptyTable; + use datafusion_common::{not_impl_err, plan_err}; + use datafusion_datasource_csv::file_format::CsvFormatFactory; + use datafusion_datasource_json::file_format::JsonFormatFactory; + use datafusion_functions::string::upper; + use std::fmt::Debug; + + /// Owns the table and the scalar function named after it, and encodes + /// either as that name. Decodes any bytes as its table, a one-column table + /// named after it, as a codec that just calls `MyMessage::decode(buf)` + /// might with another codec's bytes. Everything else keeps the trait's + /// defaults. + #[derive(Debug)] + struct Owner(&'static str); + + impl LogicalExtensionCodec for Owner { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[LogicalPlan], + _ctx: &TaskContext, + ) -> Result { + not_impl_err!("{} has no extension nodes", self.0) + } + + fn try_encode(&self, _node: &Extension, _buf: &mut Vec) -> Result<()> { + not_impl_err!("{} has no extension nodes", self.0) + } + + fn try_decode_table_provider( + &self, + _buf: &[u8], + _table_ref: &TableReference, + _schema: SchemaRef, + _ctx: &TaskContext, + ) -> Result> { + Ok(Arc::new(EmptyTable::new(column(self.0)))) + } + + fn try_encode_table_provider( + &self, + table_ref: &TableReference, + _node: Arc, + buf: &mut Vec, + ) -> Result<()> { + if table_ref.table() != self.0 { + return not_impl_err!("{} doesn't handle {table_ref}", self.0); + } + buf.extend_from_slice(self.0.as_bytes()); + Ok(()) + } + + fn try_decode_udf(&self, name: &str, _buf: &[u8]) -> Result> { + let owned = datafusion_functions::all_default_functions() + .into_iter() + .find(|udf| udf.name() == name && name == self.0); + match owned { + Some(udf) => Ok(udf), + None => not_impl_err!("{} doesn't handle {name}", self.0), + } + } + + fn try_encode_udf(&self, node: &ScalarUDF, buf: &mut Vec) -> Result<()> { + if node.name() == self.0 { + buf.extend_from_slice(self.0.as_bytes()); + } + Ok(()) + } + } + + /// Recognises every table and function but fails to encode it, as a codec + /// that can't load it would. It writes part of a table's payload first, + /// and decodes nothing. + #[derive(Debug)] + struct Broken; + + impl LogicalExtensionCodec for Broken { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[LogicalPlan], + _ctx: &TaskContext, + ) -> Result { + not_impl_err!("broken has no extension nodes") + } + + fn try_encode(&self, _node: &Extension, _buf: &mut Vec) -> Result<()> { + not_impl_err!("broken has no extension nodes") + } + + fn try_decode_table_provider( + &self, + _buf: &[u8], + _table_ref: &TableReference, + _schema: SchemaRef, + _ctx: &TaskContext, + ) -> Result> { + not_impl_err!("broken decodes no tables") + } + + fn try_encode_table_provider( + &self, + table_ref: &TableReference, + _node: Arc, + buf: &mut Vec, + ) -> Result<()> { + buf.extend_from_slice(b"partial"); + plan_err!("can't load {table_ref}") + } + + fn try_encode_udf(&self, node: &ScalarUDF, _buf: &mut Vec) -> Result<()> { + plan_err!("can't load {}", node.name()) + } + + fn try_encode_higher_order_function( + &self, + node: &HigherOrderUDF, + _buf: &mut Vec, + ) -> Result<()> { + plan_err!("can't load {}", node.name()) + } + + fn try_encode_udaf(&self, node: &AggregateUDF, _buf: &mut Vec) -> Result<()> { + plan_err!("can't load {}", node.name()) + } + + fn try_encode_udwf(&self, node: &WindowUDF, _buf: &mut Vec) -> Result<()> { + plan_err!("can't load {}", node.name()) + } + } + + fn column(name: &str) -> SchemaRef { + Arc::new(Schema::new(vec![Field::new(name, DataType::Utf8, true)])) + } + + fn composed(owners: &[&'static str]) -> ComposedLogicalExtensionCodec { + ComposedLogicalExtensionCodec::new( + owners + .iter() + .map(|o| Arc::new(Owner(o)) as Arc) + .collect(), + ) + } + + /// The payload the composed codec writes for `blob` from codec `position`. + fn payload(position: u32, blob: &[u8]) -> Vec { + DataEncoderTuple { + encoder_position: position, + blob: blob.to_vec(), + } + .encode_to_vec() + } + + /// What `encode` writes. + fn written(encode: impl FnOnce(&mut Vec) -> Result<()>) -> Result> { + let mut buf = Vec::new(); + encode(&mut buf)?; + Ok(buf) + } + + fn error(result: Result) -> String { + result.unwrap_err().to_string() + } + + fn encode_table( + codec: &ComposedLogicalExtensionCodec, + table: &str, + ) -> Result> { + let node = Arc::new(EmptyTable::new(Arc::new(Schema::empty()))); + written(|buf| { + codec.try_encode_table_provider(&TableReference::bare(table), node, buf) + }) + } + + /// Decodes a table, returning the name of the codec that decoded it. + fn decode_table(codec: &ComposedLogicalExtensionCodec, buf: &[u8]) -> Result { + let table = codec.try_decode_table_provider( + buf, + &TableReference::bare("t"), + Arc::new(Schema::empty()), + &TaskContext::default(), + )?; + Ok(table.schema().field(0).name().clone()) + } + + #[test] + fn records_the_position_of_the_encoding_codec() -> Result<()> { + let codec = composed(&["delta", "iceberg", "hudi"]); + assert_eq!(encode_table(&codec, "hudi")?, payload(2, b"hudi")); + Ok(()) + } + + #[test] + fn decodes_only_with_the_codec_that_encoded() -> Result<()> { + // Every codec here would decode any bytes it was offered. + let codec = composed(&["delta", "iceberg", "hudi"]); + for owner in ["delta", "iceberg", "hudi"] { + assert_eq!(decode_table(&codec, &encode_table(&codec, owner)?)?, owner); + } + Ok(()) + } + + #[test] + fn discards_what_a_failed_codec_wrote() -> Result<()> { + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Broken), + Arc::new(Owner("iceberg")), + ]); + assert_eq!(encode_table(&codec, "iceberg")?, payload(1, b"iceberg")); + Ok(()) + } + + #[test] + fn keeps_a_node_encoded_as_zero_bytes_with_its_codec() -> Result<()> { + // The owner with an empty name encodes its table as zero bytes, like + // an all-default protobuf message. + let codec = composed(&["iceberg", "", "hudi"]); + let buf = encode_table(&codec, "")?; + assert_eq!(buf, payload(1, b"")); + assert_eq!(decode_table(&codec, &buf)?, ""); + + // At position 0 the whole payload is empty. + let codec = composed(&["", "iceberg"]); + let buf = encode_table(&codec, "")?; + assert_eq!(buf, b""); + assert_eq!(decode_table(&codec, &buf)?, ""); + Ok(()) + } + + #[test] + fn decodes_an_empty_payload_only_with_the_first_codec() { + // `hudi` would decode anything it was offered. + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Broken), + Arc::new(Owner("hudi")), + ]); + assert_eq!( + error(decode_table(&codec, b"")), + "This feature is not implemented: broken decodes no tables" + ); + } + + #[test] + fn rejects_a_position_beyond_the_list() -> Result<()> { + let buf = encode_table(&composed(&["delta", "iceberg", "hudi"]), "hudi")?; + assert_eq!( + error(decode_table(&composed(&["delta", "iceberg"]), &buf)), + "Invalid or Unsupported Configuration: Payload was encoded by composed \ + codec 2, but only 2 are composed here. The encoding and decoding sides \ + must compose the same codecs in the same order" + ); + Ok(()) + } + + #[test] + fn rejects_an_invalid_payload() { + assert_eq!( + error(decode_table(&composed(&["delta"]), &[0xff])), + "Invalid or Unsupported Configuration: Invalid composed codec payload: \ + failed to decode Protobuf message: invalid varint. The encoding and \ + decoding sides must compose the same codecs in the same order" + ); + } + + #[test] + fn lists_every_error_when_every_codec_declines() { + assert_eq!( + error(encode_table(&composed(&["iceberg", "hudi"]), "delta")), + "This feature is not implemented: None of the 2 composed codecs could \ + encode it: codec 0: iceberg doesn't handle delta; codec 1: hudi doesn't \ + handle delta" + ); + } + + #[test] + fn declines_when_nested_and_every_codec_declines() -> Result<()> { + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(composed(&["iceberg", "hudi"])), + Arc::new(Owner("delta")), + ]); + assert_eq!(encode_table(&codec, "delta")?, payload(1, b"delta")); + Ok(()) + } + + #[test] + fn returns_the_error_of_the_codec_that_recognised_the_node() { + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Owner("delta")), + Arc::new(Broken), + ]); + assert_eq!( + error(encode_table(&codec, "iceberg")), + "Error during planning: can't load iceberg" + ); + } + + #[test] + fn lists_every_error_when_several_codecs_recognised_the_node() { + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Broken), + Arc::new(Owner("delta")), + Arc::new(Broken), + ]); + assert_eq!( + error(encode_table(&codec, "iceberg")), + "Execution error: None of the 3 composed codecs could encode it: codec \ + 0: Error during planning: can't load iceberg; codec 1: delta doesn't \ + handle iceberg; codec 2: Error during planning: can't load iceberg" + ); + } + + #[test] + fn returns_the_only_codecs_error_unchanged() { + assert_eq!( + error(encode_table(&composed(&["iceberg"]), "delta")), + "This feature is not implemented: iceberg doesn't handle delta" + ); + } + + #[test] + fn declines_with_no_codecs() { + assert_eq!( + error(encode_table(&composed(&[]), "delta")), + "This feature is not implemented: Empty list of composed codecs" + ); + } + + #[test] + fn encodes_a_function_with_the_first_codec_that_writes_a_payload() -> Result<()> { + // `iceberg` keeps the trait's default, which succeeds without writing. + let codec = composed(&["iceberg", "upper"]); + let buf = written(|buf| codec.try_encode_udf(&upper(), buf))?; + assert_eq!(buf, payload(1, b"upper")); + assert_eq!(codec.try_decode_udf("upper", &buf)?.name(), "upper"); + Ok(()) + } + + #[test] + fn sends_every_kind_of_function_by_name_when_no_codec_writes_a_payload() -> Result<()> + { + // `Broken` fails, so `iceberg` succeeds at position 1 without writing. + // Any payload would make the decoder skip the function registry. + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Broken), + Arc::new(Owner("iceberg")), + ]); + let higher_order = array_transform_higher_order_function(); + let encoded = [ + written(|buf| codec.try_encode_udf(&upper(), buf))?, + written(|buf| codec.try_encode_higher_order_function(&higher_order, buf))?, + written(|buf| codec.try_encode_udaf(&count_udaf(), buf))?, + written(|buf| codec.try_encode_udwf(&row_number_udwf(), buf))?, + ]; + assert_eq!(encoded, [b""; 4]); + Ok(()) + } + + #[test] + fn decodes_a_function_sent_by_name_with_a_later_codec() -> Result<()> { + let codec = composed(&["iceberg", "upper"]); + assert_eq!(codec.try_decode_udf("upper", b"")?.name(), "upper"); + Ok(()) + } + + #[test] + fn offers_every_kind_of_function_sent_by_name_to_every_codec() { + let codec = composed(&["iceberg", "hudi"]); + let errors = [ + error(codec.try_decode_udf("upper", b"")), + error(codec.try_decode_higher_order_function("array_transform", b"")), + error(codec.try_decode_udaf("count", b"")), + error(codec.try_decode_udwf("row_number", b"")), + ]; + assert_eq!( + errors, + [ + "This feature is not implemented: None of the 2 composed codecs could \ + decode 'upper' by name: codec 0: iceberg doesn't handle upper; codec \ + 1: hudi doesn't handle upper", + "This feature is not implemented: None of the 2 composed codecs could \ + decode 'array_transform' by name: codec 0: LogicalExtensionCodec is \ + not provided for higher order function array_transform; codec 1: \ + LogicalExtensionCodec is not provided for higher order function \ + array_transform", + "This feature is not implemented: None of the 2 composed codecs could \ + decode 'count' by name: codec 0: LogicalExtensionCodec is not \ + provided for aggregate function count; codec 1: LogicalExtensionCodec \ + is not provided for aggregate function count", + "This feature is not implemented: None of the 2 composed codecs could \ + decode 'row_number' by name: codec 0: LogicalExtensionCodec is not \ + provided for window function row_number; codec 1: \ + LogicalExtensionCodec is not provided for window function row_number", + ] + ); + } + + #[test] + fn encodes_a_file_format_with_the_first_codec_that_writes() -> Result<()> { + // `iceberg` keeps the trait's default, which succeeds without writing. + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Owner("iceberg")), + Arc::new(DefaultLogicalExtensionCodec {}), + ]); + let csv: Arc = Arc::new(CsvFormatFactory::new()); + let expected = written(|buf| { + DefaultLogicalExtensionCodec {}.try_encode_file_format(buf, Arc::clone(&csv)) + })?; + assert_eq!( + written(|buf| codec.try_encode_file_format(buf, csv))?, + payload(1, &expected) + ); + Ok(()) + } + + #[test] + fn keeps_an_unwritten_file_format_with_the_first_codec_that_succeeded() -> Result<()> + { + // The CSV codec rejects a JSON format, and neither owner writes it. + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(CsvLogicalExtensionCodec), + Arc::new(Owner("iceberg")), + Arc::new(Owner("hudi")), + ]); + let json = Arc::new(JsonFormatFactory::new()); + assert_eq!( + written(|buf| codec.try_encode_file_format(buf, json))?, + payload(1, b"") + ); + Ok(()) + } + + #[tokio::test] + async fn round_trips_a_plan_split_across_codecs() -> Result<()> { + // `iceberg` encodes the table, the default codec the CSV format, and + // `upper` goes by name. + let ctx = SessionContext::new(); + ctx.register_table("iceberg", Arc::new(EmptyTable::new(column("iceberg"))))?; + let plan = ctx + .state() + .create_logical_plan( + "COPY (SELECT upper(iceberg) FROM iceberg) TO 'out' STORED AS CSV", + ) + .await?; + let codec = ComposedLogicalExtensionCodec::new(vec![ + Arc::new(Owner("iceberg")), + Arc::new(DefaultLogicalExtensionCodec {}), + ]); + let bytes = logical_plan_to_bytes_with_extension_codec(&plan, &codec)?; + let decoded = logical_plan_from_bytes_with_extension_codec( + &bytes, + &ctx.task_ctx(), + &codec, + )?; + assert_eq!( + decoded.display_indent().to_string(), + "CopyTo: format=csv output_url=out options: ()\n \ + Projection: upper(iceberg.iceberg)\n \ + TableScan: iceberg" + ); + assert_eq!(decoded, plan); + Ok(()) + } +} diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs index b0aef619add52..e10d2760e4f1f 100644 --- a/datafusion/proto/src/logical_plan/mod.rs +++ b/datafusion/proto/src/logical_plan/mod.rs @@ -73,10 +73,13 @@ use datafusion_execution::TaskContext; use prost::Message; use prost::bytes::BufMut; +mod composed; pub mod file_formats; pub mod from_proto; pub mod to_proto; +pub use composed::ComposedLogicalExtensionCodec; + pub trait AsLogicalPlan: Debug + Send + Sync + Clone { fn try_decode(buf: &[u8]) -> Result where diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs index 858976d637bbd..34548c37b56c5 100644 --- a/datafusion/proto/src/physical_plan/mod.rs +++ b/datafusion/proto/src/physical_plan/mod.rs @@ -1694,9 +1694,10 @@ pub trait PhysicalProtoConverterExtension { } /// DataEncoderTuple captures the position of the encoder -/// in the codec list that was used to encode the data and actual encoded data +/// in the codec list that was used to encode the data and actual encoded data. +/// Both composed codecs write it, so their payloads share one layout. #[derive(Clone, PartialEq, prost::Message)] -struct DataEncoderTuple { +pub(crate) struct DataEncoderTuple { /// The position of encoder used to encode data /// (to be used for decoding) #[prost(uint32, tag = 1)]