Skip to content

[Data] Prune Parquet row groups for mixed partition/data OR filters - #67855

Open
m4ru1 wants to merge 6 commits into
ray-project:masterfrom
m4ru1:contribution/mixed-or-parquet-pruning
Open

m4ru1 wants to merge 6 commits into
ray-project:masterfrom
m4ru1:contribution/mixed-or-parquet-pruning

Conversation

@m4ru1

@m4ru1 m4ru1 commented Nov 5, 2026 •

Copy link
Copy Markdown

Summary

Prune Parquet row groups for mixed partition/data filters during Datasource V2 listing, addressing #67567. This extends the listing path using the shared safety checks from #68325.

Before

For a filter such as (year == "2023") | (x < 1000), Ray retains the complete expression above ReadFiles, so every candidate row group may be read.

After

Pass the retained filter to listing as a pruning hint. Arrow combines each file’s partition values with footer statistics to exclude row groups before read tasks are created. The complete filter still runs after the read.

Safe AND terms can prune alongside a UDF or synthesized-column condition. The hint falls back when earlier pruning could change row evaluation.

flowchart LR
  P["Logical planning: retained Filter"] -. pruning hint .-> L["IO: FooterReader<br/>partition values + statistics"]
  L --> R["ReadFiles: surviving row groups"]
  R --> F["Residual Filter"]
Loading

Subsystems

Logical planning / query optimization and IO.

Testing

Local validation passed on PyArrow 23.0.1, 25.0.1 and 26.0.1 using the base revision’s Ray wheel with the updated Python sources. Tests check returned rows and row groups read by workers, including the reported correctness regressions.

Focused pytest selections, each run in a separate process:

for test in \
  datasource_v2/test_footer_reader.py \
  unit/datasource_v2/test_read_units.py \
  datasource_v2/test_parquet_residual_pruning.py \
  test_predicate_pushdown.py::test_pushed_filter_matches_in_memory_filter
do
  python -m pytest -q "python/ray/data/tests/$test"
done

Related footer, planner and pushdown regressions, and pre-commit checks also passed.

AI assistance was used.

@m4ru1
m4ru1 requested a review from a team as a code owner November 5, 2026 02:57
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 5, 2026
@AarryaSaraf

Copy link
Copy Markdown
Contributor

Hi @m4ru1, thank you for your contribution! This is a nice simple implementation, but I think there are a few things to keep in mind:

  • We should be able to do the pruning during listing instead of during the read.
  • We can cover all such cases, instead of only the few comparison-based ones handled here.
  • A pushed data filter shouldn't turn pruning off.
  • The per-file partition substitution doesn't need to be format-specific.

@Jadiouo Jadiouo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, @m4ru1. I compared base f492423 and head b2ffe8c on a small local Hive dataset (V2 reader, 3 files x 5 row groups, with nulls and an all-null row group, year as int and as string), counting the bytes read through a wrapped filesystem.

For 20 OR filters the rows were identical between base and PR. (year==2020)|(x>12000) read 9 of 15 row groups (2.43 MB instead of 3.65 MB), and (year==2099)|(x>12000) read 5. Reversed operands and string partitions prune the same way. Nested AND, NOT, is_null, is_in, != and 3-way ORs fall back to a full scan, still correct.

Tests: 154 + 99 pass on the PR. On base the unit file fails to import and two logical tests fail, but test_parquet_mixed_or.py passes on base too, since it only compares rows.

Two small things:

  1. Could one e2e test assert that fewer row groups or bytes are read? Today only the unit tests would catch a pruning regression.
  2. The two new tests in test_read_files_logical.py sit after the if __name__ == "__main__": block.

@AarryaSaraf's points on the PR (pruning at listing time, a pushed-down filter disabling this, wider coverage) seem worth settling first.

m4ru1 commented Nov 8, 2026

Copy link
Copy Markdown
Author

@AarryaSaraf, in reply to your comment:

Thanks, Aarrya. I have moved the pruning decision into listing. Partition substitution now uses the existing column-substitution visitor in a common helper, with the Parquet adapter checking partition values and schema. An existing pushed data filter no longer turns it off: listing applies that filter first, then intersects the remaining groups with those selected after partition substitution. Both filters stay in place.

