Skip to content

[Data] Run projection/predicate pushdown before limit pushdown - #64651

Merged
goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
goutamvenkat-anyscale:fix-projection-pushdown-before-limit
Jul 10, 2026
Merged

goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
goutamvenkat-anyscale:fix-projection-pushdown-before-limit

Conversation

@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor

Why

select_columns([...]) (and read_parquet(columns=[...]), which is rewired to it) inserts a Project directly above the read, and filter(expr=...) inserts a Filter there. These are meant to be pushed into the reader so it prunes columns / skips rows at the source.

But when a .limit() is also present, LimitPushdownRule runs first and pushes the Limit down between that Project/Filter and the read. ProjectionPushdown/PredicatePushdown only push an operator into a read when the two are adjacent, so once the Limit is wedged in, the projection/predicate is stranded above it and the reader ends up reading every column and every row — defeating pushdown exactly in the common "select a few columns, take N rows" pattern.

Example — read_parquet().select_columns(["a","b"]).limit(512).map(...) optimized to:

Map -> Project -> Limit -> Read        # Project stranded; Read reads all columns

Fix

Declare ProjectionPushdown and PredicatePushdown as dependencies of LimitPushdownRule so they run first. The selection/filter is absorbed into the read while still adjacent, then the Limit pushes past the already-pruned read:

Map -> Limit -> Read(pruned)           # Project/Filter folded into the read

While adding the dependency I also fixed Ruleset.__iter__: its BFS emitted a rule once per incoming edge, so a rule with two dependencies (now LimitPushdownRule) was yielded twice. Replaced it with a dedup'd topological sort (Kahn's), preserving insertion order among independent rules.

Testing

  • New behavior verified on both V1 (ReadParquet) and V2 (ReadFilesParquetV2): the Project/Filter is now folded into the read even with a .limit() present.
  • Existing optimizer suites pass: limit-pushdown, predicate-pushdown, projection-fusion, idempotency guards, ruleset unit, optimizer basic/advanced (262 tests).

🤖 Generated with Claude Code

@goutamvenkat-anyscale
goutamvenkat-anyscale requested a review from a team as a code owner July 10, 2026 00:11

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request adds a dependency declaration for the LimitPushdownRule and updates the Ruleset iterator to use Kahn's algorithm for topological sorting. However, the new topological sort implementation contains critical bugs: a continue statement can prematurely skip decrementing the in-degree of dependents, stranding downstream rules, and there is inconsistent keying between id(dep) and dep.rule which breaks the sort when multiple nodes share the same rule type. A refactored implementation has been suggested to resolve these issues.

@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the fix-projection-pushdown-before-limit branch 2 times, most recently from ea06eeb to dafa4d8 Compare July 10, 2026 00:25
@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces dependency-based ordering for logical rules in Ray Data, ensuring that projection and predicate pushdowns run before limit pushdown. It rewrites the ruleset iteration to use Kahn's algorithm for topological sorting. The review feedback points out a bug in the cycle detection logic where a cycle could go undetected if an independent root node exists, and suggests simplifying the topological sort by removing a redundant yielded set.

@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the fix-projection-pushdown-before-limit branch from dafa4d8 to 1562a3d Compare July 10, 2026 00:34
@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request adds dependency definitions to the LimitPushdownRule and refactors the Ruleset class to use Kahn's algorithm for topological sorting, which improves cycle detection and ensures correct rule execution order. The review feedback suggests improving the type annotation of the new dependencies method for better static type checking, and tracking added edges in _build_graph to prevent duplicate edges and redundant in-degree increments when relationships are defined redundantly.

@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the fix-projection-pushdown-before-limit branch from 1562a3d to 9126d25 Compare July 10, 2026 00:44
LimitPushdownRule pushes a Limit through a Project/Filter that sits directly above a read. When it runs before ProjectionPushdown/PredicatePushdown, the Limit lands between that operator and the read, so the column selection or filter can no longer be pushed into the reader -- it gets stranded above the Limit and the reader reads every column / every row.

