comphead commented on code in PR #27578:
URL: https://github.com/apache/datafusion/pull/27578#discussion_r4657197763
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -279,8 +286,12 @@ pub struct PiecewiseMergeJoinExec {
pub operator: Operator,
/// How the join is performed
pub join_type: JoinType,
- /// The schema once the join is applied
+ /// The schema once the join is applied, after `projection`
schema: SchemaRef,
+ /// The schema once the join is applied, before `projection`, which
indexes into it
+ join_schema: SchemaRef,
Review Comment:
`join_schema`, the projected `schema` and the cached properties now hold
three schemas, and `project` and `replace_children` have to keep two of them in
step. `SortMergeJoinExec` keeps `schema` as the unprojected join schema and
reads the output schema from the cache through `self.schema()`. Doing the same
here leaves `schema` as it is on `main`: `join_schema` goes away, `project`,
`Display` and `JoinProjection::try_new` read `self.schema`, and
`with_projection` (`can_project`) and `execute` use `self.schema()`.
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -1255,3 +1485,116 @@ pub(super) struct BufferedSideReadyState {
/// Collected build-side data
pub(super) buffered_data: Arc<BufferedSideData>,
}
+
+#[cfg(test)]
+mod tests {
Review Comment:
These can move into `classic_join.rs`'s `mod tests`, which already has
`build_table`, `columns` and `join` (copied here as `build_table`,
`field_names` and `less_than_join`, and `build_table` is also
`crate::test::build_table_scan_i32`). In the same pass:
- `projected_properties_forget_dropped_columns` can go. `schema()` is
`properties().schema()`, the eq-properties schema, so its second `assert_eq!`
compares a value with itself, and the `["b2"]` check repeats the field check in
the first test.
- `projection_rejected_for_existence_joins` can go too. The planner side is
already pinned by the LeftSemi `EXPLAIN` in `pwmj.slt` that keeps its
`ProjectionExec`, and the direct call is only reachable from a hand-built plan.
- In the first test, `with_new_children(children)` is the `Recompute` path,
and the execute and snapshot half repeats the matrix "FULL, partial" case.
Asserting `projection()` and the field names is enough, as a sync `#[test]`.
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -406,6 +419,73 @@ impl PiecewiseMergeJoinExec {
&self.sort_options
}
+ /// The embedded projection, as indices into the unprojected join schema
+ pub fn projection(&self) -> Option<&ProjectionRef> {
+ self.projection.as_ref().map(|p| &p.indices)
+ }
+
+ /// Whether a parent projection has been embedded into this join.
+ pub fn contains_projection(&self) -> bool {
+ self.projection.is_some()
+ }
+
+ /// Returns a copy of this join whose output is `projection` of its
current output.
+ ///
+ /// Only Inner/Left/Right/Full joins take one: the existence joins emit
one side (plus
+ /// a `mark` column) through streams that do not narrow their input.
+ pub fn with_projection(&self, projection: Option<Vec<usize>>) ->
Result<Self> {
+ let projection: Option<ProjectionRef> = projection.map(Into::into);
+ can_project(&self.schema, projection.as_deref())?;
+ let projection = combine_projections(projection.as_ref(),
self.projection())?;
+
+ let join = Self::try_new(
+ Arc::clone(&self.buffered),
+ Arc::clone(&self.streamed),
+ self.on.clone(),
+ self.operator,
+ self.join_type,
+ self.num_partitions,
+ )?;
+ match projection {
+ Some(indices) => join.project(indices),
+ None => Ok(join),
+ }
+ }
+
+ /// Embeds `indices` into a join that has no projection yet.
+ fn project(mut self, indices: ProjectionRef) -> Result<Self> {
+ if !is_classic_join(self.join_type) {
+ return internal_err!(
+ "PiecewiseMergeJoinExec cannot embed a projection for {}
joins",
+ self.join_type
+ );
+ }
Review Comment:
Taking an `Option` here turns the three `try_new` + `match` sites into one
call each: `Self::try_new(..)?.project(projection)` in `with_projection`,
`.project(self.projection().cloned())` in `Recompute`, and the proto decode
`match` yielding an `Option<ProjectionRef>`.
`is_classic_join` is `!is_existence_join` from `crate::joins::utils`
(already used by `HashJoinExec::swap_inputs`), so
`try_swapping_with_projection` can call that too and `is_classic_join` can go.
And since `with_projection` is public, the existence-join case is a missing
feature rather than a DataFusion bug, so `not_impl_err!` fits better than
`internal_err!`:
```suggestion
/// Embeds `indices`, if any, into a join that has no projection yet.
fn project(mut self, indices: Option<ProjectionRef>) -> Result<Self> {
let Some(indices) = indices else {
return Ok(self);
};
if is_existence_join(self.join_type) {
return not_impl_err!(
"PiecewiseMergeJoinExec cannot embed a projection for {}
joins",
self.join_type
);
}
```
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -957,29 +1082,129 @@ impl DisplayAs for PiecewiseMergeJoinExec {
fmt_sql(self.on.1.as_ref())
);
+ let projection_str = self.projection().map(|indices| {
+ let columns = indices
+ .iter()
+ .map(|&i| format!("{}@{i}", self.join_schema.field(i).name()))
+ .collect::<Vec<_>>();
+ format!("projection=[{}]", columns.join(", "))
+ });
+
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
write!(
f,
"PiecewiseMergeJoin: operator={:?}, join_type={:?}, on={}",
self.operator, self.join_type, on_str
- )
+ )?;
+ if let Some(projection_str) = projection_str {
+ write!(f, ", {projection_str}")?;
+ }
}
DisplayFormatType::TreeRender => {
writeln!(f, "operator={:?}", self.operator)?;
if self.join_type != JoinType::Inner {
writeln!(f, "join_type={:?}", self.join_type)?;
}
- writeln!(f, "on={on_str}")
+ writeln!(f, "on={on_str}")?;
+ if let Some(projection_str) = projection_str {
+ writeln!(f, "{projection_str}")?;
+ }
}
}
+ Ok(())
+ }
+}
+
+impl EmbeddedProjection for PiecewiseMergeJoinExec {
+ fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
+ self.with_projection(projection)
+ }
+}
+
+/// An embedded projection split per side, so each side is narrowed as it
arrives instead
+/// of every column being materialized into the output and dropped afterwards.
+///
+/// The classic stream builds each output batch's columns as `buffered_columns
++
+/// streamed_columns`; `reorder` then puts them into `indices` order,
zero-copy.
+#[derive(Debug)]
+struct JoinProjection {
+ /// Indices into the unprojected join schema, as embedded
+ indices: ProjectionRef,
+ /// Buffered columns kept, ascending
+ buffered_columns: Vec<usize>,
+ /// Streamed columns kept, ascending
+ streamed_columns: Vec<usize>,
+ /// The streamed input's schema narrowed to `streamed_columns`
+ streamed_schema: SchemaRef,
+ /// Maps `buffered_columns ++ streamed_columns` onto the output, or `None`
when they
+ /// are already in output order
+ reorder: Option<Vec<usize>>,
+}
+
+impl JoinProjection {
+ fn try_new(
+ indices: ProjectionRef,
+ join_schema: &SchemaRef,
+ streamed_schema: &SchemaRef,
+ ) -> Result<Self> {
+ let num_buffered = join_schema.fields().len() -
streamed_schema.fields().len();
+
+ let mut buffered_columns: Vec<usize> = indices
+ .iter()
+ .copied()
+ .filter(|&i| i < num_buffered)
+ .collect();
+ buffered_columns.sort_unstable();
+ buffered_columns.dedup();
+
+ let mut streamed_columns: Vec<usize> = indices
+ .iter()
+ .filter_map(|&i| i.checked_sub(num_buffered))
+ .collect();
+ streamed_columns.sort_unstable();
+ streamed_columns.dedup();
+
+ let stream_columns: Vec<usize> = buffered_columns
+ .iter()
+ .copied()
+ .chain(streamed_columns.iter().map(|&i| i + num_buffered))
+ .collect();
+ let reorder: Vec<usize> = indices
+ .iter()
+ .map(|i| {
+ stream_columns
+ .iter()
+ .position(|j| j == i)
+ .ok_or_else(|| internal_datafusion_err!("column {i} not
kept"))
+ })
+ .collect::<Result<_>>()?;
+ let is_identity = reorder.len() == stream_columns.len()
+ && reorder.iter().enumerate().all(|(k, &i)| k == i);
+
+ Ok(Self {
+ streamed_schema:
Arc::new(streamed_schema.project(&streamed_columns)?),
+ reorder: (!is_identity).then_some(reorder),
+ indices,
+ buffered_columns,
+ streamed_columns,
+ })
Review Comment:
`indices` is sorted and deduped twice (once per side), `stream_columns`
rebuilds the same sorted list, and each `reorder` entry is a linear `position`
over it. Since every buffered index sorts before every streamed one, one sort
gives both sides and the build order, `reorder` is a `partition_point` into it,
and the identity check is `kept == indices`. That also drops the `column {i}
not kept` error, which cannot fire, and the `stream_columns` /
`streamed_columns` naming clash. Checked against the current logic for every
index list up to length 4 over joins up to 5 columns wide:
```suggestion
// Sorted, `kept` is also the order the stream builds columns in:
the kept
// buffered columns, then the kept streamed ones.
let mut kept = indices.to_vec();
kept.sort_unstable();
kept.dedup();
let reorder: Option<Vec<usize>> = (kept[..] != indices[..]).then(|| {
indices
.iter()
.map(|i| kept.partition_point(|k| k < i))
.collect()
});
let split = kept.partition_point(|&i| i < num_buffered);
let streamed_columns: Vec<usize> =
kept.drain(split..).map(|i| i - num_buffered).collect();
Ok(Self {
streamed_schema:
Arc::new(streamed_schema.project(&streamed_columns)?),
reorder,
indices,
buffered_columns: kept,
streamed_columns,
})
```
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -140,24 +143,35 @@ impl ClassicPWMJStream {
join_type: JoinType,
operator: Operator,
streamed: SendableRecordBatchStream,
+ streamed_projection: Option<(Vec<usize>, SchemaRef)>,
+ output_reorder: Option<Vec<usize>>,
Review Comment:
`JoinProjection` is unpacked into a tuple plus `output_reorder` here and
repacked in the body, and `execute` clones two `Vec`s per partition to do it.
Passing `Option<Arc<JoinProjection>>` (with the struct `pub(super)`) keeps one
parameter: `streamed_schema` and the `OutputBuffer` reorder come from it in
`try_new`, and `fetch_stream_batch` reads `streamed_columns` from it.
##########
datafusion/sqllogictest/test_files/piecewise_merge_join_matrix.slt:
##########
@@ -589,6 +589,371 @@ SELECT l.lid, l.lv, r.rid, r.rv FROM cj_lsl l FULL JOIN
cj_lsr r ON l.lv >= r.rv
NULL NULL 5 [{x: 7, y: NULL}]
NULL NULL 6 NULL
+# ------------------------------------------------------------------
+# Embedded projection: each classic join type under each select list shape --
+# partial (some columns of both sides, reordered, with same-typed `p`/`q` so a
+# swapped column is wrong rather than an error), one side only (the other side
is
+# narrowed to zero columns), and none (`count(*)`, both sides narrowed to
zero).
+# pj_r is inserted as three batches, the first with no matchable row, so it is
settled
+# whole; NULL keys on both sides leave unmatched rows for the outer joins.
Review Comment:
FULL alone reaches every branch the projection touches: `flush` (all types),
unmatched streamed rows (Right/Full, `split_off_never_matching`) and unmatched
buffered rows (Left/Full, `process_unmatched_buffered_batch`), all ending in
`push_columns`. Narrowing does not depend on the join type, and `configMatrix`
already reruns each query 8 times against NLJ. So FULL with {partial, buffered
only, streamed only, none} plus one identity query covers what the 21 queries
here do, and the `>=` case adds nothing for the projection. Also, "Every case
above reorders" in the identity comment is off: the `count(*)` cases embed `[]`
and take `reorder: None`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]