Nested AND/OR/NOT, leaf null checks and bounded literal IN are covered now. Narrow-integer IN and floating-point residual predicates still fall back; the description has a coverage table. The helper is format-independent, but I have kept admission in the source adapter: it must supply the values the reader actually returns, match the statistics to the reader’s field types, and preserve the empty-result schema. For example, MCAP keeps a message’s own topic even under a conflicting topic=.../ directory, so a path value is not automatically a valid substitute. Only the built-in local Hive Parquet path has those checks here; support for other sources needs its own adapter and reader tests.

The part I would like your input on is the empty result. Keeping a data group just for its schema still caused an unnecessary read. Instead, listing emits at most one schema-only manifest entry per verified shard; the reader uses it to emit a typed empty table, with normal partition columns and projection, before opening data files. Since #67037 also changes these shared interfaces, would you carry that instruction in the manifest?

Skipping a group also skips the work that could raise an error. A pushed expression such as division by zero can stop raising when the groups that would evaluate it are pruned. A task containing only schema-only entries does not construct the data scanner, so options checked there, such as batch_size, may not be validated either. I have kept that behavior without adding a separate validation pass or disabling the hint for those options. Errors from required footers and reads that actually run still propagate.

m4ru1 commented Nov 8, 2026

Copy link
Copy Markdown
Author

@Jadiouo, in reply to your review:

Thanks for checking the base too, Jadiouo. You caught the gap in the e2e test: it checked the answer but could not tell whether pruning happened. The new tests observe actual read workers and compare against the same code with the listing hint disabled.

For the original issue’s query, Arrow 17.0.0 and 23.0.1 both consumed 25 rather than 160 groups, from five rather than 32 files. The test checks the complete multiset of 5,000 (x, year, month) tuples, including duplicates, and the schema in both arms. Footer reads still happen; these are data-consumption counts, not total opens or bytes.

I moved the planning regressions into the listing rule’s test module, before its main guard. The focused tests were rerun on final 17bbe597 with the matching official aa00fdbb Ray Core. Each Arrow version passed 306 tests, including 21 schema-only tests, with one existing pre-footer empty-input failure marked expected. Full upstream CI has not run.

The performance comparison was rerun on the final integrated commit, using one 59.75 GB dataset with filters keeping 100%, 50% and 12.5% of the row groups. Each case has two pairs with reversed version order. Query time fell by 55.0–62.6% when half the groups remained and 94.2–95.9% when one eighth remained. Keeping every group gave mixed results: +5.48% and −0.42% query time. The description includes both pairs for each large-dataset case. Full output and schema matched in separate checks, but caches were not cleared, so these timings do not establish cold-cache performance or a repeatable gain.

Your exact 20-query set has not been rerun. If you still have the script, could you share it? The cases that fell back in your run would be useful to compare on the same input. Pruning is now in listing; the design question I raised with Aarrya is how the manifest should carry the empty-result schema without retaining a data group just for it.

@m4ru1
m4ru1 requested a review from Jadiouo November 9, 2026 14:30
@AarryaSaraf

Copy link
Copy Markdown
Contributor

Thanks for moving this to listing, but this is now 6.3k lines (5.2k of them tests), and I think a much smaller version could cover more. Right now pruning only kicks in for a bare filter → take_all on a local disk: adding map_batches after the filter, calling count(), reading from S3, or having one binary or timestamp column anywhere in the schema all read every row group again.

Something like this should be enough:

  • In FooterReader._read_and_chunk, build the fragment with the file's folder values (make_fragment(..., partition_expression=...)) and prune with split_by_row_group(residual, schema=...), where the schema includes the partition columns. pyarrow does the substitution itself, including nested AND/OR/NOT, isin, floats and timestamps, and _try_split_by_row_group already keeps every group when it can't.
  • Hand the residual to the indexer for any Filter directly above ReadFiles, not only at the plan root.
  • No other admission checks, and no schema-only manifest entries. When every group is pruned, behave like a pushed data filter does today: read_parquet(d).filter(expr=col("x") < 0) also produces no blocks on master. The empty-result schema can be fixed separately for every pushdown.
  • A few tests: one parametrized test through read_parquet(...).filter(...) that checks both the rows and the row groups read, plus one with a null folder value.
    Lets aim to keep this to a few hundred lines including tests.

