Skip to content

Commit 02a902c

Browse files
refactor(proto): migrate FilterExec serde (apache#23708)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes apache#123` indicates that this PR will close issue apache#123. --> - Closes apache#23499. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> The centralized protobuf dispatcher couples each execution plan to datafusion-proto. Adding plan serialization therefore requires changes outside the plan implementation. Move FilterExec encoding and decoding behind its ExecutionPlan hooks. Preserve the existing wire format and retain the old helper methods as deprecated compatibility APIs. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> --------- Signed-off-by: Jiawei Zhao <[email protected]>
1 parent 774f0bc commit 02a902c

3 files changed

Lines changed: 152 additions & 80 deletions

File tree

‎datafusion/physical-plan/src/filter.rs‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,101 @@ impl ExecutionPlan for FilterExec {
812812
.ok()
813813
})
814814
}
815+
816+
#[cfg(feature = "proto")]
817+
fn try_to_proto(
818+
&self,
819+
ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
820+
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
821+
use datafusion_proto_models::protobuf;
822+
let input = ctx.encode_child(self.input())?;
823+
let expr = ctx.encode_expr(self.predicate())?;
824+
// Preserve the exact wire format: `None` (full projection) is serialized
825+
// as the identity projection `[0, 1, ..., num_fields - 1]` so that it is
826+
// distinguishable from an explicit projection on decode.
827+
let projection = if let Some(v) = self.projection() {
828+
v.iter().map(|x| *x as u32).collect()
829+
} else {
830+
(0..self.input().schema().fields().len())
831+
.map(|i| i as u32)
832+
.collect()
833+
};
834+
Ok(Some(protobuf::PhysicalPlanNode {
835+
physical_plan_type: Some(
836+
protobuf::physical_plan_node::PhysicalPlanType::Filter(Box::new(
837+
protobuf::FilterExecNode {
838+
input: Some(Box::new(input)),
839+
expr: Some(expr),
840+
default_filter_selectivity: self.default_selectivity() as u32,
841+
projection,
842+
batch_size: self.batch_size() as u32,
843+
fetch: self.fetch().map(|f| f as u32),
844+
},
845+
)),
846+
),
847+
}))
848+
}
849+
}
850+
851+
#[cfg(feature = "proto")]
852+
impl FilterExec {
853+
/// Reconstruct a [`FilterExec`] from its protobuf representation.
854+
///
855+
/// The exact inverse of [`ExecutionPlan::try_to_proto`]: it takes the whole
856+
/// [`PhysicalPlanNode`] so every plan's `try_from_proto` shares one signature.
857+
///
858+
/// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
859+
/// [`ExecutionPlan::try_to_proto`]: crate::ExecutionPlan::try_to_proto
860+
pub fn try_from_proto(
861+
node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
862+
ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
863+
) -> Result<Arc<dyn ExecutionPlan>> {
864+
use datafusion_proto_models::protobuf;
865+
let filter = crate::expect_plan_variant!(
866+
node,
867+
protobuf::physical_plan_node::PhysicalPlanType::Filter,
868+
"FilterExec",
869+
);
870+
let input =
871+
ctx.decode_required_child(filter.input.as_deref(), "FilterExec", "input")?;
872+
let predicate = ctx.decode_required_expr(
873+
filter.expr.as_ref(),
874+
input.schema().as_ref(),
875+
"FilterExec",
876+
"expr",
877+
)?;
878+
let filter_selectivity = filter.default_filter_selectivity.try_into();
879+
880+
// `None` is encoded as the full identity projection. Reconstruct it only
881+
// when all input columns are present in order, leaving an empty list as
882+
// `Some(vec![])`.
883+
let num_fields = input.schema().fields().len();
884+
let mut is_full_projection = filter.projection.len() == num_fields;
885+
let mut projection_vec: Vec<usize> = Vec::with_capacity(filter.projection.len());
886+
for (i, idx) in filter.projection.iter().enumerate() {
887+
let idx = *idx as usize;
888+
is_full_projection &= idx == i;
889+
projection_vec.push(idx);
890+
}
891+
let projection = if is_full_projection {
892+
None
893+
} else {
894+
Some(projection_vec)
895+
};
896+
let filter = FilterExecBuilder::new(predicate, input)
897+
.apply_projection(projection)?
898+
.with_batch_size(filter.batch_size as usize)
899+
.with_fetch(filter.fetch.map(|f| f as usize))
900+
.build()?;
901+
match filter_selectivity {
902+
Ok(filter_selectivity) => Ok(Arc::new(
903+
filter.with_default_selectivity(filter_selectivity)?,
904+
)),
905+
Err(_) => Err(datafusion_common::internal_datafusion_err!(
906+
"filter_selectivity in PhysicalPlanNode is invalid"
907+
)),
908+
}
909+
}
815910
}
816911

817912
impl EmbeddedProjection for FilterExec {

‎datafusion/proto/src/physical_plan/mod.rs‎

Lines changed: 24 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ use datafusion_physical_plan::coop::CooperativeExec;
7777
use datafusion_physical_plan::empty::EmptyExec;
7878
use datafusion_physical_plan::explain::ExplainExec;
7979
use datafusion_physical_plan::expressions::PhysicalSortExpr;
80-
use datafusion_physical_plan::filter::{FilterExec, FilterExecBuilder};
80+
use datafusion_physical_plan::filter::FilterExec;
8181
use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter};
8282
use datafusion_physical_plan::joins::{
8383
CrossJoinExec, HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec,
@@ -756,8 +756,8 @@ pub trait PhysicalPlanNodeExt: Sized {
756756
PhysicalPlanType::Projection(_) => {
757757
ProjectionExec::try_from_proto(self.node(), &decode_ctx)
758758
}
759-
PhysicalPlanType::Filter(filter) => {
760-
self.try_into_filter_physical_plan(filter, ctx, proto_converter)
759+
PhysicalPlanType::Filter(_) => {
760+
FilterExec::try_from_proto(self.node(), &decode_ctx)
761761
}
762762
PhysicalPlanType::CsvScan(scan) => {
763763
self.try_into_csv_scan_physical_plan(scan, ctx, proto_converter)
@@ -913,14 +913,6 @@ pub trait PhysicalPlanNodeExt: Sized {
913913
);
914914
}
915915

916-
if let Some(exec) = plan.downcast_ref::<FilterExec>() {
917-
return protobuf::PhysicalPlanNode::try_from_filter_exec(
918-
exec,
919-
codec,
920-
proto_converter,
921-
);
922-
}
923-
924916
if let Some(limit) = plan.downcast_ref::<GlobalLimitExec>() {
925917
return protobuf::PhysicalPlanNode::try_from_global_limit_exec(
926918
limit,
@@ -1214,59 +1206,25 @@ pub trait PhysicalPlanNodeExt: Sized {
12141206
Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input)?))
12151207
}
12161208

1209+
#[deprecated(
1210+
since = "55.0.0",
1211+
note = "unused by DataFusion; `FilterExec` deserializes itself via `FilterExec::try_from_proto`"
1212+
)]
12171213
fn try_into_filter_physical_plan(
12181214
&self,
12191215
filter: &protobuf::FilterExecNode,
12201216
ctx: &PhysicalPlanDecodeContext<'_>,
12211217
proto_converter: &dyn PhysicalProtoConverterExtension,
12221218
) -> Result<Arc<dyn ExecutionPlan>> {
1223-
let input: Arc<dyn ExecutionPlan> =
1224-
into_physical_plan(&filter.input, ctx, proto_converter)?;
1225-
1226-
let predicate = filter
1227-
.expr
1228-
.as_ref()
1229-
.map(|expr| {
1230-
proto_converter.proto_to_physical_expr(expr, input.schema().as_ref(), ctx)
1231-
})
1232-
.transpose()?
1233-
.ok_or_else(|| {
1234-
internal_datafusion_err!(
1235-
"filter (FilterExecNode) in PhysicalPlanNode is missing."
1236-
)
1237-
})?;
1238-
1239-
let filter_selectivity = filter.default_filter_selectivity.try_into();
1240-
// Preserve the `None` state across proto boundaries. Proto cannot distinguish
1241-
// between `None` (full projection) and `Some(vec![])` (empty projection) since
1242-
// both serialize as an empty list. If all columns are included, we reconstruct
1243-
// `None` to avoid losing this semantic distinction on deserialization.
1244-
let num_fields = input.schema().fields().len();
1245-
let mut is_full_projection = filter.projection.len() == num_fields;
1246-
let mut projection_vec: Vec<usize> = Vec::with_capacity(filter.projection.len());
1247-
for (i, idx) in filter.projection.iter().enumerate() {
1248-
let idx = *idx as usize;
1249-
is_full_projection &= idx == i;
1250-
projection_vec.push(idx);
1251-
}
1252-
let projection = if is_full_projection {
1253-
None
1254-
} else {
1255-
Some(projection_vec)
1219+
let node = protobuf::PhysicalPlanNode {
1220+
physical_plan_type: Some(PhysicalPlanType::Filter(Box::new(filter.clone()))),
12561221
};
1257-
let filter = FilterExecBuilder::new(predicate, input)
1258-
.apply_projection(projection)?
1259-
.with_batch_size(filter.batch_size as usize)
1260-
.with_fetch(filter.fetch.map(|f| f as usize))
1261-
.build()?;
1262-
match filter_selectivity {
1263-
Ok(filter_selectivity) => Ok(Arc::new(
1264-
filter.with_default_selectivity(filter_selectivity)?,
1265-
)),
1266-
Err(_) => Err(internal_datafusion_err!(
1267-
"filter_selectivity in PhysicalPlanNode is invalid "
1268-
)),
1269-
}
1222+
let decoder = ConverterPlanDecoder {
1223+
ctx,
1224+
proto_converter,
1225+
};
1226+
let decode_ctx = ExecutionPlanDecodeCtx::new(&decoder);
1227+
FilterExec::try_from_proto(&node, &decode_ctx)
12701228
}
12711229

12721230
fn try_into_csv_scan_physical_plan(
@@ -2963,36 +2921,22 @@ pub trait PhysicalPlanNodeExt: Sized {
29632921
})
29642922
}
29652923