Declare ProjectionPushdown and PredicatePushdown as dependencies of LimitPushdownRule so they run first and get absorbed into the read while still adjacent; the Limit then pushes past the already-pruned read.

Also fix Ruleset.__iter__ to yield each rule exactly once in true topological order (Kahn's algorithm). The previous BFS emitted a rule once per incoming edge, so a rule with multiple dependencies (now LimitPushdownRule) was duplicated.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Goutam <[email protected]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the fix-projection-pushdown-before-limit branch from 9126d25 to b7a2587 Compare July 10, 2026 00:45
@goutamvenkat-anyscale goutamvenkat-anyscale added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Jul 10, 2026

@ayushk7102 ayushk7102 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.

LGTM

@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 52b3a95 into ray-project:master Jul 10, 2026
3 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the fix-projection-pushdown-before-limit branch July 10, 2026 06:43
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…roject#64651)

## Why

`select_columns([...])` (and `read_parquet(columns=[...])`, which is
rewired to it) inserts a `Project` directly above the read, and
`filter(expr=...)` inserts a `Filter` there. These are meant to be
pushed *into* the reader so it prunes columns / skips rows at the
source.

But when a `.limit()` is also present, `LimitPushdownRule` runs first
and pushes the `Limit` down **between** that `Project`/`Filter` and the
read. `ProjectionPushdown`/`PredicatePushdown` only push an operator
into a read when the two are adjacent, so once the `Limit` is wedged in,
the projection/predicate is stranded above it and the reader ends up
**reading every column and every row** — defeating pushdown exactly in
the common "select a few columns, take N rows" pattern.

Example — `read_parquet().select_columns(["a","b"]).limit(512).map(...)`
optimized to:

```
Map -> Project -> Limit -> Read        # Project stranded; Read reads all columns
```

## Fix

Declare `ProjectionPushdown` and `PredicatePushdown` as dependencies of
`LimitPushdownRule` so they run first. The selection/filter is absorbed
into the read while still adjacent, then the `Limit` pushes past the
already-pruned read:

```
Map -> Limit -> Read(pruned)           # Project/Filter folded into the read
```

While adding the dependency I also fixed `Ruleset.__iter__`: its BFS
emitted a rule once per incoming edge, so a rule with two dependencies
(now `LimitPushdownRule`) was yielded twice. Replaced it with a dedup'd
topological sort (Kahn's), preserving insertion order among independent
rules.

## Testing

- New behavior verified on both V1 (`ReadParquet`) and V2
(`ReadFilesParquetV2`): the `Project`/`Filter` is now folded into the
read even with a `.limit()` present.
- Existing optimizer suites pass: limit-pushdown, predicate-pushdown,
projection-fusion, idempotency guards, ruleset unit, optimizer
basic/advanced (262 tests).

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

---------

Signed-off-by: Goutam <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Sep 17, 2026
…down at Limit (#66143)

## Description

The default optimizer currently rewrites `Filter(Limit(input))` as
`Limit(Filter(input))`. For example, `range(10).limit(3).filter(id >=
3)` returns IDs 3, 4, and 5 instead of an empty result. This silently
changes which rows the query selects.

Remove `Limit`'s predicate pass-through trait so filters cannot cross
that boundary. Safe projection rebinding still works, and filters
originally placed before the limit remain eligible for reader pushdown.
Update the existing tests that assumed these operations commute, and add
eight regression cases covering Range/Parquet, one/three input blocks,
and partial/empty filtered results after a rename.

The complex-pipeline test now compares against an explicit
materialization boundary after the limit and verifies that the
post-limit filter stays outside the reader.

## Related issues

Fixes #66142.

## Duplicate-work check

Rechecked issues and PRs on 2026-09-13 using `limit filter`, `filter
limit`, `predicate limit`, and `Filter(Limit`, including current open
PRs. No matching in-flight fix was found. #51966 concerns avoiding
unnecessary reads; merged #64651 changes pushdown rule ordering for
efficiency. The tested baseline already includes #64651 and still
returns the incorrect rows described above.

## Validation

Revalidated on 2026-09-13. Linux x86_64, Python 3.11.15, Ray
`3.0.0.dev0`. The official nightly wheel and source checkout both use
commit `be4889928d3a396d7a1476d1bac3288dac72f9ab`; Python sources are
linked using `setup-dev.py`.

- Two minimal reproduction cases, repeated three times each: all six
fail on the baseline and all six return the expected rows after this
change.
- The complete predicate-pushdown and limit-pushdown test modules: **88
passed**.
- Ruff, import sorting, Black, pydoclint, docstyle, and the other
pre-commit hooks applicable to the changed files pass, as does `git diff
--check`.

```bash
RAY_USAGE_STATS_ENABLED=0 python -c 'import ray,pytest; raise SystemExit(pytest.main(["python/ray/data/tests/test_predicate_pushdown.py", "python/ray/data/tests/test_execution_optimizer_limit_pushdown.py", "-q", "--tb=short"]))'
```

The command imports the installed Ray package before pytest to use the
matching wheel's compiled components with the linked local Python
modules. This does not constitute a full C++ build or full-repository
test run.

## Compatibility

Queries that filter after a limit will preserve the requested operation
order. They may push fewer predicates into readers, because moving those
predicates across the limit changes results. No API or configuration
changes are introduced.

Signed-off-by: Rui <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…down at Limit (ray-project#66143)

## Description

The default optimizer currently rewrites `Filter(Limit(input))` as
`Limit(Filter(input))`. For example, `range(10).limit(3).filter(id >=
3)` returns IDs 3, 4, and 5 instead of an empty result. This silently
changes which rows the query selects.

Remove `Limit`'s predicate pass-through trait so filters cannot cross
that boundary. Safe projection rebinding still works, and filters
originally placed before the limit remain eligible for reader pushdown.
Update the existing tests that assumed these operations commute, and add
eight regression cases covering Range/Parquet, one/three input blocks,
and partial/empty filtered results after a rename.

The complex-pipeline test now compares against an explicit
materialization boundary after the limit and verifies that the
post-limit filter stays outside the reader.

## Related issues

Fixes ray-project#66142.

## Duplicate-work check

Rechecked issues and PRs on 2026-09-13 using `limit filter`, `filter
limit`, `predicate limit`, and `Filter(Limit`, including current open
PRs. No matching in-flight fix was found. ray-project#51966 concerns avoiding
unnecessary reads; merged ray-project#64651 changes pushdown rule ordering for
efficiency. The tested baseline already includes ray-project#64651 and still
returns the incorrect rows described above.

## Validation

Revalidated on 2026-09-13. Linux x86_64, Python 3.11.15, Ray
`3.0.0.dev0`. The official nightly wheel and source checkout both use
commit `be4889928d3a396d7a1476d1bac3288dac72f9ab`; Python sources are
linked using `setup-dev.py`.

- Two minimal reproduction cases, repeated three times each: all six
fail on the baseline and all six return the expected rows after this
change.
- The complete predicate-pushdown and limit-pushdown test modules: **88
passed**.
- Ruff, import sorting, Black, pydoclint, docstyle, and the other
pre-commit hooks applicable to the changed files pass, as does `git diff
--check`.

```bash
RAY_USAGE_STATS_ENABLED=0 python -c 'import ray,pytest; raise SystemExit(pytest.main(["python/ray/data/tests/test_predicate_pushdown.py", "python/ray/data/tests/test_execution_optimizer_limit_pushdown.py", "-q", "--tb=short"]))'
```

The command imports the installed Ray package before pytest to use the
matching wheel's compiled components with the linked local Python
modules. This does not constitute a full C++ build or full-repository
test run.

## Compatibility

Queries that filter after a limit will preserve the requested operation
order. They may push fewer predicates into readers, because moving those
predicates across the limit changes results. No API or configuration
changes are introduced.

Signed-off-by: Rui <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants