You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "SubhamSinghal (via GitHub)" <gi...@apache.org> on 2026/09/28 17:28:59 UTC
[PR] perf:settle never-matching streamed rows against the buffered extreme… [datafusion]
SubhamSinghal opened a new pull request, #25840:
URL: https://github.com/apache/datafusion/pull/25840
## Which issue does this PR close?
- Part of #18221 (and the PWMJ epic #17427).
It doesn't close #18221. On the issue's 100K × 100K shape, the join's time goes to its huge output, so this change leaves it about the same. See the benchmarks below.
## Rationale for this change
The classic `PiecewiseMergeJoin` stream (`INNER` / `LEFT` / `RIGHT` / `FULL`) sorts each streamed batch, then walks the sorted buffered side row by row to find each streamed row's first match. Two costs are avoidable:
- **Rows that can't match anything still pay full price.** They are sorted, gathered and walked through the buffered side like every other row. This covers keys below every buffered key for `<`, and NULL keys. When most streamed rows can't match, which is common for a selective range predicate, the operator does all this work and outputs nothing for them.
- **The first match is found by a linear walk.** Every match set is a suffix `[k, len)` of the sorted buffered side, so `k` can be found with a binary search instead of stepping over every non-matching buffered row.
## What changes are included in this PR?
All changes are in `joins/piecewise_merge_join/`, plus a new benchmark.
- **Rows that can't match are removed before the sort (`classic_join.rs`).** Because every match set is a suffix, a streamed row matches anything at all only if it matches the last buffered key.
- One vectorized comparison against that key, cached once when the buffered side is ready, finds those rows.
- They are emitted as unmatched rows for `Right`/`Full` and dropped for `Inner`/`Left`. Only the remaining rows are sorted, gathered and scanned.
- When no rows were removed, the path is unchanged except for that one comparison per batch. When some were, the sort indices are mapped back to positions in the batch, so it is still gathered only once.
- An empty buffered side, or one whose keys are all NULL, short-circuits without the comparison.
- **The comparison must agree exactly with the scan, or it would change results.**
- Flat keys use one `apply_cmp`, which normalizes `-0.0`/`+0.0` just as the scan's `JoinKeyComparator` does.
- Nested keys are decided with the scan's own comparator. `apply_cmp` orders NULL elements inside a key ascending, while the comparator applies the sort options, descending for `<`/`<=`, at every nesting level.
- The scan's nested ordering for `<`/`<=` gives different results from `NestedLoopJoinExec` when keys contain NULL elements. That is a pre-existing bug on `main`, which I'll file and fix separately. This PR keeps PWMJ's current results unchanged.
- **Binary search for each row's first match (`utils.rs`).**
- `first_match(lo, hi, matches)` replaces the linear walk in `resolve_classic_join`.
- It searches `[previous row's match, len)`. The streamed batch is sorted, so each row's first match is at or after the previous row's.
- The existence stream already did an inline binary search. It now calls the same helper, with no change in behavior.
- The operator dispatch moves into two small helpers, `matches_on_equal` and `is_match`, used by both streams.
- **Streamed NULL keys never reach the scan now,** since the new pre-sort step removes them. The scan's streamed-NULL skip was dead code and is replaced by a `debug_assert`. The buffered-side NULL skip stays.
### Benchmarks
`cargo bench -p datafusion --bench pwmj_classic_sql`, Apple M-series, tp=1. The baseline is `main` (`bf01e288e`): the same build with only `classic_join.rs` swapped back to `main`'s version, saved with `--save-baseline main`. Every change listed has p = 0.00.
| regime | `main` (median) | Inner | Left | Right | Full |
|---|---|---|---|---|---|
| `no_match`: no streamed row matches | 47–50 ms | −95.9% (25×) | −95.9% (24×) | −94.0% (17×) | −93.7% (16×) |
| `null_heavy`: half NULL, rest `no_match` | 45–50 ms | −95.7% (23×) | −95.7% (23×) | −94.0% (17×) | −93.7% (16×) |
| `half_match`: half `no_match`, half `selective` | 371–375 ms | −9.2% | −8.7% | −8.2% | −8.4% |
| `selective`: every row matches the 1–4 smallest buffered keys | 694–699 ms | −2.9% | −3.9% | −3.6% | −3.2% |
| `all_match`: every row matches every buffered key | 162–163 ms | +0.1% | −0.6% | −0.0% | +0.3% |
## What is the testing strategy for this PR?
- `first_match_agrees_with_linear_scan` (`utils.rs`): exhaustive over every range, answer and start position up to 40. It checks the result against a linear scan and bounds the number of comparisons by `⌈log2(hi − lo + 1)⌉`.
- `matchable_rows_agrees_with_scan` (`classic_join.rs`): the pre-sort check against a brute-force version of the scan's own definition of a match. It covers 12 key types, 4 operators, and a normal, all-NULL and empty buffered side.
- The key types: Int32, Float64 with `±0.0`/NaN/`±inf`, Utf8, Utf8View, Binary, Dictionary, Decimal128, Date32, Timestamp, Boolean, and two List cases with NULL elements.
- With the nested-key branch removed, this test fails.
- `join_right_less_than_signed_zero_prefilter_agrees_with_scan`: end to end with `-0.0`/`+0.0` keys.
- Existing tests:
- all PWMJ unit tests;
- the NLJ differential fuzz test `fuzz_pwmj_matches_nested_loop` (`--features extended_tests`), covering Inner/Left/Right/Full, NULL keys, small batches and multiple partitions;
- the PWMJ and join sqllogictests.
## Are there any user-facing changes?
No API or configuration changes.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4156141966
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -456,126 +494,49 @@ fn resolve_classic_join(
)?;
let mut buffer_idx = batch_process_state.start_buffer_idx;
- let mut stream_idx = batch_process_state.start_stream_idx;
+ let stream_idx = batch_process_state.start_stream_idx;
+ // NULL keys never match and sort first, so the scan starts past the buffered ones.
+ // Streamed NULL keys never get here: `matchable_rows` settled them before the sort.
+ debug_assert_eq!(stream_values[0].null_count(), 0);
if !batch_process_state.processed_null_count {
- let buffered_null_idx = buffered_side.buffered_data.values().null_count();
- let stream_null_idx = stream_values[0].null_count();
- buffer_idx = buffered_null_idx;
- stream_idx = stream_null_idx;
+ buffer_idx = buffered_side.buffered_data.values().null_count();
batch_process_state.processed_null_count = true;
-
- // The scan below starts past the streamed side's NULL-keyed rows, which
- // sit at the front (`nulls_first`). A NULL join key never matches under
- // `NullEqualsNothing`, so for `Right`/`Full` those rows are unmatched and
- // must still be emitted; record them here since the scan will skip them.
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- for row_idx in 0..stream_null_idx as u32 {
- batch_process_state.unmatched_indices.append_value(row_idx);
- }
- }
}
- // Our buffer_idx variable allows us to start probing on the buffered side where we last matched
- // in the previous stream row.
- for row_idx in stream_idx..stream_batch.batch.num_rows() {
- while buffer_idx < buffered_len {
- let compare = cmp.compare(row_idx, buffer_idx);
-
- // If we find a match we append all indices and move to the next stream row index
- match operator {
- Operator::Gt | Operator::Lt => {
- if compare == Ordering::Less {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
-
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- batch_process_state.output_batches.push_batch(batch)?;
-
- // Flush batch and update pointers if we have a completed batch
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
+ let match_on_equal = matches_on_equal(operator)?;
- break;
- }
- }
- Operator::GtEq | Operator::LtEq => {
- if matches!(compare, Ordering::Equal | Ordering::Less) {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- // Flush batch and update pointers if we have a completed batch
- batch_process_state.output_batches.push_batch(batch)?;
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
-
- break;
- }
- }
- _ => {
- return internal_err!(
- "PiecewiseMergeJoin should not contain operator, {}",
- operator
- );
- }
- }
-
- // Increment buffer_idx after every row
- buffer_idx += 1;
- }
-
- // If a match was not found for the current stream row index the stream indice is appended
- // to the unmatched indices to be flushed later.
- if matches!(join_type, JoinType::Right | JoinType::Full)
- && !batch_process_state.found
- {
- batch_process_state
- .unmatched_indices
- .append_value(row_idx as u32);
- }
-
- batch_process_state.found = false;
- }
-
- // Flushed all unmatched indices on the streamed side
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- let batch = create_unmatched_batch(
- &mut batch_process_state.unmatched_indices,
+ // `buffer_idx` resumes where the previous stream row's first match was: rows are sorted
+ // so that each one's first match is at or after the previous one's, which bounds the
+ // search below to `[buffer_idx, buffered_len)`.
+ //
+ // Every row here matches: `matchable_rows` kept only rows that match the last buffered
+ // row, and settled the rest (as unmatched for `Right`/`Full`) before the sort.
+ for row_idx in stream_idx..stream_batch.batch.num_rows() {
+ buffer_idx = first_match(buffer_idx, buffered_len, |idx| {
+ is_match(cmp.compare(row_idx, idx), match_on_equal)
+ });
+ debug_assert!(buffer_idx < buffered_len);
Review Comment:
Maybe internal error here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4157589052
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1227,313 @@ mod tests {
Ok(())
}
+ /// The pre-sort check that settles never-matching streamed rows must compare keys
+ /// the way the scan's `JoinKeyComparator` does, which normalizes `-0.0` to `+0.0`.
+ /// Under IEEE 754 total order (arrow's raw kernels, and the sort) `-0.0 < +0.0`
+ /// holds, so a check built on that would let the `+0.0` row through as a candidate
+ /// that the scan then rejects; with SQL semantics both rows are unmatched.
+ #[tokio::test]
+ async fn join_right_less_than_signed_zero_prefilter_agrees_with_scan() -> Result<()> {
Review Comment:
This overlaps the `float64` case of `matchable_rows_agrees_with_scan` and the `f64` pass of `fuzz_pwmj_matches_nested_loop`. A classic `RIGHT`/`FULL` case in `piecewise_merge_join_matrix.slt` Part 1 would replace it and be checked against `NestedLoopJoin` at batch sizes 1, 2, 100 and 8192, instead of a hard-coded snapshot. The matrix only has `-0.0` for existence joins today. The same file could take one unsorted streamed batch mixing matching, non-matching and NULL keys to cover the `positions` remap. I tried both cases across the matrix locally and they pass on this head.
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -456,126 +494,49 @@ fn resolve_classic_join(
)?;
let mut buffer_idx = batch_process_state.start_buffer_idx;
- let mut stream_idx = batch_process_state.start_stream_idx;
+ let stream_idx = batch_process_state.start_stream_idx;
+ // NULL keys never match and sort first, so the scan starts past the buffered ones.
+ // Streamed NULL keys never get here: `matchable_rows` settled them before the sort.
+ debug_assert_eq!(stream_values[0].null_count(), 0);
if !batch_process_state.processed_null_count {
Review Comment:
With streamed NULLs gone from the scan, `processed_null_count` only seeds `buffer_idx` with the buffered NULL count once per stream batch. Seeding `start_buffer_idx` right after `batch_process_state.reset()` in `fetch_stream_batch` removes the flag, its reset and this first-call branch. I tried it locally and the PWMJ unit tests and the fuzz still pass.
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1227,313 @@ mod tests {
Ok(())
}
+ /// The pre-sort check that settles never-matching streamed rows must compare keys
+ /// the way the scan's `JoinKeyComparator` does, which normalizes `-0.0` to `+0.0`.
+ /// Under IEEE 754 total order (arrow's raw kernels, and the sort) `-0.0 < +0.0`
+ /// holds, so a check built on that would let the `+0.0` row through as a candidate
+ /// that the scan then rejects; with SQL semantics both rows are unmatched.
+ #[tokio::test]
+ async fn join_right_less_than_signed_zero_prefilter_agrees_with_scan() -> Result<()> {
+ let float_exec =
+ |a: &str, b: &str, keys: Vec<f64>| -> Result<Arc<dyn ExecutionPlan>> {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new(a, DataType::Int32, false),
+ Field::new(b, DataType::Float64, false),
+ ]));
+ let ids = (0..keys.len() as i32).collect::<Vec<_>>();
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(arrow::array::Int32Array::from(ids)),
+ Arc::new(arrow::array::Float64Array::from(keys)),
+ ],
+ )?;
+ Ok(TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?)
+ };
+ let left = float_exec("a1", "b1", vec![-0.0])?;
+ let right = float_exec("a2", "b2", vec![0.0, -1.0])?;
+ let on = (
+ Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
+ Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
+ );
+
+ let (_, batches, _) =
+ join_collect(left, right, on, Operator::Lt, JoinType::Right).await?;
+
+ assert_snapshot!(batches_to_string(&batches), @r"
+ +----+----+----+------+
+ | a1 | b1 | a2 | b2 |
+ +----+----+----+------+
+ | | | 0 | 0.0 |
+ | | | 1 | -1.0 |
+ +----+----+----+------+
+ ");
+ Ok(())
+ }
+
+ /// `matchable_rows` against the scan's own definition of a match -- some non-NULL
+ /// buffered row `idx` with `is_match(cmp.compare(row, idx))` under the scan's
+ /// `JoinKeyComparator` -- for every operator and every kind of key it dispatches on:
+ /// flat keys through `apply_cmp` (incl. signed zeros, NaN, strings, dictionaries) and
+ /// nested keys with NULL elements through the comparator. Each is also checked against
+ /// an all-NULL and an empty buffered side.
+ #[test]
+ fn matchable_rows_agrees_with_scan() -> Result<()> {
+ use arrow::array::{
+ BinaryArray, BooleanArray, Decimal128Array, DictionaryArray, Float64Array,
+ Int32Array, ListArray, StringArray, StringViewArray,
+ TimestampMicrosecondArray,
+ };
+ use arrow::datatypes::Int32Type;
+
+ let strings =
+ |v: &[Option<&str>]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
+ let cases: Vec<(&str, ArrayRef, ArrayRef)> = vec![
+ (
+ "int32",
+ Arc::new(Int32Array::from(vec![
+ Some(5),
+ None,
+ Some(1),
+ Some(9),
+ Some(3),
+ ])),
+ Arc::new(Int32Array::from(vec![
+ Some(0),
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(5),
+ Some(9),
+ Some(10),
+ None,
+ ])),
+ ),
+ (
+ "float64",
+ Arc::new(Float64Array::from(vec![
+ Some(0.0),
+ Some(-0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ None,
+ ])),
+ Arc::new(Float64Array::from(vec![
+ Some(-0.0),
+ Some(0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ Some(-1.0),
+ Some(2.0),
+ Some(f64::INFINITY),
+ Some(f64::NEG_INFINITY),
+ None,
+ ])),
+ ),
+ (
+ "utf8",
+ strings(&[Some("b"), Some(""), Some("d"), None]),
+ strings(&[
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("c"),
+ Some("d"),
+ Some("e"),
+ None,
+ ]),
+ ),
+ (
+ "utf8_view",
+ Arc::new(StringViewArray::from(vec![
+ Some("b"),
+ Some(""),
+ Some("d"),
+ None,
+ ])),
+ Arc::new(StringViewArray::from(vec![
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("d"),
+ Some("e"),
+ None,
+ ])),
+ ),
+ (
+ "binary",
+ Arc::new(BinaryArray::from(vec![Some(&b"b"[..]), Some(b""), None])),
+ Arc::new(BinaryArray::from(vec![
+ Some(&b""[..]),
+ Some(b"a"),
+ Some(b"b"),
+ Some(b"c"),
+ None,
+ ])),
+ ),
+ (
+ "dictionary",
+ Arc::new(
+ vec![Some("b"), None, Some("d"), Some("b")]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ Arc::new(
+ vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e"), None]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ ),
+ (
+ "decimal128",
+ Arc::new(
+ Decimal128Array::from(vec![Some(150), None, Some(-25)])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ Arc::new(
+ Decimal128Array::from(vec![
+ Some(-26),
+ Some(-25),
+ Some(0),
+ Some(150),
+ Some(151),
+ None,
+ ])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ ),
+ (
+ "date32",
+ Arc::new(Date32Array::from(vec![Some(10), None, Some(20)])),
+ Arc::new(Date32Array::from(vec![
+ Some(9),
+ Some(10),
+ Some(15),
+ Some(20),
+ Some(21),
+ None,
+ ])),
+ ),
+ (
+ "timestamp_us",
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-5),
+ Some(7),
+ None,
+ ])),
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-6),
+ Some(-5),
+ Some(7),
+ Some(8),
+ None,
+ ])),
+ ),
+ (
+ "boolean",
+ Arc::new(BooleanArray::from(vec![Some(true), None])),
+ Arc::new(BooleanArray::from(vec![Some(false), Some(true), None])),
+ ),
+ (
+ "list_with_null_elements",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![None]),
+ Some(vec![Some(1), Some(2)]),
+ Some(vec![]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ Some(vec![Some(5)]),
+ Some(vec![]),
+ Some(vec![None, Some(1)]),
+ Some(vec![Some(5), None]),
+ None,
+ ])),
+ ),
+ (
+ // No empty list, so the extreme key has a first element to compare
+ // against the streamed NULL elements.
+ "list_null_elements_vs_extreme",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![Some(3)]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(3), None]),
+ Some(vec![Some(4)]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ None,
+ ])),
+ ),
+ ];
+
+ for (name, buffered, streamed) in cases {
+ let all_null = new_null_array(buffered.data_type(), 3);
+ let empty = buffered.slice(0, 0);
+ for (side, buffered) in
+ [("full", buffered), ("all_null", all_null), ("empty", empty)]
+ {
+ for operator in
+ [Operator::Lt, Operator::LtEq, Operator::Gt, Operator::GtEq]
+ {
+ // As `PiecewiseMergeJoinExec::try_new` sorts both sides.
+ let sort_options = match operator {
+ Operator::Lt | Operator::LtEq => SortOptions::new(true, true),
+ _ => SortOptions::new(false, true),
+ };
+ let sorted = take(
+ buffered.as_ref(),
+ &sort_to_indices(buffered.as_ref(), Some(sort_options), None)?,
+ None,
+ )?;
+ let extreme = match sorted.len().checked_sub(1) {
Review Comment:
This copies the extreme computation from `collect_buffered_side`, so the test would not notice a bug in the production version. A small shared function, for example `fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>>`, would remove the duplicate and make the test exercise the real code.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf:settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#issuecomment-5876270469
Benchmark PR: https://github.com/apache/datafusion/pull/25839
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4166675528
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -631,18 +587,111 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last key of the sorted buffered side, or `None` when it is empty or every key is NULL:
+// NULLs sort first, so the last key is NULL only when every buffered key is.
+fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>> {
+ Ok(match values.len().checked_sub(1) {
+ Some(last) if values.is_valid(last) => Some(ColumnarValue::Scalar(
+ ScalarValue::try_from_array(values, last)?,
Review Comment:
For `Dictionary(_, Float*)` keys the pre-filter disagrees with the scan on `-0.0`. `apply_cmp` normalizes the streamed array (dictionary values included), but `normalize_float_zero_scalar` skips `ScalarValue::Dictionary`, so the extreme keeps `-0.0` under total order while `JoinKeyComparator` treats it as `0.0`. This gives an internal error when the filter lets a row through, and wrong rows when it drops a real match. The base commit returns the right results.
Repro:
```sql
set datafusion.optimizer.enable_piecewise_merge_join = true;
CREATE TABLE dl AS SELECT * FROM (VALUES (1, arrow_cast(-0.0, 'Dictionary(Int32, Float64)')), (2, arrow_cast(0.5, 'Dictionary(Int32, Float64)'))) t(lid, lv);
CREATE TABLE dr AS SELECT * FROM (VALUES (1, arrow_cast(0.0, 'Dictionary(Int32, Float64)')), (2, arrow_cast(0.25, 'Dictionary(Int32, Float64)'))) t(rid, rv);
SELECT * FROM dl JOIN dr ON dl.lv < dr.rv;
-- Internal error: PiecewiseMergeJoin: streamed row 1 reached the scan without a match
CREATE TABLE dl2 AS SELECT * FROM (VALUES (1, arrow_cast(-1.0, 'Dictionary(Int32, Float64)')), (2, arrow_cast(-0.0, 'Dictionary(Int32, Float64)'))) t(lid, lv);
CREATE TABLE dr2 AS SELECT * FROM (VALUES (1, arrow_cast(0.0, 'Dictionary(Int32, Float64)'))) t(rid, rv);
SELECT * FROM dl2 RIGHT JOIN dr2 ON dl2.lv >= dr2.rv;
-- got `NULL NULL 1 0`, expected `2 0 1 0` (NLJ and the base commit agree)
```
Fix (normalize the extreme before taking it as a scalar):
```diff
+use datafusion_common::utils::normalize_float_zero;
```
```diff
fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>> {
Ok(match values.len().checked_sub(1) {
- Some(last) if values.is_valid(last) => Some(ColumnarValue::Scalar(
- ScalarValue::try_from_array(values, last)?,
- )),
+ // `apply_cmp` normalizes `-0.0` only in flat float scalars, not inside a
+ // `ScalarValue::Dictionary`, so normalize the key before taking it.
+ Some(last) if values.is_valid(last) => {
+ let extreme = normalize_float_zero(&values.slice(last, 1));
+ Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &extreme, 0,
+ )?))
+ }
_ => None,
})
}
```
Cases for `matchable_rows_agrees_with_scan`. They fail on the current head (`dictionary_float64_neg_zero_min/full <: streamed row 0`) and pass with the fix:
```rs
(
// `-0.0` as the buffered extreme inside a dictionary: the smallest
// key for `<`/`<=`, the largest for `>`/`>=`.
"dictionary_float64_neg_zero_min",
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1]),
Arc::new(Float64Array::from(vec![-0.0, 0.5])),
)),
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1, 2]),
Arc::new(Float64Array::from(vec![0.0, -0.0, 0.25])),
)),
),
(
"dictionary_float64_neg_zero_max",
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1]),
Arc::new(Float64Array::from(vec![-1.0, -0.0])),
)),
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1, 2]),
Arc::new(Float64Array::from(vec![0.0, -0.0, -0.5])),
)),
),
```
The root cause, `normalize_float_zero_scalar` not recursing into `ScalarValue::Dictionary`, is already on main: `SELECT arrow_cast(0.0, 'Dictionary(Int32, Float64)') > arrow_cast(-0.0, 'Dictionary(Int32, Float64)')` returns `true`. Worth filing on its own; fixing it there would also cover this.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4157591496
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -456,126 +494,49 @@ fn resolve_classic_join(
)?;
let mut buffer_idx = batch_process_state.start_buffer_idx;
- let mut stream_idx = batch_process_state.start_stream_idx;
+ let stream_idx = batch_process_state.start_stream_idx;
+ // NULL keys never match and sort first, so the scan starts past the buffered ones.
+ // Streamed NULL keys never get here: `matchable_rows` settled them before the sort.
+ debug_assert_eq!(stream_values[0].null_count(), 0);
if !batch_process_state.processed_null_count {
- let buffered_null_idx = buffered_side.buffered_data.values().null_count();
- let stream_null_idx = stream_values[0].null_count();
- buffer_idx = buffered_null_idx;
- stream_idx = stream_null_idx;
+ buffer_idx = buffered_side.buffered_data.values().null_count();
batch_process_state.processed_null_count = true;
-
- // The scan below starts past the streamed side's NULL-keyed rows, which
- // sit at the front (`nulls_first`). A NULL join key never matches under
- // `NullEqualsNothing`, so for `Right`/`Full` those rows are unmatched and
- // must still be emitted; record them here since the scan will skip them.
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- for row_idx in 0..stream_null_idx as u32 {
- batch_process_state.unmatched_indices.append_value(row_idx);
- }
- }
}
- // Our buffer_idx variable allows us to start probing on the buffered side where we last matched
- // in the previous stream row.
- for row_idx in stream_idx..stream_batch.batch.num_rows() {
- while buffer_idx < buffered_len {
- let compare = cmp.compare(row_idx, buffer_idx);
-
- // If we find a match we append all indices and move to the next stream row index
- match operator {
- Operator::Gt | Operator::Lt => {
- if compare == Ordering::Less {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
-
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- batch_process_state.output_batches.push_batch(batch)?;
-
- // Flush batch and update pointers if we have a completed batch
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
+ let match_on_equal = matches_on_equal(operator)?;
- break;
- }
- }
- Operator::GtEq | Operator::LtEq => {
- if matches!(compare, Ordering::Equal | Ordering::Less) {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- // Flush batch and update pointers if we have a completed batch
- batch_process_state.output_batches.push_batch(batch)?;
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
-
- break;
- }
- }
- _ => {
- return internal_err!(
- "PiecewiseMergeJoin should not contain operator, {}",
- operator
- );
- }
- }
-
- // Increment buffer_idx after every row
- buffer_idx += 1;
- }
-
- // If a match was not found for the current stream row index the stream indice is appended
- // to the unmatched indices to be flushed later.
- if matches!(join_type, JoinType::Right | JoinType::Full)
- && !batch_process_state.found
- {
- batch_process_state
- .unmatched_indices
- .append_value(row_idx as u32);
- }
-
- batch_process_state.found = false;
- }
-
- // Flushed all unmatched indices on the streamed side
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- let batch = create_unmatched_batch(
- &mut batch_process_state.unmatched_indices,
+ // `buffer_idx` resumes where the previous stream row's first match was: rows are sorted
+ // so that each one's first match is at or after the previous one's, which bounds the
+ // search below to `[buffer_idx, buffered_len)`.
+ //
+ // Every row here matches: `matchable_rows` kept only rows that match the last buffered
+ // row, and settled the rest (as unmatched for `Right`/`Full`) before the sort.
+ for row_idx in stream_idx..stream_batch.batch.num_rows() {
+ buffer_idx = first_match(buffer_idx, buffered_len, |idx| {
+ is_match(cmp.compare(row_idx, idx), match_on_equal)
+ });
+ debug_assert!(buffer_idx < buffered_len);
Review Comment:
+1. In release builds nothing fails here. With `buffer_idx == buffered_len`, `count` is 0 and an empty batch is pushed, so for `Right`/`Full` the streamed row is neither matched nor emitted as unmatched and is silently lost. The `debug_assert_eq!` on streamed NULLs a few lines up has the same shape. A NULL key that reached the scan compares `Less` than every non-NULL buffered key (`nulls_first`), so it would match all of them. Both checks are cheap enough for `internal_err!`.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4158960703
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -456,126 +494,49 @@ fn resolve_classic_join(
)?;
let mut buffer_idx = batch_process_state.start_buffer_idx;
- let mut stream_idx = batch_process_state.start_stream_idx;
+ let stream_idx = batch_process_state.start_stream_idx;
+ // NULL keys never match and sort first, so the scan starts past the buffered ones.
+ // Streamed NULL keys never get here: `matchable_rows` settled them before the sort.
+ debug_assert_eq!(stream_values[0].null_count(), 0);
if !batch_process_state.processed_null_count {
Review Comment:
Addressed in a15bddae28202bbbd32f902aea1815d7acda025b
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4235903494
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -633,18 +595,121 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last non-null key of the sorted buffered side, or `None` when it is empty or every key
+// is NULL. NULLs sort last for `<`/`<=`, so this is not simply the last key. Logical, as a
+// run-end encoded or `Null`-typed NULL has no physical null buffer.
+fn buffered_extreme(
+ values: &ArrayRef,
+ sort_options: SortOptions,
+) -> Result<Option<ColumnarValue>> {
+ let (start, end) = non_null_range(values.as_ref(), sort_options);
+ if start == end {
+ return Ok(None);
+ }
+ let last = values.slice(end - 1, 1);
+ // `apply_cmp` normalizes `-0.0` only in flat float scalars, not inside a
+ // `ScalarValue::Dictionary`, so normalize the key before taking it.
+ let extreme = normalize_float_zero(&last);
+ Ok(Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &extreme, 0,
+ )?)))
+}
+
+// Which rows of `stream_values` can match at least one buffered row.
+//
+// Every match set is a suffix `[k, non_null_end)` of the sorted buffered side's non-null keys,
+// so a streamed row matches anything at all iff it matches the last of them, `buffered_extreme`
+// (`None` when no buffered key is non-null, so nothing can match). A NULL on either side
+// compares to NULL, which is no match.
+//
+// This must agree exactly with the scan's `JoinKeyComparator`, or it would change which rows
+// match. One vectorized `apply_cmp` does, nested keys included: it normalizes `-0.0` to
+// `+0.0` as the comparator does, and orders NULL elements inside a nested key the same way.
+fn matchable_rows(
+ stream_values: &ArrayRef,
+ buffered_values: &ArrayRef,
+ buffered_extreme: Option<&ColumnarValue>,
+ operator: Operator,
+ sort_options: SortOptions,
+) -> Result<BooleanArray> {
+ let num_rows = stream_values.len();
+ let Some(extreme) = buffered_extreme else {
+ return Ok(BooleanArray::new(BooleanBuffer::new_unset(num_rows), None));
+ };
+
+ // Run-end encoded keys are decided with the scan's own comparator: arrow's run-end
+ // comparison kernel overflows on an empty batch sliced past its first run, which the
+ // scan never reaches.
+ if matches!(stream_values.data_type(), DataType::RunEndEncoded(_, _)) {
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(stream_values)],
+ &[Arc::clone(buffered_values)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ let last = non_null_range(buffered_values.as_ref(), sort_options).1 - 1;
+ // Logical NULLs: a run-end encoded NULL has no physical null buffer.
+ let nulls = stream_values.logical_nulls();
+ let matchable = BooleanBuffer::collect_bool(num_rows, |row| {
+ nulls.as_ref().is_none_or(|nulls| nulls.is_valid(row))
+ && is_match(cmp.compare(row, last), match_on_equal)
+ });
+ return Ok(BooleanArray::new(matchable, None));
+ }
+
+ // The predicate is oriented `buffered OP streamed`.
+ let result = apply_cmp(
+ operator,
+ extreme,
+ &ColumnarValue::Array(Arc::clone(stream_values)),
+ )?
+ .into_array(num_rows)?;
+ let result = result.as_boolean();
Review Comment:
`apply_cmp_for_nested` masks only physical nulls (`l.nulls()` / `r.nulls()`). For `Dictionary<_, List>` those are the keys' nulls, so a valid key pointing at a NULL list passes as matchable and then hits the scan guard: `Internal error: PiecewiseMergeJoin: streamed NULL keys must be settled before the scan.` (Right join, `>`). The previous head sent `is_nested()` types, dictionary-of-nested included, through the comparator path, which used `logical_nulls()`.
Repro: add this to `matchable_rows_agrees_with_scan`. It fails on this head with `dictionary_list_null_values/full >: streamed row 1`:
```rs
(
// A valid key pointing at a NULL list: logically NULL, physically valid.
"dictionary_list_null_values",
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1, 2]),
Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
Some(vec![Some(5)]),
None,
Some(vec![Some(1)]),
])),
)),
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![Some(0), Some(1), Some(2), Some(3), None]),
Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
Some(vec![Some(2)]),
None,
Some(vec![Some(6)]),
Some(vec![Some(0)]),
])),
)),
),
```
Fix (passes the case above and the end-to-end join):
```diff
let result = result.as_boolean();
- Ok(if result.null_count() > 0 {
+ let matchable = if result.null_count() > 0 {
prep_null_mask_filter(result)
} else {
result.clone()
- })
+ };
+ // The nested `apply_cmp` masks only physical NULLs, so a dictionary key pointing at a
+ // NULL nested value would pass.
+ Ok(match stream_values.logical_nulls() {
+ Some(nulls) => BooleanArray::new(matchable.values() & nulls.inner(), None),
+ None => matchable,
+ })
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4236524751
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -633,18 +595,121 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last non-null key of the sorted buffered side, or `None` when it is empty or every key
+// is NULL. NULLs sort last for `<`/`<=`, so this is not simply the last key. Logical, as a
+// run-end encoded or `Null`-typed NULL has no physical null buffer.
+fn buffered_extreme(
+ values: &ArrayRef,
+ sort_options: SortOptions,
+) -> Result<Option<ColumnarValue>> {
+ let (start, end) = non_null_range(values.as_ref(), sort_options);
+ if start == end {
+ return Ok(None);
+ }
+ let last = values.slice(end - 1, 1);
+ // `apply_cmp` normalizes `-0.0` only in flat float scalars, not inside a
+ // `ScalarValue::Dictionary`, so normalize the key before taking it.
+ let extreme = normalize_float_zero(&last);
+ Ok(Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &extreme, 0,
+ )?)))
+}
+
+// Which rows of `stream_values` can match at least one buffered row.
+//
+// Every match set is a suffix `[k, non_null_end)` of the sorted buffered side's non-null keys,
+// so a streamed row matches anything at all iff it matches the last of them, `buffered_extreme`
+// (`None` when no buffered key is non-null, so nothing can match). A NULL on either side
+// compares to NULL, which is no match.
+//
+// This must agree exactly with the scan's `JoinKeyComparator`, or it would change which rows
+// match. One vectorized `apply_cmp` does, nested keys included: it normalizes `-0.0` to
+// `+0.0` as the comparator does, and orders NULL elements inside a nested key the same way.
+fn matchable_rows(
+ stream_values: &ArrayRef,
+ buffered_values: &ArrayRef,
+ buffered_extreme: Option<&ColumnarValue>,
+ operator: Operator,
+ sort_options: SortOptions,
+) -> Result<BooleanArray> {
+ let num_rows = stream_values.len();
+ let Some(extreme) = buffered_extreme else {
+ return Ok(BooleanArray::new(BooleanBuffer::new_unset(num_rows), None));
+ };
+
+ // Run-end encoded keys are decided with the scan's own comparator: arrow's run-end
+ // comparison kernel overflows on an empty batch sliced past its first run, which the
+ // scan never reaches.
+ if matches!(stream_values.data_type(), DataType::RunEndEncoded(_, _)) {
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(stream_values)],
+ &[Arc::clone(buffered_values)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ let last = non_null_range(buffered_values.as_ref(), sort_options).1 - 1;
+ // Logical NULLs: a run-end encoded NULL has no physical null buffer.
+ let nulls = stream_values.logical_nulls();
+ let matchable = BooleanBuffer::collect_bool(num_rows, |row| {
+ nulls.as_ref().is_none_or(|nulls| nulls.is_valid(row))
+ && is_match(cmp.compare(row, last), match_on_equal)
+ });
+ return Ok(BooleanArray::new(matchable, None));
+ }
+
+ // The predicate is oriented `buffered OP streamed`.
+ let result = apply_cmp(
+ operator,
+ extreme,
+ &ColumnarValue::Array(Arc::clone(stream_values)),
+ )?
+ .into_array(num_rows)?;
+ let result = result.as_boolean();
Review Comment:
Addressed in 35fa8f25fda5d87d0c7182425d01486eaed75d4a
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf:settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#issuecomment-5910636616
@comphead can you help in reviewing this PR.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4178689803
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1245,347 @@ mod tests {
Ok(())
}
+ /// An empty streamed batch of run-end encoded keys, sliced past the first run, must not
+ /// reach arrow's run-end comparison kernel, which overflows on it.
+ #[tokio::test]
+ async fn join_right_run_end_encoded_keys_empty_sliced_batch() -> Result<()> {
+ use arrow::array::{Int32Array, RunArray};
+ use arrow::datatypes::Int32Type;
+
+ let ree_exec = |ids: &str,
+ keys: &str,
+ run_ends: Vec<i32>,
+ values: Vec<Option<i32>>,
+ slices: &[(usize, usize)]|
+ -> Result<Arc<dyn ExecutionPlan>> {
+ let keys_array = RunArray::<Int32Type>::try_new(
+ &Int32Array::from(run_ends),
+ &Int32Array::from(values),
+ )?;
+ let schema = Arc::new(Schema::new(vec![
+ Field::new(ids, DataType::Int32, false),
+ Field::new(keys, keys_array.data_type().clone(), true),
+ ]));
+ let len = keys_array.len() as i32;
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(Int32Array::from((0..len).collect::<Vec<_>>())),
+ Arc::new(keys_array),
+ ],
+ )?;
+ let batches = slices
+ .iter()
+ .map(|&(offset, len)| batch.slice(offset, len))
+ .collect::<Vec<_>>();
+ Ok(TestMemoryExec::try_new_exec(&[batches], schema, None)?)
+ };
+ // Buffered keys sorted for `<` (descending, NULLs first): {NULL, 5, 5, 1, 1}.
+ let left = ree_exec(
+ "a1",
+ "b1",
+ vec![1, 3, 5],
+ vec![None, Some(5), Some(1)],
+ &[(0, 5)],
+ )?;
+ // Streamed keys {NULL, 2, 2, 0, 6}, as batches of 3, 0 and 2 rows. The empty one
+ // starts at offset 3, past the end of the first run.
+ let right = ree_exec(
+ "a2",
+ "b2",
+ vec![1, 3, 4, 5],
+ vec![None, Some(2), Some(0), Some(6)],
+ &[(0, 3), (3, 0), (3, 2)],
+ )?;
+ let on = (
+ Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
+ Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
+ );
+
+ join_collect(left, right, on, Operator::Lt, JoinType::Right).await?;
+ Ok(())
+ }
+
+ /// `matchable_rows` against the scan's own definition of a match -- some non-NULL
+ /// buffered row `idx` with `is_match(cmp.compare(row, idx))` under the scan's
+ /// `JoinKeyComparator` -- for every operator and every kind of key it dispatches on:
+ /// flat keys through `apply_cmp` (incl. signed zeros, NaN, strings, dictionaries) and
+ /// nested keys with NULL elements through the comparator. Each is also checked against
+ /// an all-NULL and an empty buffered side.
+ #[test]
+ fn matchable_rows_agrees_with_scan() -> Result<()> {
+ use arrow::array::{
+ BinaryArray, BooleanArray, Decimal128Array, DictionaryArray, Float64Array,
+ Int32Array, ListArray, StringArray, StringViewArray,
+ TimestampMicrosecondArray,
+ };
+ use arrow::datatypes::Int32Type;
+
+ let strings =
+ |v: &[Option<&str>]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
+ let cases: Vec<(&str, ArrayRef, ArrayRef)> = vec![
+ (
+ "int32",
+ Arc::new(Int32Array::from(vec![
+ Some(5),
+ None,
+ Some(1),
+ Some(9),
+ Some(3),
+ ])),
+ Arc::new(Int32Array::from(vec![
+ Some(0),
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(5),
+ Some(9),
+ Some(10),
+ None,
+ ])),
+ ),
+ (
+ "float64",
+ Arc::new(Float64Array::from(vec![
+ Some(0.0),
+ Some(-0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ None,
+ ])),
+ Arc::new(Float64Array::from(vec![
+ Some(-0.0),
+ Some(0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ Some(-1.0),
+ Some(2.0),
+ Some(f64::INFINITY),
+ Some(f64::NEG_INFINITY),
+ None,
+ ])),
+ ),
+ (
+ "utf8",
+ strings(&[Some("b"), Some(""), Some("d"), None]),
+ strings(&[
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("c"),
+ Some("d"),
+ Some("e"),
+ None,
+ ]),
+ ),
+ (
+ "utf8_view",
+ Arc::new(StringViewArray::from(vec![
+ Some("b"),
+ Some(""),
+ Some("d"),
+ None,
+ ])),
+ Arc::new(StringViewArray::from(vec![
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("d"),
+ Some("e"),
+ None,
+ ])),
+ ),
+ (
+ "binary",
+ Arc::new(BinaryArray::from(vec![Some(&b"b"[..]), Some(b""), None])),
+ Arc::new(BinaryArray::from(vec![
+ Some(&b""[..]),
+ Some(b"a"),
+ Some(b"b"),
+ Some(b"c"),
+ None,
+ ])),
+ ),
+ (
+ "dictionary",
+ Arc::new(
+ vec![Some("b"), None, Some("d"), Some("b")]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ Arc::new(
+ vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e"), None]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ ),
+ (
+ // `-0.0` as the buffered extreme inside a dictionary: the smallest
+ // key for `<`/`<=`, the largest for `>`/`>=`.
+ "dictionary_float64_neg_zero_min",
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1]),
+ Arc::new(Float64Array::from(vec![-0.0, 0.5])),
+ )),
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1, 2]),
+ Arc::new(Float64Array::from(vec![0.0, -0.0, 0.25])),
+ )),
+ ),
+ (
+ "dictionary_float64_neg_zero_max",
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1]),
+ Arc::new(Float64Array::from(vec![-1.0, -0.0])),
+ )),
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1, 2]),
+ Arc::new(Float64Array::from(vec![0.0, -0.0, -0.5])),
+ )),
+ ),
+ (
+ "decimal128",
+ Arc::new(
+ Decimal128Array::from(vec![Some(150), None, Some(-25)])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ Arc::new(
+ Decimal128Array::from(vec![
+ Some(-26),
+ Some(-25),
+ Some(0),
+ Some(150),
+ Some(151),
+ None,
+ ])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ ),
+ (
+ "date32",
+ Arc::new(Date32Array::from(vec![Some(10), None, Some(20)])),
+ Arc::new(Date32Array::from(vec![
+ Some(9),
+ Some(10),
+ Some(15),
+ Some(20),
+ Some(21),
+ None,
+ ])),
+ ),
+ (
+ "timestamp_us",
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-5),
+ Some(7),
+ None,
+ ])),
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-6),
+ Some(-5),
+ Some(7),
+ Some(8),
+ None,
+ ])),
+ ),
+ (
+ "boolean",
+ Arc::new(BooleanArray::from(vec![Some(true), None])),
+ Arc::new(BooleanArray::from(vec![Some(false), Some(true), None])),
+ ),
+ (
+ "list_with_null_elements",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![None]),
+ Some(vec![Some(1), Some(2)]),
+ Some(vec![]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ Some(vec![Some(5)]),
+ Some(vec![]),
+ Some(vec![None, Some(1)]),
+ Some(vec![Some(5), None]),
+ None,
+ ])),
+ ),
+ (
+ // No empty list, so the extreme key has a first element to compare
+ // against the streamed NULL elements.
+ "list_null_elements_vs_extreme",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![Some(3)]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(3), None]),
+ Some(vec![Some(4)]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ None,
+ ])),
+ ),
+ ];
+
+ for (name, buffered, streamed) in cases {
+ let all_null = new_null_array(buffered.data_type(), 3);
+ let empty = buffered.slice(0, 0);
+ for (side, buffered) in
+ [("full", buffered), ("all_null", all_null), ("empty", empty)]
+ {
+ for operator in
+ [Operator::Lt, Operator::LtEq, Operator::Gt, Operator::GtEq]
+ {
+ // As `PiecewiseMergeJoinExec::try_new` sorts both sides.
+ let sort_options = match operator {
+ Operator::Lt | Operator::LtEq => SortOptions::new(true, true),
+ _ => SortOptions::new(false, true),
+ };
+ let sorted = take(
+ buffered.as_ref(),
+ &sort_to_indices(buffered.as_ref(), Some(sort_options), None)?,
+ None,
+ )?;
+ let extreme = buffered_extreme(&sorted)?;
+
+ let actual = matchable_rows(
+ &streamed,
+ &sorted,
+ extreme.as_ref(),
+ operator,
+ sort_options,
+ )?;
+
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(&streamed)],
+ &[Arc::clone(&sorted)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ for row in 0..streamed.len() {
Review Comment:
Addressed in 2627267b525c9eece069b89c55afc8099be349dc
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #25840:
URL: https://github.com/apache/datafusion/pull/25840
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4175886838
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -631,18 +588,121 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last key of the sorted buffered side, or `None` when it is empty or every key is NULL:
+// NULLs sort first, so the last key is NULL only when every buffered key is.
+fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>> {
+ Ok(match values.len().checked_sub(1) {
+ // `apply_cmp` normalizes `-0.0` only in flat float scalars, not inside a
+ // `ScalarValue::Dictionary`, so normalize the key before taking it.
+ Some(last) if values.is_valid(last) => {
+ let extreme = normalize_float_zero(&values.slice(last, 1));
+ Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &extreme, 0,
+ )?))
+ }
+ _ => None,
+ })
+}
+
+// Which rows of `stream_values` can match at least one buffered row.
+//
+// Every match set is a suffix `[k, buffered_len)` of the sorted buffered side, so a streamed
+// row matches anything at all iff it matches the last buffered row, `buffered_extreme`
+// (`None` when no buffered key is non-null, so nothing can match). A NULL on either side
+// compares to NULL, which is no match.
+//
+// This must agree exactly with the scan's `JoinKeyComparator`, or it would change which rows
+// match. For flat keys one vectorized `apply_cmp` does: it normalizes `-0.0` to `+0.0` as the
+// comparator does. For nested keys it does not -- `apply_cmp` orders NULL elements inside a
+// key ascending, while the comparator applies the sort options (descending for `<`/`<=`) at
+// every level -- so those are decided with the scan's own comparator.
+fn matchable_rows(
+ stream_values: &ArrayRef,
+ buffered_values: &ArrayRef,
+ buffered_extreme: Option<&ColumnarValue>,
+ operator: Operator,
+ sort_options: SortOptions,
+) -> Result<BooleanArray> {
+ let num_rows = stream_values.len();
+ let Some(extreme) = buffered_extreme else {
+ return Ok(BooleanArray::new(BooleanBuffer::new_unset(num_rows), None));
+ };
+
+ // The comparator's nested ordering is itself wrong for `<`/`<=` (#25957). Once that is
+ // fixed, nested keys can go through `apply_cmp` too and this branch can be removed.
+ //
+ // Run-end encoded keys are decided here too: arrow's run-end comparison kernel overflows
+ // on an empty batch sliced past its first run, which the scan never reaches.
+ if stream_values.data_type().is_nested()
+ || matches!(stream_values.data_type(), DataType::RunEndEncoded(_, _))
+ {
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(stream_values)],
+ &[Arc::clone(buffered_values)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ let last = buffered_values.len() - 1;
+ let matchable = BooleanBuffer::collect_bool(num_rows, |row| {
+ stream_values.is_valid(row)
Review Comment:
`is_valid` only checks the physical null buffer, and a `RunArray` has none. So a run-end encoded NULL key passes as matchable, gets past the `null_count() > 0` guard at :492, and the scan joins it with every buffered row (`nulls_first` → `Less`). `main` gives the same rows, so this is fine as a follow-up. But `join_right_run_end_encoded_keys_empty_sliced_batch` already feeds such a NULL (a2 = 0) and asserts nothing.
```diff
let last = buffered_values.len() - 1;
+ // A run-end encoded NULL has no physical null buffer.
+ let nulls = stream_values.logical_nulls();
let matchable = BooleanBuffer::collect_bool(num_rows, |row| {
- stream_values.is_valid(row)
+ nulls.as_ref().is_none_or(|n| n.is_valid(row))
&& is_match(cmp.compare(row, last), match_on_equal)
});
```
```diff
- if stream_values[0].null_count() > 0 {
+ if stream_values[0].logical_null_count() > 0 {
```
In the test, after importing `batches_to_sort_string`. This fails on this head and passes with the fix:
```rs
let (_, batches, _) =
join_collect(left, right, on, Operator::Lt, JoinType::Right).await?;
// The NULL key (a2 = 0) and 0 (a2 = 3) match nothing.
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+
| a1 | b1 | a2 | b2 |
+----+----+----+----+
| | | 0 | |
| | | 3 | 0 |
| 1 | 5 | 4 | 6 |
| 2 | 5 | 4 | 6 |
| 3 | 1 | 1 | 2 |
| 3 | 1 | 2 | 2 |
| 3 | 1 | 4 | 6 |
| 4 | 1 | 1 | 2 |
| 4 | 1 | 2 | 2 |
| 4 | 1 | 4 | 6 |
+----+----+----+----+
");
```
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1245,347 @@ mod tests {
Ok(())
}
+ /// An empty streamed batch of run-end encoded keys, sliced past the first run, must not
+ /// reach arrow's run-end comparison kernel, which overflows on it.
+ #[tokio::test]
+ async fn join_right_run_end_encoded_keys_empty_sliced_batch() -> Result<()> {
+ use arrow::array::{Int32Array, RunArray};
+ use arrow::datatypes::Int32Type;
+
+ let ree_exec = |ids: &str,
+ keys: &str,
+ run_ends: Vec<i32>,
+ values: Vec<Option<i32>>,
+ slices: &[(usize, usize)]|
+ -> Result<Arc<dyn ExecutionPlan>> {
+ let keys_array = RunArray::<Int32Type>::try_new(
+ &Int32Array::from(run_ends),
+ &Int32Array::from(values),
+ )?;
+ let schema = Arc::new(Schema::new(vec![
+ Field::new(ids, DataType::Int32, false),
+ Field::new(keys, keys_array.data_type().clone(), true),
+ ]));
+ let len = keys_array.len() as i32;
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(Int32Array::from((0..len).collect::<Vec<_>>())),
+ Arc::new(keys_array),
+ ],
+ )?;
+ let batches = slices
+ .iter()
+ .map(|&(offset, len)| batch.slice(offset, len))
+ .collect::<Vec<_>>();
+ Ok(TestMemoryExec::try_new_exec(&[batches], schema, None)?)
+ };
+ // Buffered keys sorted for `<` (descending, NULLs first): {NULL, 5, 5, 1, 1}.
+ let left = ree_exec(
+ "a1",
+ "b1",
+ vec![1, 3, 5],
+ vec![None, Some(5), Some(1)],
+ &[(0, 5)],
+ )?;
+ // Streamed keys {NULL, 2, 2, 0, 6}, as batches of 3, 0 and 2 rows. The empty one
+ // starts at offset 3, past the end of the first run.
+ let right = ree_exec(
+ "a2",
+ "b2",
+ vec![1, 3, 4, 5],
+ vec![None, Some(2), Some(0), Some(6)],
+ &[(0, 3), (3, 0), (3, 2)],
+ )?;
+ let on = (
+ Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
+ Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
+ );
+
+ join_collect(left, right, on, Operator::Lt, JoinType::Right).await?;
+ Ok(())
+ }
+
+ /// `matchable_rows` against the scan's own definition of a match -- some non-NULL
+ /// buffered row `idx` with `is_match(cmp.compare(row, idx))` under the scan's
+ /// `JoinKeyComparator` -- for every operator and every kind of key it dispatches on:
+ /// flat keys through `apply_cmp` (incl. signed zeros, NaN, strings, dictionaries) and
+ /// nested keys with NULL elements through the comparator. Each is also checked against
+ /// an all-NULL and an empty buffered side.
+ #[test]
+ fn matchable_rows_agrees_with_scan() -> Result<()> {
+ use arrow::array::{
+ BinaryArray, BooleanArray, Decimal128Array, DictionaryArray, Float64Array,
+ Int32Array, ListArray, StringArray, StringViewArray,
+ TimestampMicrosecondArray,
+ };
+ use arrow::datatypes::Int32Type;
+
+ let strings =
+ |v: &[Option<&str>]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
+ let cases: Vec<(&str, ArrayRef, ArrayRef)> = vec![
+ (
+ "int32",
+ Arc::new(Int32Array::from(vec![
+ Some(5),
+ None,
+ Some(1),
+ Some(9),
+ Some(3),
+ ])),
+ Arc::new(Int32Array::from(vec![
+ Some(0),
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(5),
+ Some(9),
+ Some(10),
+ None,
+ ])),
+ ),
+ (
+ "float64",
+ Arc::new(Float64Array::from(vec![
+ Some(0.0),
+ Some(-0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ None,
+ ])),
+ Arc::new(Float64Array::from(vec![
+ Some(-0.0),
+ Some(0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ Some(-1.0),
+ Some(2.0),
+ Some(f64::INFINITY),
+ Some(f64::NEG_INFINITY),
+ None,
+ ])),
+ ),
+ (
+ "utf8",
+ strings(&[Some("b"), Some(""), Some("d"), None]),
+ strings(&[
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("c"),
+ Some("d"),
+ Some("e"),
+ None,
+ ]),
+ ),
+ (
+ "utf8_view",
+ Arc::new(StringViewArray::from(vec![
+ Some("b"),
+ Some(""),
+ Some("d"),
+ None,
+ ])),
+ Arc::new(StringViewArray::from(vec![
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("d"),
+ Some("e"),
+ None,
+ ])),
+ ),
+ (
+ "binary",
+ Arc::new(BinaryArray::from(vec![Some(&b"b"[..]), Some(b""), None])),
+ Arc::new(BinaryArray::from(vec![
+ Some(&b""[..]),
+ Some(b"a"),
+ Some(b"b"),
+ Some(b"c"),
+ None,
+ ])),
+ ),
+ (
+ "dictionary",
+ Arc::new(
+ vec![Some("b"), None, Some("d"), Some("b")]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ Arc::new(
+ vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e"), None]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ ),
+ (
+ // `-0.0` as the buffered extreme inside a dictionary: the smallest
+ // key for `<`/`<=`, the largest for `>`/`>=`.
+ "dictionary_float64_neg_zero_min",
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1]),
+ Arc::new(Float64Array::from(vec![-0.0, 0.5])),
+ )),
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1, 2]),
+ Arc::new(Float64Array::from(vec![0.0, -0.0, 0.25])),
+ )),
+ ),
+ (
+ "dictionary_float64_neg_zero_max",
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1]),
+ Arc::new(Float64Array::from(vec![-1.0, -0.0])),
+ )),
+ Arc::new(DictionaryArray::<Int32Type>::new(
+ Int32Array::from(vec![0, 1, 2]),
+ Arc::new(Float64Array::from(vec![0.0, -0.0, -0.5])),
+ )),
+ ),
+ (
+ "decimal128",
+ Arc::new(
+ Decimal128Array::from(vec![Some(150), None, Some(-25)])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ Arc::new(
+ Decimal128Array::from(vec![
+ Some(-26),
+ Some(-25),
+ Some(0),
+ Some(150),
+ Some(151),
+ None,
+ ])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ ),
+ (
+ "date32",
+ Arc::new(Date32Array::from(vec![Some(10), None, Some(20)])),
+ Arc::new(Date32Array::from(vec![
+ Some(9),
+ Some(10),
+ Some(15),
+ Some(20),
+ Some(21),
+ None,
+ ])),
+ ),
+ (
+ "timestamp_us",
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-5),
+ Some(7),
+ None,
+ ])),
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-6),
+ Some(-5),
+ Some(7),
+ Some(8),
+ None,
+ ])),
+ ),
+ (
+ "boolean",
+ Arc::new(BooleanArray::from(vec![Some(true), None])),
+ Arc::new(BooleanArray::from(vec![Some(false), Some(true), None])),
+ ),
+ (
+ "list_with_null_elements",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![None]),
+ Some(vec![Some(1), Some(2)]),
+ Some(vec![]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ Some(vec![Some(5)]),
+ Some(vec![]),
+ Some(vec![None, Some(1)]),
+ Some(vec![Some(5), None]),
+ None,
+ ])),
+ ),
+ (
+ // No empty list, so the extreme key has a first element to compare
+ // against the streamed NULL elements.
+ "list_null_elements_vs_extreme",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![Some(3)]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(3), None]),
+ Some(vec![Some(4)]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ None,
+ ])),
+ ),
+ ];
+
+ for (name, buffered, streamed) in cases {
+ let all_null = new_null_array(buffered.data_type(), 3);
+ let empty = buffered.slice(0, 0);
+ for (side, buffered) in
+ [("full", buffered), ("all_null", all_null), ("empty", empty)]
+ {
+ for operator in
+ [Operator::Lt, Operator::LtEq, Operator::Gt, Operator::GtEq]
+ {
+ // As `PiecewiseMergeJoinExec::try_new` sorts both sides.
+ let sort_options = match operator {
+ Operator::Lt | Operator::LtEq => SortOptions::new(true, true),
+ _ => SortOptions::new(false, true),
+ };
+ let sorted = take(
+ buffered.as_ref(),
+ &sort_to_indices(buffered.as_ref(), Some(sort_options), None)?,
+ None,
+ )?;
+ let extreme = buffered_extreme(&sorted)?;
+
+ let actual = matchable_rows(
+ &streamed,
+ &sorted,
+ extreme.as_ref(),
+ operator,
+ sort_options,
+ )?;
+
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(&streamed)],
+ &[Arc::clone(&sorted)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ for row in 0..streamed.len() {
Review Comment:
This PR also fixes dictionary keys whose *values* are NULL (a valid key pointing at a NULL value). `apply_cmp` sees the logical NULL and sets the row aside, while `main` joins it with every buffered row. Nothing pins this, and the oracle here uses physical `is_valid`, so it would call such a row matchable. Fine as a follow-up; this passes on the current head:
```diff
+ let nulls = streamed.logical_nulls();
for row in 0..streamed.len() {
- let expected = streamed.is_valid(row)
+ let expected = nulls.as_ref().is_none_or(|n| n.is_valid(row))
```
```rs
(
// A valid key pointing at a NULL value: logically NULL, physically valid.
"dictionary_null_values",
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1, 2]),
Arc::new(Int32Array::from(vec![Some(5), None, Some(1)])),
)),
Arc::new(DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![0, 1, 2, 3]),
Arc::new(Int32Array::from(vec![Some(2), None, Some(6), Some(0)])),
)),
),
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4174300119
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -631,18 +587,111 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last key of the sorted buffered side, or `None` when it is empty or every key is NULL:
+// NULLs sort first, so the last key is NULL only when every buffered key is.
+fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>> {
+ Ok(match values.len().checked_sub(1) {
+ Some(last) if values.is_valid(last) => Some(ColumnarValue::Scalar(
+ ScalarValue::try_from_array(values, last)?,
Review Comment:
Thanks @jayzhan211. Addressed in 036502fadc51464e781f7c555485d0b6c4e3dff0
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4158965379
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1227,313 @@ mod tests {
Ok(())
}
+ /// The pre-sort check that settles never-matching streamed rows must compare keys
+ /// the way the scan's `JoinKeyComparator` does, which normalizes `-0.0` to `+0.0`.
+ /// Under IEEE 754 total order (arrow's raw kernels, and the sort) `-0.0 < +0.0`
+ /// holds, so a check built on that would let the `+0.0` row through as a candidate
+ /// that the scan then rejects; with SQL semantics both rows are unmatched.
+ #[tokio::test]
+ async fn join_right_less_than_signed_zero_prefilter_agrees_with_scan() -> Result<()> {
Review Comment:
Addressed in a15bddae28202bbbd32f902aea1815d7acda025b
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -1185,6 +1227,313 @@ mod tests {
Ok(())
}
+ /// The pre-sort check that settles never-matching streamed rows must compare keys
+ /// the way the scan's `JoinKeyComparator` does, which normalizes `-0.0` to `+0.0`.
+ /// Under IEEE 754 total order (arrow's raw kernels, and the sort) `-0.0 < +0.0`
+ /// holds, so a check built on that would let the `+0.0` row through as a candidate
+ /// that the scan then rejects; with SQL semantics both rows are unmatched.
+ #[tokio::test]
+ async fn join_right_less_than_signed_zero_prefilter_agrees_with_scan() -> Result<()> {
+ let float_exec =
+ |a: &str, b: &str, keys: Vec<f64>| -> Result<Arc<dyn ExecutionPlan>> {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new(a, DataType::Int32, false),
+ Field::new(b, DataType::Float64, false),
+ ]));
+ let ids = (0..keys.len() as i32).collect::<Vec<_>>();
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(arrow::array::Int32Array::from(ids)),
+ Arc::new(arrow::array::Float64Array::from(keys)),
+ ],
+ )?;
+ Ok(TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?)
+ };
+ let left = float_exec("a1", "b1", vec![-0.0])?;
+ let right = float_exec("a2", "b2", vec![0.0, -1.0])?;
+ let on = (
+ Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
+ Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
+ );
+
+ let (_, batches, _) =
+ join_collect(left, right, on, Operator::Lt, JoinType::Right).await?;
+
+ assert_snapshot!(batches_to_string(&batches), @r"
+ +----+----+----+------+
+ | a1 | b1 | a2 | b2 |
+ +----+----+----+------+
+ | | | 0 | 0.0 |
+ | | | 1 | -1.0 |
+ +----+----+----+------+
+ ");
+ Ok(())
+ }
+
+ /// `matchable_rows` against the scan's own definition of a match -- some non-NULL
+ /// buffered row `idx` with `is_match(cmp.compare(row, idx))` under the scan's
+ /// `JoinKeyComparator` -- for every operator and every kind of key it dispatches on:
+ /// flat keys through `apply_cmp` (incl. signed zeros, NaN, strings, dictionaries) and
+ /// nested keys with NULL elements through the comparator. Each is also checked against
+ /// an all-NULL and an empty buffered side.
+ #[test]
+ fn matchable_rows_agrees_with_scan() -> Result<()> {
+ use arrow::array::{
+ BinaryArray, BooleanArray, Decimal128Array, DictionaryArray, Float64Array,
+ Int32Array, ListArray, StringArray, StringViewArray,
+ TimestampMicrosecondArray,
+ };
+ use arrow::datatypes::Int32Type;
+
+ let strings =
+ |v: &[Option<&str>]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
+ let cases: Vec<(&str, ArrayRef, ArrayRef)> = vec![
+ (
+ "int32",
+ Arc::new(Int32Array::from(vec![
+ Some(5),
+ None,
+ Some(1),
+ Some(9),
+ Some(3),
+ ])),
+ Arc::new(Int32Array::from(vec![
+ Some(0),
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(5),
+ Some(9),
+ Some(10),
+ None,
+ ])),
+ ),
+ (
+ "float64",
+ Arc::new(Float64Array::from(vec![
+ Some(0.0),
+ Some(-0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ None,
+ ])),
+ Arc::new(Float64Array::from(vec![
+ Some(-0.0),
+ Some(0.0),
+ Some(1.5),
+ Some(f64::NAN),
+ Some(-1.0),
+ Some(2.0),
+ Some(f64::INFINITY),
+ Some(f64::NEG_INFINITY),
+ None,
+ ])),
+ ),
+ (
+ "utf8",
+ strings(&[Some("b"), Some(""), Some("d"), None]),
+ strings(&[
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("c"),
+ Some("d"),
+ Some("e"),
+ None,
+ ]),
+ ),
+ (
+ "utf8_view",
+ Arc::new(StringViewArray::from(vec![
+ Some("b"),
+ Some(""),
+ Some("d"),
+ None,
+ ])),
+ Arc::new(StringViewArray::from(vec![
+ Some(""),
+ Some("a"),
+ Some("b"),
+ Some("d"),
+ Some("e"),
+ None,
+ ])),
+ ),
+ (
+ "binary",
+ Arc::new(BinaryArray::from(vec![Some(&b"b"[..]), Some(b""), None])),
+ Arc::new(BinaryArray::from(vec![
+ Some(&b""[..]),
+ Some(b"a"),
+ Some(b"b"),
+ Some(b"c"),
+ None,
+ ])),
+ ),
+ (
+ "dictionary",
+ Arc::new(
+ vec![Some("b"), None, Some("d"), Some("b")]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ Arc::new(
+ vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e"), None]
+ .into_iter()
+ .collect::<DictionaryArray<Int32Type>>(),
+ ),
+ ),
+ (
+ "decimal128",
+ Arc::new(
+ Decimal128Array::from(vec![Some(150), None, Some(-25)])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ Arc::new(
+ Decimal128Array::from(vec![
+ Some(-26),
+ Some(-25),
+ Some(0),
+ Some(150),
+ Some(151),
+ None,
+ ])
+ .with_precision_and_scale(10, 2)?,
+ ),
+ ),
+ (
+ "date32",
+ Arc::new(Date32Array::from(vec![Some(10), None, Some(20)])),
+ Arc::new(Date32Array::from(vec![
+ Some(9),
+ Some(10),
+ Some(15),
+ Some(20),
+ Some(21),
+ None,
+ ])),
+ ),
+ (
+ "timestamp_us",
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-5),
+ Some(7),
+ None,
+ ])),
+ Arc::new(TimestampMicrosecondArray::from(vec![
+ Some(-6),
+ Some(-5),
+ Some(7),
+ Some(8),
+ None,
+ ])),
+ ),
+ (
+ "boolean",
+ Arc::new(BooleanArray::from(vec![Some(true), None])),
+ Arc::new(BooleanArray::from(vec![Some(false), Some(true), None])),
+ ),
+ (
+ "list_with_null_elements",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![None]),
+ Some(vec![Some(1), Some(2)]),
+ Some(vec![]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ Some(vec![Some(5)]),
+ Some(vec![]),
+ Some(vec![None, Some(1)]),
+ Some(vec![Some(5), None]),
+ None,
+ ])),
+ ),
+ (
+ // No empty list, so the extreme key has a first element to compare
+ // against the streamed NULL elements.
+ "list_null_elements_vs_extreme",
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(5)]),
+ Some(vec![Some(3)]),
+ None,
+ ])),
+ Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None]),
+ Some(vec![Some(3), None]),
+ Some(vec![Some(4)]),
+ Some(vec![Some(7)]),
+ Some(vec![Some(1)]),
+ None,
+ ])),
+ ),
+ ];
+
+ for (name, buffered, streamed) in cases {
+ let all_null = new_null_array(buffered.data_type(), 3);
+ let empty = buffered.slice(0, 0);
+ for (side, buffered) in
+ [("full", buffered), ("all_null", all_null), ("empty", empty)]
+ {
+ for operator in
+ [Operator::Lt, Operator::LtEq, Operator::Gt, Operator::GtEq]
+ {
+ // As `PiecewiseMergeJoinExec::try_new` sorts both sides.
+ let sort_options = match operator {
+ Operator::Lt | Operator::LtEq => SortOptions::new(true, true),
+ _ => SortOptions::new(false, true),
+ };
+ let sorted = take(
+ buffered.as_ref(),
+ &sort_to_indices(buffered.as_ref(), Some(sort_options), None)?,
+ None,
+ )?;
+ let extreme = match sorted.len().checked_sub(1) {
Review Comment:
Addressed in a15bddae28202bbbd32f902aea1815d7acda025b
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4158957360
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -456,126 +494,49 @@ fn resolve_classic_join(
)?;
let mut buffer_idx = batch_process_state.start_buffer_idx;
- let mut stream_idx = batch_process_state.start_stream_idx;
+ let stream_idx = batch_process_state.start_stream_idx;
+ // NULL keys never match and sort first, so the scan starts past the buffered ones.
+ // Streamed NULL keys never get here: `matchable_rows` settled them before the sort.
+ debug_assert_eq!(stream_values[0].null_count(), 0);
if !batch_process_state.processed_null_count {
- let buffered_null_idx = buffered_side.buffered_data.values().null_count();
- let stream_null_idx = stream_values[0].null_count();
- buffer_idx = buffered_null_idx;
- stream_idx = stream_null_idx;
+ buffer_idx = buffered_side.buffered_data.values().null_count();
batch_process_state.processed_null_count = true;
-
- // The scan below starts past the streamed side's NULL-keyed rows, which
- // sit at the front (`nulls_first`). A NULL join key never matches under
- // `NullEqualsNothing`, so for `Right`/`Full` those rows are unmatched and
- // must still be emitted; record them here since the scan will skip them.
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- for row_idx in 0..stream_null_idx as u32 {
- batch_process_state.unmatched_indices.append_value(row_idx);
- }
- }
}
- // Our buffer_idx variable allows us to start probing on the buffered side where we last matched
- // in the previous stream row.
- for row_idx in stream_idx..stream_batch.batch.num_rows() {
- while buffer_idx < buffered_len {
- let compare = cmp.compare(row_idx, buffer_idx);
-
- // If we find a match we append all indices and move to the next stream row index
- match operator {
- Operator::Gt | Operator::Lt => {
- if compare == Ordering::Less {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
-
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- batch_process_state.output_batches.push_batch(batch)?;
-
- // Flush batch and update pointers if we have a completed batch
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
+ let match_on_equal = matches_on_equal(operator)?;
- break;
- }
- }
- Operator::GtEq | Operator::LtEq => {
- if matches!(compare, Ordering::Equal | Ordering::Less) {
- batch_process_state.found = true;
- let count = buffered_len - buffer_idx;
- let batch = build_matched_indices_and_mark_buffered(
- (buffer_idx, count),
- (row_idx, count),
- buffered_side,
- stream_batch,
- join_type,
- join_schema,
- &mut batch_process_state.batch_min_marked,
- )?;
-
- // Flush batch and update pointers if we have a completed batch
- batch_process_state.output_batches.push_batch(batch)?;
- if let Some(batch) =
- batch_process_state.output_batches.next_completed_batch()
- {
- batch_process_state.found = false;
- batch_process_state.start_buffer_idx = buffer_idx;
- batch_process_state.start_stream_idx = row_idx + 1;
- return Ok(batch);
- }
-
- break;
- }
- }
- _ => {
- return internal_err!(
- "PiecewiseMergeJoin should not contain operator, {}",
- operator
- );
- }
- }
-
- // Increment buffer_idx after every row
- buffer_idx += 1;
- }
-
- // If a match was not found for the current stream row index the stream indice is appended
- // to the unmatched indices to be flushed later.
- if matches!(join_type, JoinType::Right | JoinType::Full)
- && !batch_process_state.found
- {
- batch_process_state
- .unmatched_indices
- .append_value(row_idx as u32);
- }
-
- batch_process_state.found = false;
- }
-
- // Flushed all unmatched indices on the streamed side
- if matches!(join_type, JoinType::Right | JoinType::Full) {
- let batch = create_unmatched_batch(
- &mut batch_process_state.unmatched_indices,
+ // `buffer_idx` resumes where the previous stream row's first match was: rows are sorted
+ // so that each one's first match is at or after the previous one's, which bounds the
+ // search below to `[buffer_idx, buffered_len)`.
+ //
+ // Every row here matches: `matchable_rows` kept only rows that match the last buffered
+ // row, and settled the rest (as unmatched for `Right`/`Full`) before the sort.
+ for row_idx in stream_idx..stream_batch.batch.num_rows() {
+ buffer_idx = first_match(buffer_idx, buffered_len, |idx| {
+ is_match(cmp.compare(row_idx, idx), match_on_equal)
+ });
+ debug_assert!(buffer_idx < buffered_len);
Review Comment:
Addressed in a15bddae28202bbbd32f902aea1815d7acda025b
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf:settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#issuecomment-5876485212
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/25840?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `92.01878%` with `34 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 82.55%. Comparing base ([`991fd23`](https://app.codecov.io/gh/apache/datafusion/commit/991fd23dd0be0046af5945b8c3905612859b657a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`9228989`](https://app.codecov.io/gh/apache/datafusion/commit/9228989a0b8eafda7da18314f8cff9bd3d26681d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/25840?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...lan/src/joins/piecewise\_merge\_join/classic\_join.rs](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fpiecewise_merge_join%2Fclassic_join.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9waWVjZXdpc2VfbWVyZ2Vfam9pbi9jbGFzc2ljX2pvaW4ucnM=) | 91.73% | [9 Missing and 22 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...sical-plan/src/joins/piecewise\_merge\_join/utils.rs](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fpiecewise_merge_join%2Futils.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9waWVjZXdpc2VfbWVyZ2Vfam9pbi91dGlscy5ycw==) | 95.65% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...n/src/joins/piecewise\_merge\_join/existence\_join.rs](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fpiecewise_merge_join%2Fexistence_join.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9waWVjZXdpc2VfbWVyZ2Vfam9pbi9leGlzdGVuY2Vfam9pbi5ycw==) | 80.00% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25840?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #25840 +/- ##
========================================
Coverage 82.55% 82.55%
========================================
Files 1141 1141
Lines 440209 440527 +318
Branches 440209 440527 +318
========================================
+ Hits 363409 363688 +279
- Misses 54829 54846 +17
- Partials 21971 21993 +22
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/25840?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf(pwmj):settle never-matching streamed rows against the buffered extreme… [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25840:
URL: https://github.com/apache/datafusion/pull/25840#discussion_r4178690446
##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -631,18 +588,121 @@ fn build_matched_indices_and_mark_buffered(
)?)
}
-// Creates a record batch from the unmatched indices on the streamed side
-fn create_unmatched_batch(
- streamed_indices: &mut PrimitiveBuilder<UInt32Type>,
- stream_batch: &SortedStreamBatch,
+// The last key of the sorted buffered side, or `None` when it is empty or every key is NULL:
+// NULLs sort first, so the last key is NULL only when every buffered key is.
+fn buffered_extreme(values: &ArrayRef) -> Result<Option<ColumnarValue>> {
+ Ok(match values.len().checked_sub(1) {
+ // `apply_cmp` normalizes `-0.0` only in flat float scalars, not inside a
+ // `ScalarValue::Dictionary`, so normalize the key before taking it.
+ Some(last) if values.is_valid(last) => {
+ let extreme = normalize_float_zero(&values.slice(last, 1));
+ Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &extreme, 0,
+ )?))
+ }
+ _ => None,
+ })
+}
+
+// Which rows of `stream_values` can match at least one buffered row.
+//
+// Every match set is a suffix `[k, buffered_len)` of the sorted buffered side, so a streamed
+// row matches anything at all iff it matches the last buffered row, `buffered_extreme`
+// (`None` when no buffered key is non-null, so nothing can match). A NULL on either side
+// compares to NULL, which is no match.
+//
+// This must agree exactly with the scan's `JoinKeyComparator`, or it would change which rows
+// match. For flat keys one vectorized `apply_cmp` does: it normalizes `-0.0` to `+0.0` as the
+// comparator does. For nested keys it does not -- `apply_cmp` orders NULL elements inside a
+// key ascending, while the comparator applies the sort options (descending for `<`/`<=`) at
+// every level -- so those are decided with the scan's own comparator.
+fn matchable_rows(
+ stream_values: &ArrayRef,
+ buffered_values: &ArrayRef,
+ buffered_extreme: Option<&ColumnarValue>,
+ operator: Operator,
+ sort_options: SortOptions,
+) -> Result<BooleanArray> {
+ let num_rows = stream_values.len();
+ let Some(extreme) = buffered_extreme else {
+ return Ok(BooleanArray::new(BooleanBuffer::new_unset(num_rows), None));
+ };
+
+ // The comparator's nested ordering is itself wrong for `<`/`<=` (#25957). Once that is
+ // fixed, nested keys can go through `apply_cmp` too and this branch can be removed.
+ //
+ // Run-end encoded keys are decided here too: arrow's run-end comparison kernel overflows
+ // on an empty batch sliced past its first run, which the scan never reaches.
+ if stream_values.data_type().is_nested()
+ || matches!(stream_values.data_type(), DataType::RunEndEncoded(_, _))
+ {
+ let match_on_equal = matches_on_equal(operator)?;
+ let cmp = JoinKeyComparator::new(
+ &[Arc::clone(stream_values)],
+ &[Arc::clone(buffered_values)],
+ &[sort_options],
+ NullEquality::NullEqualsNothing,
+ )?;
+ let last = buffered_values.len() - 1;
+ let matchable = BooleanBuffer::collect_bool(num_rows, |row| {
+ stream_values.is_valid(row)
Review Comment:
Addressed in 2627267b525c9eece069b89c55afc8099be349dc
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org