2924+
#[deprecated(
2925+
since = "55.0.0",
2926+
note = "unused by DataFusion; `FilterExec` serializes itself via `ExecutionPlan::try_to_proto`"
2927+
)]
29662928
fn try_from_filter_exec(
29672929
exec: &FilterExec,
29682930
codec: &dyn PhysicalExtensionCodec,
29692931
proto_converter: &dyn PhysicalProtoConverterExtension,
29702932
) -> Result<protobuf::PhysicalPlanNode> {
2971-
let input = protobuf::PhysicalPlanNode::try_from_physical_plan_with_converter(
2972-
exec.input().to_owned(),
2933+
let encoder = ConverterPlanEncoder {
29732934
codec,
29742935
proto_converter,
2975-
)?;
2976-
Ok(protobuf::PhysicalPlanNode {
2977-
physical_plan_type: Some(PhysicalPlanType::Filter(Box::new(
2978-
protobuf::FilterExecNode {
2979-
input: Some(Box::new(input)),
2980-
expr: Some(
2981-
proto_converter
2982-
.physical_expr_to_proto(exec.predicate(), codec)?,
2983-
),
2984-
default_filter_selectivity: exec.default_selectivity() as u32,
2985-
projection: match exec.projection() {
2986-
None => (0..exec.input().schema().fields().len())
2987-
.map(|i| i as u32)
2988-
.collect(),
2989-
Some(v) => v.iter().map(|x| *x as u32).collect(),
2990-
},
2991-
batch_size: exec.batch_size() as u32,
2992-
fetch: exec.fetch().map(|f| f as u32),
2993-
},
2994-
))),
2995-
})
2936+
};
2937+
let encode_ctx = ExecutionPlanEncodeCtx::new(&encoder);
2938+
exec.try_to_proto(&encode_ctx)?
2939+
.ok_or_else(|| internal_datafusion_err!("FilterExec is not serializable"))
29962940
}
29972941

29982942
fn try_from_global_limit_exec(

‎datafusion/proto/tests/cases/roundtrip_physical_plan.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,6 +1028,39 @@ fn roundtrip_filter_with_fetch() -> Result<()> {
10281028
roundtrip_test(Arc::new(filter))
10291029
}
10301030

1031+
#[test]
1032+
fn roundtrip_filter_projection_states() -> Result<()> {
1033+
let schema = Arc::new(Schema::new(vec![
1034+
Field::new("a", DataType::Boolean, false),
1035+
Field::new("b", DataType::Int64, false),
1036+
]));
1037+
let ctx = SessionContext::new();
1038+
let codec = DefaultPhysicalExtensionCodec {};
1039+
let proto_converter = DefaultPhysicalProtoConverter {};
1040+
1041+
for projection in [None, Some(vec![]), Some(vec![0])] {
1042+
let filter = FilterExecBuilder::new(
1043+
col("a", &schema)?,
1044+
Arc::new(EmptyExec::new(Arc::clone(&schema))),
1045+
)
1046+
.apply_projection(projection.clone())?
1047+
.with_default_selectivity(37)
1048+
.with_batch_size(1024)
1049+
.with_fetch(Some(5))
1050+
.build()?;
1051+
1052+
let result =
1053+
roundtrip_test_and_return(Arc::new(filter), &ctx, &codec, &proto_converter)?;
1054+
let result = result.downcast_ref::<FilterExec>().unwrap();
1055+
assert_eq!(result.projection().as_deref(), projection.as_deref());
1056+
assert_eq!(result.default_selectivity(), 37);
1057+
assert_eq!(result.batch_size(), 1024);
1058+
assert_eq!(result.fetch(), Some(5));
1059+
}
1060+
1061+
Ok(())
1062+
}
1063+
10311064
#[test]
10321065
fn roundtrip_sort() -> Result<()> {
10331066
let field_a = Field::new("a", DataType::Boolean, false);

0 commit comments

Comments
 (0)