← Back to Pull requests

perf: slice contiguous rows in native shuffle instead of gathering them one at a time #7636

Closed
unknown closed this pull request without merging on Nov 30, 2026 23:10 UTC
View on GitHub
unknown unknown commented on Nov 15, 2026 19:27 UTC
Author

Which issue does this PR close?

Closes #7474.

Rationale for this change

Hash, range, and hash round robin partitioning record one (batch, row) pair per row and build each output chunk with interleave_record_batch. Arrow copies primitive and string columns there one row at a time (interleave_primitive, interleave_bytes) and merges contiguous rows only in interleave_fallback, which Boolean columns use. So a chunk whose rows are already one span of a buffered batch is still gathered row by row.

That is the shape an Iceberg write gets when Spark rebalances on a partition column that holds one value per run, such as the ds of an hourly or daily ETL. Every row hashes to one partition, and each buffered batch is a single run. In the production job described in #7474, partition interleaving was 54% of the native shuffle writer time in the map stage.

DataFusion's RepartitionExec gained the whole-batch case of this in 56.0.0. Its partition_grouped_take passes a batch through unchanged when all of its rows go to one partition (apache/datafusion#24598). This PR also covers runs that span buffered batches and output chunks.

What changes are included in this PR?

  • RowIterator (partitioned_batch_iterator.rs) splits each output chunk into runs of consecutive rows of one buffered batch with chunk_by. When the runs average at least 64 rows, it slices them out of the buffered batches and concatenates the slices, and a chunk that is a single run reaches the writer as a zero-copy slice. Otherwise it gathers as before.

  • Deciding is cheap on both sides of the threshold. One probe per 64 rows gives a lower bound on the run count that rules out a chunk whose runs are all shorter than 64 rows, and an exact count that stops one run past the budget decides the rest. Without the bound, a chunk with runs just under the threshold paid for reading most of itself before being gathered anyway.

  • The partition index is unchanged, so placement, memory accounting, and spilling are untouched. This answers the open question in #7474 with a choice made per output chunk at flush, rather than a mixed index of rows and runs.

  • A schema with a view type or a dictionary anywhere keeps the gather, because the IPC writer serializes every data buffer a sliced view array shares and a sliced dictionary's whole values array. For view types this is the rule partitioning_for_schema already applies to positional round robin, so contains_view_type becomes pub(crate). Dictionary schemas write the same blocks as before.

  • RunIterator and RowIterator share the single-slice passthrough through a new concat_slices.

  • native_shuffle.md describes how a hash partition's rows are written, Range Partitioning points at it, and the RowGroups section no longer says positional placement is the only strategy that hands the IPC writer slices. It also names dictionaries as the second type whose slices the writer does not truncate.

  • A shuffle_hash_contiguous bench group in benches/shuffle_writer.rs, with constant, clustered (runs of 48 and 96 rows) and per-row hash keys.
  • Range partitioning over clustered input takes the same path.

    The threshold comes from a sweep with arrow 59.3.2 on Apple Silicon, over chunks of 8192 rows drawn from 16 batches. Slicing and concatenating beats interleave_record_batch from an average run of about 32 rows on 4-column and 16-column flat schemas, and breaks even at about 64 on a nested schema (8 columns of a three-leaf struct inside two single-field structs, plus a list column). At the shuffle level, the 40-column nested fixture already runs 0.63x to 0.72x of the merge base at 64-row runs. I did not measure x86.

    How are these changes tested?

    New unit tests in partitioned_batch_iterator.rs:

  • contiguous_rows_are_sliced_not_gathered: over sliced sources with an Int64, a nullable Utf8 and a nullable Boolean column, chunks that are a whole batch, two runs, and part of a batch come out equal to interleave_record_batch. The whole-batch chunk shares its source buffers, which shows the slice path ran.

  • view_and_dictionary_columns_are_gathered_even_when_contiguous: contiguous Utf8View, Dictionary(Int32, Utf8) and struct<dictionary> chunks long enough to slice are still gathered.

  • long_run_bound_matches_exact_count: the lower bound never changes the exact count's decision, on random mixes of short, long and out-of-order runs.
  • offsets_as_lengths_round_trip_every_mapped_type now also round-trips its batch of every mapped type (struct, list, large list, map, fixed size list, decimal, boolean and others, with nulls, empty values and inner arrays that start past offset 0) sliced from row 5, through ShuffleBlockWriter and both readers under every codec. That is the shape the slice path hands the IPC writer. The existing boolean_interleave_matches_arrow_for_sliced_nullable_states also sends its contiguous selections through the slice path.

    Benchmarks ran on an 18-core Apple Silicon machine that was shared with other work, so the before and after binaries ran alternately and the numbers below are means over the rounds.

    shuffle_hash_contiguous, place and gather of 65,536 rows into 200 partitions, PR time over the merge base. Rows at or under 48 are the mean of four rounds interleaved per case, the others are two rounds. Flat is the 4-column fixture, nested is the bench's 40-column struct fixture with a key column added.

    | hash key | flat | nested structs |
    | --- | --- | --- |
    | per row (scattered) | 0.99 | |
    | runs of 32 rows | 1.01 | |
    | runs of 48 rows | 1.00 | 1.00 |
    | runs of 64 rows | 0.76 / 0.82 | 0.63 / 0.72 |
    | runs of 96 rows | 0.72 / 0.79 | 0.65 / 0.66 |
    | runs of 120 rows | 0.69 / 0.77 | 0.60 / 0.61 |
    | runs of 136 rows | 0.71 / 0.71 | 0.57 / 0.59 |
    | one key per task | 0.48 / 0.51 | |

    The same group in absolute numbers, three rounds, measured before the lower bound was added. The bound changes no decision and costs about 20 ns of probes per scattered chunk.

    | Hash key | Rows per batch | Before | After |
    | --- | --- | --- | --- |
    | constant | 8192 | 693 µs | 333 µs |
    | constant | 1000 | 702 µs | 408 µs |
    | per row | 8192 | 981 µs | 997 µs |
    | per row | 1000 | 1.369 ms | 1.329 ms |

    shuffle_bench over a generated 4M-row Parquet file with 16 columns (8 strings, 7 longs, 1 int) and a constant ds, 1600 partitions, zstd(1), two rounds:

    | Hash key | Write time | interleave time | Encode time | Output |
    | --- | --- | --- | --- | --- |
    | constant ds, before | 1.301 s | 0.151 s | 0.94 s | 335 MiB |
    | constant ds, after | 1.161 s | 0.016 s | 0.94 s | 335 MiB |
    | per-row seq, before | 2.317 s | 0.913 s | 1.18 s | 451 MiB |
    | per-row seq, after | 2.304 s | 0.886 s | 1.17 s | 451 MiB |

    Encode time does not change, so the IPC writer does not pay more for slices. zstd encoding takes most of the write time on this data, so the end-to-end gain here is smaller than the production share in #7474 suggests.

    <details>
    <summary>Input and commands</summary>

    The input was generated with DuckDB:

    COPY (
      SELECT
        '2026-11-03' AS ds,
        md5(i::VARCHAR) AS record_id,
        sha256(i::VARCHAR) AS payload_hash,
        CASE WHEN i % 20 = 0 THEN NULL ELSE 'device-' || (i % 5000)::VARCHAR END AS device,
        ['US', 'DE', 'FR', 'JP', 'IN', 'BR', 'GB', 'CN'][(i % 8) + 1] AS country,
        (i % 256)::VARCHAR || '.' || ((i // 256) % 256)::VARCHAR || '.'
          || ((i // 65536) % 256)::VARCHAR || '.' || (i % 251)::VARCHAR AS ip,
        'app/' || (i % 37)::VARCHAR || '.' || (i % 11)::VARCHAR AS app_version,
        CASE WHEN i % 7 = 0 THEN NULL ELSE 'city_' || (i % 997)::VARCHAR END AS city,
        i::BIGINT AS seq,
        (1730000000000000 + i * 1000)::BIGINT AS event_time_us,
        (i * 2654435761 % 1000000007)::BIGINT AS user_id,
        (i % 1000)::BIGINT AS bucket,
        CASE WHEN i % 13 = 0 THEN NULL ELSE (i * 31)::BIGINT END AS bytes_in,
        (i * 17)::BIGINT AS bytes_out,
        (i % 86400)::BIGINT AS second_of_day,
        (i % 100)::INTEGER AS shard
      FROM range(4000000) t(i)
    ) TO 'constant_ds.parquet' (FORMAT parquet, ROW_GROUP_SIZE 1048576);
    

    cd native
    cargo bench -p datafusion-comet-shuffle --bench shuffle_writer -- shuffle_hash_contiguous
    cargo build --release -p datafusion-comet-shuffle --features shuffle-bench --bin shuffle_bench
    # --hash-columns 0 is the constant ds, 8 is the per-row seq
    target/release/shuffle_bench --input constant_ds.parquet --partitions 1600 --partitioning hash \
      --hash-columns 0 --codec zstd --zstd-level 1 --warmup 1 --iterations 3
    

    </details>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: sunchao Review duration: 21822m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #7636"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%