Repository navigation
Conversation
… join `inner_10to1` joins 10 streamed rows to each buffered row, as a fact table joins a dimension on its key. `left_1to1000_selective_filtered` runs the inputs and filter of `inner_1to1000_selective_filtered` as a Left join.
…first A streamed row and the run of buffered rows it matches are now recorded as one `PairRun`, in a vector that the freezes reuse, instead of a pair of `u64` indices per match in chunks allocated for each buffered batch. At the freeze a side whose rows form a range is sliced as before, long runs of buffered rows are copied as ranges, and the streamed row of a long run is repeated for primitive columns. Short runs are still gathered row by row. Left, Right and Full joins with a filter now evaluate it before materializing pairs, like Inner joins. They keep the pairs that pass and the first pair of each streamed row whose pairs all fail, which the deferred filter null-joins as before.
Buffered batches kept every input column while they waited for their key group, and spilled them all. Once its join keys are computed, a buffered batch now keeps only the columns that the join emits or its filter reads, so its reservation and spill files no longer include, for example, a join key that the projection drops.
|
With Comet 10TB |
A freeze that copies runs of buffered rows built a `MutableArrayData` for each column, which converted the column of every source batch with `to_data()` and boxed an extend closure for each. With 64-row buffered batches, that setup took about 6% of the CPU in a Linux profile. Primitive and byte arrays now copy their value ranges and validity directly. Other types keep `MutableArrayData`.
|
run benchmark tpch tpcds smj |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark tpcds
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark tpch
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark tpch
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagesmj — base (merge-base)
smj — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (b255dd5) to 5184bdd (merge-base) diff Run configurationrun benchmark tpcds
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
|
run benchmark |
|
Hi @comphead, Usage: Any benchmark name is accepted: Per-side configuration ( env:
# shared env is inherited by BOTH the build and the run, so build
# flags go here. Builds default to no debuginfo for speed; opt back
# in for hung-job gdb dumps and cap jobs to stay within memory:
CARGO_PROFILE_RELEASE_DEBUG: "1"
CARGO_BUILD_JOBS: "1"
baseline:
ref: v45.0.0
env:
# per-side env only reaches the benchmark run, not the build
DATAFUSION_RUNTIME_MEMORY_LIMIT: 1G
changed:
ref: v46.0.0
env:
DATAFUSION_RUNTIME_MEMORY_LIMIT: 2GPod size and CPU architecture (each key is optional and keeps the default when absent; requests and limits are set equal): resources:
cpu: "16"
memory: "128Gi"
arch: arm64 # arm64 or amd64Independent benchmark shards (optional; 1–8, default 1): run benchmark arrow_writer
shards: 4Each shard builds both revisions, measures its assigned cases, and posts its own report. Resources and the job deadline apply per shard. DataFusion requests specifying a shard count greater than 1 fail with an error. Omit shards or use shards: 1 for DataFusion. File an issue against this benchmark runner |
- Skip loading buffered batches when the join reads no buffered column. - Share one `PairRun::continues` rule between the summary and the ranges. - Copy ranges of primitive and byte columns and gather the other columns, instead of a separate `MutableArrayData` path and dictionary check. - Repeat streamed rows by the number of streamed rows, not runs, and build their indices once. - Remap the filter's buffered columns from the remapped filter. - Reuse `SortMergeJoinExec::probe_side`, add `filter_indices` and `filter_columns`, and fold the dictionary test into the runs test.
…ranges `join_left_copies_runs_of_several_batches` now also checks the key column, which has no nulls of its own, and a new test keeps a null-joined pair that passes the filter in the same freeze as a filtered run.
One-row ranges had a `collect_bool` path that measured no faster than the builder loop (0.99x on `left_1to1_unmatched`), so the gather keeps one loop.
|
run benchmark smj tpch tpcds |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark tpcds
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark tpch
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagesmj — base (merge-base)
smj — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark tpch
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (d7fab8a) to 5184bdd (merge-base) diff Run configurationrun benchmark tpcds
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
`filter_ranges` reserved one kept range per input range, but a long run of buffered rows splits into a range for each slice of pairs that pass, so a selective filter grew the vector several times per freeze. In a Linux profile of TPC-DS q72 the regrowth took about 6% of the join's CPU. The capacity now bounds the slices by the pairs that pass and by one more than the pairs that fail, plus one per input range, without a pass over the mask. The benchmarks sort `data` within each key group, so their filters keep one slice per run and never regrow. On a variant of `inner_1to1000_selective_filtered` whose buffered `data` has no order within a key group, as q72's quantities have none, this is 3.5% faster.
…time A filter-first freeze materialized the pairs that passed, often a few hundred out of `batch_size`, and the output coalescer then copied them again into its batch. When the freeze of an Inner join keeps no more pairs than the coalescer copies, it now records them as runs, and the stream materializes them in batches that complete the coalescer's partial batch, so that the coalescer passes the next ones on without copying them. Such a freeze also builds no filter predicate and filters neither the filter's columns nor the pairs' rows. Since the runs address the streamed batch and the buffered batches by position, they are materialized before the streamed batch changes, before a buffered batch is dequeued and at the end, in pieces that join the partial batch, so every batch but the last stays full. A new test checks a selective Inner join, with and without spilling, against the unfiltered join and the filter. Against the previous commit, on macOS, `inner_1to1000_selective_filtered`, which has the shape of TPC-DS q72, is 29% faster, `inner_1to100_filtered` 15%, `inner_1to10_filtered` 10% and `inner_1to1_filtered` 5%, and the variant with unordered buffered `data` 13%. The two Left cases, which do not take this path, are 4-5% slower: the new code changes the inlining, which leaves arrow's `BooleanBuilder::extend` in `FilterMetadata::append_filter_metadata` out of line.
`FilterMetadata::append_filter_metadata` extended its builders from the arrays' iterators. Arrow's `BooleanBuilder::extend` collects the values into a `Vec<Option<bool>>` and builds a `BooleanArray` from it to append. After the previous commit, which changed the inlining, building that array took 5% of `left_1to1000_selective_filtered` in a profile. `append_array` copies the arrays' buffers instead. Against the previous commit, on macOS, `left_1to100_filtered` is 14% faster and `left_1to1000_selective_filtered` 10%, so both are now faster than before the previous two commits, by 10% and 5%. The Inner cases do not change.
|
run benchmark smj |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing smj-27910 (0259a38) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing smj-27910 (0259a38) to 5184bdd (merge-base) diff Run configurationrun benchmark smj
env:
PREFER_HASH_JOIN: "false"Trigger commentCPU Details (lscpu)Details
Resource Usagesmj — base (merge-base)
smj — branch
File an issue against this benchmark runner |
andygrove
left a comment
There was a problem hiding this comment.
This review is based on d7fab8a, before the three commits pushed since.
Thanks @comphead. Keeping pairs as runs makes the pairing state much simpler, and the wins reproduce here. I ran 10 alternating rounds on an M3 Max with thin LTO, against the PR's base plus the bench commit: left_1to1000_selective_filtered 0.11x, left_1to100_filtered 0.50x, inner_1to100 0.59x, inner_group_spans_buffered_batches/8 0.44x.
I found one wrong-results case, in Full joins with a filter. When a streamed row's pairs straddle a freeze and filtering first keeps few of them, the deferred metadata can stay under batch_size. Then the flush gate at the top of join doesn't fire after the row. If a buffered group that matches nothing comes next, a later freeze_all pushes its null-joined rows ahead of the rest of the streamed row's pairs. That splits the row's group in get_corrected_filter_mask, so the row comes out joined to NULLs as well as with its match. On main every pair reached the metadata, so the gate always fired right after such a row.
The test below fails on this PR and passes on main. The same shape also fails at the default batch size, with one streamed row against a 10,000-row key group. I left a fix that worked in a prototype on the materialize_pairs docs. With it, the filtered Left and Right joins of a 20,000-case differential fuzz matched main exactly, and the filtered Full joins all matched HashJoinExec.
Test
/// A Full join row whose pairs straddle a freeze, and of which only the first
/// passes the filter, keeps just that pair when a buffered group that matches
/// nothing comes before the rest of its pairs reach the deferred filter.
#[tokio::test]
async fn join_full_filtered_row_straddling_a_freeze() -> Result<()> {
let left = build_table(
("a1", &vec![5, 7, 8, 9]),
("b1", &vec![0, 0, 0, 0]),
("c1", &vec![1, 2, 3, 4]),
);
let right = build_table(
("a2", &vec![5, 5, 5, 5, 5, 6, 10]),
("b2", &vec![0, 1, 1, 1, 1, 0, 0]),
("c2", &vec![10, 11, 12, 13, 14, 15, 16]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
)];
// `b2 < 1`
let filter = JoinFilter::new(
Arc::new(BinaryExpr::new(
Arc::new(Column::new("b2", 0)),
Operator::Lt,
Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
)),
vec![ColumnIndex {
index: 1,
side: JoinSide::Right,
}],
Arc::new(Schema::new(vec![Field::new("b2", DataType::Int32, true)])),
);
let join = join_with_filter(
left,
right,
on,
filter,
Full,
vec![SortOptions::default()],
NullEquality::NullEqualsNothing,
)?;
let task_ctx = Arc::new(
TaskContext::default()
.with_session_config(SessionConfig::new().with_batch_size(4)),
);
let batches = common::collect(join.execute(0, task_ctx)?).await?;
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| | | | 10 | 0 | 16 |
| | | | 5 | 1 | 11 |
| | | | 5 | 1 | 12 |
| | | | 5 | 1 | 13 |
| | | | 5 | 1 | 14 |
| | | | 6 | 0 | 15 |
| 5 | 0 | 1 | 5 | 0 | 10 |
| 7 | 0 | 2 | | | |
| 8 | 0 | 3 | | | |
| 9 | 0 | 4 | | | |
+----+----+----+----+----+----+
");
Ok(())
}Two open PRs touch the same code. #27346 re-evaluates the buffered join keys when a spilled batch is read back. It merges cleanly with this PR, but the batch it reads back is now projected, and join_with_projection_matches_projected_join fails with both applied. #27731's regression test also passes on this PR without its fix. The dictionary overflow now surfaces in finish_buffered_batch, which JoinedRecordBatches::concat_batches already propagates, instead of inside push_batch.
This review was AI-assisted.
| /// pairs of a many-to-many join. An outer join also keeps the first pair of | ||
| /// each streamed row whose pairs all fail, which the deferred filter | ||
| /// null-joins unless another freeze passes one of the row's pairs. |
There was a problem hiding this comment.
This relies on a row's kept pairs reaching the deferred metadata back to back across freezes. In a Full join a later freeze_all can push null-joined buffered rows between them, which is the case in the review body. Freezing the rest of a row as soon as its scan finishes, when the row straddled a freeze, fixed it in a prototype:
Ordering::Equal => {
+ let mut straddled = false;
while !self.pair_streamed_row_with_group() {
self.freeze_and_emit(emitter).await?;
+ straddled = true;
+ }
+ // The deferred filter needs a streamed row's pairs back to back,
+ // and a later `freeze_all` would push null-joined buffered rows
+ // ahead of the rest of this row.
+ if straddled && self.deferred_filtering {
+ self.restore_spilled_batches_for_freeze().await?;
+ self.freeze_streamed()?;
}| buffered_schema = | ||
| Arc::new(buffered_schema.project(&buffered_gathered_columns)?); |
There was a problem hiding this comment.
From here on buffered_schema holds the kept columns, so its field doc ("Input schema of buffered") is out of date. Could it say so? on_buffered still indexes the input's columns, which is what trips up #27346 when it re-evaluates the keys on a restored batch.
| end += runs[i].len; | ||
| i += 1; | ||
| } | ||
| let none_passed = if end - start == 1 { |
There was a problem hiding this comment.
Inverting this one-pair shortcut still passes every sort-merge join test, though it changes the output of 151 of 2,500 fuzz cases. Could you add a test where a streamed row's only pair fails in a freeze that filters first? This one fails with the shortcut inverted:
Test
/// A streamed row whose only pair fails the filter is still null-joined when a
/// longer run in the same freeze makes the freeze filter first.
#[tokio::test]
async fn join_left_null_joins_single_failing_pair_in_filtered_freeze() -> Result<()> {
let left = build_table(
("a1", &vec![1, 2]),
("b1", &vec![0, 0]),
("c1", &vec![10, 20]),
);
let right = build_table(
("a2", &vec![1, 1, 2]),
("b2", &vec![1, 1, 0]),
("c2", &vec![0, 1, 2]),
);
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
)];
// `b2 > 0`
let filter = JoinFilter::new(
Arc::new(BinaryExpr::new(
Arc::new(Column::new("b2", 0)),
Operator::Gt,
Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
)),
vec![ColumnIndex {
index: 1,
side: JoinSide::Right,
}],
Arc::new(Schema::new(vec![Field::new("b2", DataType::Int32, true)])),
);
let (_, batches) = join_collect_with_filter(left, right, on, filter, Left).await?;
assert_snapshot!(batches_to_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 0 | 10 | 1 | 1 | 0 |
| 1 | 0 | 10 | 1 | 1 | 1 |
| 2 | 0 | 20 | | | |
+----+----+----+----+----+----+
");
Ok(())
}| let status = &mut self.buffered_data.batches[batch] | ||
| .join_filter_status[run.buffered_row..run.buffered_row + run.len]; | ||
| for (i, state) in status.iter_mut().enumerate() { | ||
| if *state != FilterState::SomePassed { |
There was a problem hiding this comment.
Replacing this condition with true also passes every sort-merge join test, though 93 of 2,500 fuzz cases change. This test pins it down, since its buffered row passes with the first streamed row and fails with the second:
Test
/// A buffered row that passes the filter with one streamed row and fails with a
/// later one has matched, so a Full join does not also null-join it.
#[tokio::test]
async fn join_full_keeps_buffered_row_that_passed_once() -> Result<()> {
let left = build_table(
("a1", &vec![1, 1]),
("b1", &vec![0, 0]),
("c1", &vec![10, 20]),
);
let right = build_table(("a2", &vec![1]), ("b2", &vec![0]), ("c2", &vec![30]));
let on = vec![(
Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
)];
// `c1 < 15`
let filter = JoinFilter::new(
Arc::new(BinaryExpr::new(
Arc::new(Column::new("c1", 0)),
Operator::Lt,
Arc::new(Literal::new(ScalarValue::Int32(Some(15)))),
)),
vec![ColumnIndex {
index: 2,
side: JoinSide::Left,
}],
Arc::new(Schema::new(vec![Field::new("c1", DataType::Int32, true)])),
);
let (_, batches) = join_collect_with_filter(left, right, on, filter, Full).await?;
assert_snapshot!(batches_to_sort_string(&batches), @r"
+----+----+----+----+----+----+
| a1 | b1 | c1 | a2 | b2 | c2 |
+----+----+----+----+----+----+
| 1 | 0 | 10 | 1 | 0 | 30 |
| 1 | 0 | 20 | | | |
+----+----+----+----+----+----+
");
Ok(())
}
Which issue does this PR close?
Rationale for this change
#27278 filters Inner sort-merge join pairs before materializing them. Its profiles showed where the join still spends its time:
inner_1to1000_selective_filtered), gathering the filter's columns through per-pair indices took about 30% of the CPU, and recording those indices 11%.What changes are included in this PR?
append_output_pairsrecords a streamed row and its run of buffered rows as onePairRun, in a vector that the freezes reuse. Before, it stored au64pair per match, in chunks allocated for each buffered batch. At the freeze, a side whose rows form a range is still sliced. Long runs are copied: the buffered rows as ranges, and the streamed row repeated for primitive columns. Primitive and byte arrays copy their value ranges and validity directly. Other types are gathered row by row, and for dictionariesinterleavemerges what copying would concatenate. Buffered runs, or streamed rows, that average fewer than 12 pairs are still gathered row by row.sort_merge_joinbenchmark cases,inner_10to1andleft_1to1000_selective_filtered, are in a separate first commit.What is the testing strategy for this PR?
The existing sort-merge join tests cover most of the new paths. They compare with
HashJoinExecand with projected joins, and they cover spilling. Mutation checks of the new code found gaps, which the first three of these tests close:join_runs_continue_only_within_a_buffered_batch: a key group starts at row 32 of one buffered batch and ends at row 32 of the next, so runs from the two batches line up. Its dictionary column is gathered withinterleave, since copying would concatenate the batches' dictionaries pastInt8keys.join_left_copies_runs_of_several_batches: a Left join copies runs from two buffered batches around a null-joined pair, into a key without nulls and integer, string and boolean columns with nulls.join_left_keeps_nulls_of_passing_null_joined_pair: a null-joined pair that passes the filter keeps its NULL buffered values when its freeze filters a run.join_with_projection_matches_projected_joinnow also runs with spilling. Its projections drop the buffered key.The join fuzz tests and the sort-merge join sqllogictest files pass.
Benchmarks:
cargo bench -p datafusion-physical-plan --features test_utils --bench sort_merge_join, this PR against its base plus the bench commit (the head of #27278, whose sort-merge join codemainnow has), with thin LTO on an Apple M5 Max. The two builds and a second copy of the base ran alternately for four rounds. The table shows each case's best round.inner_1to1000_selective_filtered/20000left_1to1000_selective_filtered/20000(new)left_1to100_filtered/20000inner_1to100/20000inner_1to100_filtered/20000inner_group_spans_buffered_batches/8inner_group_spans_buffered_batches/64inner_group_spans_buffered_batches/512inner_1to1/100000inner_10to1/100000(new)inner_1to10/100000inner_1to10_high_pass_filtered_narrow/100000The other cases changed by 4% or less, and the second copy of the base ran up to 6% apart from the first, so the small changes are within noise. Runs of about 10 pairs can be a few percent slower, because the freeze now expands them into indices that pairing used to write. A linux/arm64 run in Docker (4 vCPUs, two rounds) agreed: q72's shape took 0.54x as long as the base, its Left join 0.13x, and
inner_group_spans_buffered_batches/640.41x, with the 1:10 cases within 5% of the base. The table predates the last three commits, review cleanups that measured 0.96x to 1.01x of the previous head on these cases (medians of four alternating rounds, with a copy of the previous head within 1%).For item 3, in a scratch Inner join whose projection drops the buffered key and a string column, with 50,000 buffered rows per key, the peak reservation fell from 2.99 MB to 1.38 MB. With a 1 MB pool, the spilled bytes fell from 4.71 MB to 0.49 MB.
Are there any user-facing changes?
No.