@Jadiouo

Jadiouo commented Nov 10, 2026

Copy link
Copy Markdown

Thanks for the update, @m4ru1. I re-ran an equivalent of my earlier check on 17bbe59 against aa00fdb: a local Hive dataset (3 files x 5 row groups, with nulls and an all-null group; int and string year), 21 queries, counting the bytes read from the data files.

Rows and schema match base in all of them. (year==2020)|(x>12000) reads 4.2 MB instead of 6.7 MB, and nested AND, NOT, is_in and != now prune too. With a pushed filter first (filter(x>5000), then the mixed OR), it reads 2.1 MB instead of 4.2 MB, so the pushed filter no longer turns pruning off. A query that matches nothing keeps its schema and reads only the footers.

Both of my earlier points are addressed. You asked about my script: I no longer have the original, so here is the rebuilt one: https://gist.github.com/Jadiouo/35fcb95a0aee582953449dc44c65648f. It counts reads with strace, because my first version went through a wrapped filesystem, where this revision doesn't prune at all (that matches the local-only scope in the description).

@m4ru1
m4ru1 force-pushed the contribution/mixed-or-parquet-pruning branch from 8f0a595 to 17bbe59 Compare November 11, 2026 13:43

m4ru1 commented Nov 11, 2026 •

Copy link
Copy Markdown
Author

Thanks, @AarryaSaraf. I’ve kept the smaller revision local for now. It uses Arrow for listing-time pruning, keeps the existing filters, and leaves the empty-result schema fix separate.

I ran into two cases when passing the residual directly to statistics pruning with PyArrow 23.0.1. Both have one row group under p=a and the residual (p == "keep") | predicate:

  • x = [NaN, 0.0], predicate ~(x == 0.0): filtering the rows keeps NaN, but pruning removes the group.
  • x = [-0.0, +0.0], predicate x.is_in([+0.0]): eager filtering keeps the +0.0 row, but pruning removes the group.

There is related upstream work in Arrow #54915 for signed-zero membership and #50807 for NaN-aware pruning. Both are still open.

For now, the smaller revision skips extra residual pruning when it cannot establish safety, rather than rewriting parts of the expression. This can read more groups for mixed expressions, while preserving the existing pushed filter and final residual evaluation. I’d prefer to keep the underlying fixes in Arrow and avoid expanding this PR.

How would you think about this?

m4ru1 commented Nov 11, 2026

Copy link
Copy Markdown
Author

Hi @Jadiouo, sorry for the review-request noise. During my latest update, the PR temporarily included unrelated upstream changes in its diff and appears to have triggered additional CODEOWNERS requests. I should have checked the PR’s actual comparison before pushing. I’ve reverted the update, but the extra requests remain.

I’m discussing a more suitable approach with Aarrya.

Could you help remove the requests below, or point me to a maintainer who can?

  • People: richardliaw, MengjinYan, edoakes, andrewsykim, ryanaoleary
  • Teams: ray-core, ray-docs, ray-ci, ray-serve, ray-llm, ray-train, ray-tune, ray-docs-reviewers, kuberay

I tried removing them through the API and GitHub UI. The API returns 422 when resolving a team node, and the UI change does not persist after refreshing. Thanks for your help, and sorry for the extra work.

@AarryaSaraf

Copy link
Copy Markdown
Contributor

@m4ru1 The two cases you mentioned are already pruned during listing on master, with a plain data filter and no partition column. For example, read_parquet(...).filter(expr=~(col("x") == 0.0)) on [NaN, 0.0] returns [], and filter(expr=col("x").is_in([0.0])) on [-0.0, 0.0] also returns []. This means the gap is in pyarrow's statistics pruning itself (the Arrow PRs you linked), not in pruning the residual. So the residual doesn't need extra safety checks: it can go through the same pruning as the pushed data filter, and the NaN and signed-zero issue can be fixed separately for every pushdown.

m4ru1 commented Nov 15, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf and @Jadiouo for taking the time to work through this with me. Your feedback helped make the design much simpler.

I’ve pushed the revision using Arrow’s existing pruning path. It’s much smaller now and also works with S3 and operations after the filter. I’ve kept the tests focused on actual worker reads and rechecked the queries from Jadiouo’s reproducer.

Would you both have time to take another look when you get a chance?

@AarryaSaraf

AarryaSaraf commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

#68325 fixes the float case for the pushed filter. Its is_statistics_safe can gate the residual hint too, and its test_float_filter_keeps_nan_rows fails on this head with the fix applied (the hint prunes on the held-back filter), so it is a ready regression test for the first case.

m4ru1 commented Nov 19, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf for the guidance. I’ve used your helper from #68325 to guard the residual hint and added the arithmetic fallback, with both row-loss regressions covered. The nits are fixed too. I’d appreciate another look when you have a chance.

richardliaw pushed a commit that referenced this pull request Nov 20, 2026
…and integer overflow (#68325)

## Why

A filter pushed into a Parquet read can return fewer rows than the same
filter on materialized data:

```python
pq.write_table(pa.table({"id": [0, 1], "x": [40.0, float("nan")]}), path)
ds = ray.data.read_parquet(path)
ds.filter(expr=col("x") != 40.0).take_all()                # before: []   after: [{'id': 1, 'x': nan}]
ds.materialize().filter(expr=col("x") != 40.0).take_all()  # [{'id': 1, 'x': nan}]
```

`NaN != 40.0` is true in Arrow, NumPy and Spark, so row 1 matches. It is
lost because PyArrow skips whole row groups using the min/max in the
Parquet footer, and those min/max leave NaN out. The group `[40.0, NaN]`
is stored as min = max = 40.0, which reads as "every value is 40", so
PyArrow skips it. Whether the row comes back depends on its neighbours:
a group `[35.0, NaN]` keeps it.

Only filters that can match NaN are hit: `!=`, `not_in`, `is_in` with
NaN in its list, and negated comparisons such as `~(x >= 30.0)` or `(x
>= 30.0) == False`. Signed zero hits `is_in` too: `is_in([0.0])` on
`[-0.0, 0.0]` skips the group. `<`, `<=`, `>`, `>=`, `==` and `is_in`
with neither NaN nor zero in its list never lose a row, so skipping on
them is safe.

A second bug has the same symptom. PyArrow computes arithmetic in a
pushed filter in the column's own type, so on an int8 column `x + 100`
with `x = 100` wraps to `-56`, while Ray's in-memory filter widens to
int64 and gets `200`. `filter(expr=(col("x") + 100) > 120)` returns no
rows instead of one.

## Changes

`datasource_v2/common/pushdown_utils.py` adds two checks:
`is_statistics_safe` (a float column is used only in `<`, `<=`, `>`,
`>=`, `==`, a null check, or `is_in` with no NaN or zero in its list)
and `has_column_arithmetic`. A filter that fails either one is not
pushed into the scan; Ray runs it on the rows after reading, as it does
for any filter it cannot push.

- V2, `formats/parquet/parquet_scanner.py`: `push_filters` checks each
part of a top-level `&` on its own, so `(x != 40.0) & (id >= 0)` still
pushes `id >= 0`.
- V1, `datasource/parquet_datasource.py`: V1 pushes a filter whole or
not at all, so `apply_predicate` keeps the whole filter after the read
if any part fails.
- `tests/test_predicate_pushdown.py`:
`test_pushed_filter_matches_in_memory_filter` compares pushed and
in-memory results for 9 filters on V1 and V2.

## Cost

Filters that are no longer pushed lose row-group skipping. On a sorted
float column with 100 row groups:

| Filter | Row groups read, before | After |
| --- | --- | --- |
| `x != 40.0`, `x.not_in([40.0])` | 100 | 100 |
| `~(x >= 30.0)` | 31 | 100 |
| `x.is_in([40.0, 41.0])` | 2 | 2 |
| `x < 30.0` | 31 | 31 |

A TODO on each check names the upstream fix: NaN and signed zero in
PyArrow's statistics (apache/arrow#50807, apache/arrow#54915), and
widening in `Expr.to_pyarrow()`.

## Checks

- Not a duplicate: no open issue or PR covers this. #67855 adds a
separate pruning path that copies both checks; it will import them from
here once this lands.
- `pytest python/ray/data/tests/test_predicate_pushdown.py -k
test_pushed_filter_matches_in_memory_filter -v`: 18 passed. With both
checks disabled: 16 failed, 2 passed (the `x > 30.0` case, which is
safe).
- AI assistance was used; I reviewed every changed line.

Signed-off-by: Aarrya <[email protected]>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Fable 5.2 <[email protected]>
@m4ru1
m4ru1 force-pushed the contribution/mixed-or-parquet-pruning branch from 1ce0337 to c291e1f Compare November 20, 2026 22:00

m4ru1 commented Nov 20, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf for following up. I’ve rebased onto master and switched to the shared helpers from #68325, with the AND pruning and test cleanup included. I’d appreciate another look when you have a chance.

m4ru1 commented Nov 21, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf for catching these. The path and UDF cases now keep pruning the safe AND parts, and I’ve added regression coverage and simplified the tests as suggested. I kept subset to limit residual statistics work to the remaining candidate groups and corrected the misleading cache-isolation comment.

@m4ru1
m4ru1 force-pushed the contribution/mixed-or-parquet-pruning branch from 752d718 to b80be10 Compare November 21, 2026 15:46

@AarryaSaraf AarryaSaraf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could you trim the description before merge? python/ray/data/AGENTS.md asks for a short Summary, Before, After, Subsystems and Testing. A lot of the current text is history from earlier revisions (what this revision removed, older test layouts, thanks), which makes it harder to see what the final PR does.


Generated by Claude Code

m4ru1 commented Nov 21, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf for another careful pass. I’ve addressed these suggestions and trimmed the description to focus on the final behavior.

m4ru1 commented Nov 22, 2026

Copy link
Copy Markdown
Author

Thanks @AarryaSaraf for the careful review and all your help with this. Could you add the go label to kick off premerge when you have a chance?

@m4ru1
m4ru1 force-pushed the contribution/mixed-or-parquet-pruning branch from 6c706da to 96e5e8b Compare November 24, 2026 02:13
@AarryaSaraf AarryaSaraf added the go add ONLY when ready to merge, run all tests label Nov 24, 2026
Use partition facts and the existing Arrow footer pruning path during
Datasource V2 listing, retaining the full residual filter after the read.
Keep safe AND conjuncts eligible for pruning when other conjuncts are unsafe.

Rebase onto d6432c7 after ray-project#68325 merged and import its shared
float and arithmetic checks instead of carrying local copies. Consolidate
the reader-cast regression with the NaN and integer-overflow cases.

Signed-off-by: mora <[email protected]>
…UDFs

Check synthesized-column references and Arrow convertibility per AND
conjunct so unrelated parts can still prune. Clarify the candidate limit
provided by subset and strengthen pushed-filter coverage while removing
redundant test assertions.

Signed-off-by: mora <[email protected]>
Include the unset residual pruning hint in the read-unit exclusion test
expectation to match the arguments forwarded to FooterReaderActor.

Signed-off-by: mora <[email protected]>
Skip residual pruning when the retained expression is non-idempotent.
Cover the row-position regression and update footer test doubles for
the schema argument.

Signed-off-by: mora <[email protected]>
Share Parquet safety checks between listing and scan pushdown.
Name residual partition facts, clarify calls and simplify regression tests.

Signed-off-by: mora <[email protected]>
Annotate the dynamically generated PyArrow compute functions used by the residual pruning tests.

Signed-off-by: mora <[email protected]>

m4ru1 commented Nov 26, 2026

Copy link
Copy Markdown
Author

Thanks again, @AarryaSaraf, for the review and for adding the go label. Premerge #77811 passed on the current head (fe2c42d). Could you check whether auto-merge needs to be re-enabled after the last push, or let me know if anything else is needed from my side?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants