ray icon indicating copy to clipboard operation
ray copied to clipboard

[Data] Predicate pushdown drops execution options from expression filters and fuses incompatible filters

Open m4ru1 opened this issue 6 days ago • 1 comments

What happened + What you expected to happen

Execution options passed to Dataset.filter(expr=..., ...)—such as runtime_env, num_cpus, num_gpus, memory, resources, concurrency, compute, and ray_remote_args_fn—work when the filter stays in place, but are silently dropped whenever predicate pushdown splits, merges, or moves the filter. In addition, consecutive .filter(expr=...) calls with different execution options are fused together and lose both sets of options.

For example, when an expression @udf reads os.environ["THRESHOLD"] provided via runtime_env:

# Succeeds: standalone UDF filter receives THRESHOLD="7"
ds.filter(expr=above_threshold(col("id")), runtime_env=env).take_all()

# Fails with KeyError('THRESHOLD'): id >= 0 pushes into the read and the remaining filter loses runtime_env
ds.filter(expr=(col("id") >= 0) & above_threshold(col("id")), runtime_env=env).take_all()

The same option loss happens across all four predicate-pushdown rewrites:

  • Partial pushdown into a read (e.g., (col("id") >= 0) & udf_expr, or when a scanner leaves unpushed conjuncts such as col("path"))
  • Chained .filter(expr=...) calls (even when their execution options conflict)
  • Pushing .filter(expr=...) past .sort(), .repartition(), .random_shuffle(), or .rename_columns() / .select_columns()
  • Pushing .filter(expr=...) into .union() branches

Expected behavior: Dataset.filter(expr=...) should preserve its execution options when predicate pushdown splits or moves the filter, and consecutive .filter(expr=...) calls should only be fused when their execution options and compute strategies are compatible.

Cause: Rewrite paths in PredicatePushdown (python/ray/data/_internal/logical/rules/predicate_pushdown.py) and ReadFiles.apply_predicate construct replacement Filter operators with default options instead of carrying over the original operator's options, and consecutive Filter fusion in PredicatePushdown does not check option compatibility.

Versions / Dependencies

  • Ray 2.60.1 and master (976013db03)
  • Python 3.13.5, PyArrow 26.0.1, macOS (arm64)

Reproduction script

import os
import tempfile

import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import ray
from ray.data.datatype import DataType
from ray.data.expressions import col, udf


@udf(return_dtype=DataType.bool())
def above_threshold(x):
    return pc.greater(x, int(os.environ["THRESHOLD"]))


with tempfile.TemporaryDirectory() as tmpdir:
    path = f"{tmpdir}/data.parquet"
    pq.write_table(pa.table({"id": list(range(10))}), path)
    env = {"env_vars": {"THRESHOLD": "7"}}
    ok = ray.data.read_parquet(path).filter(
        expr=above_threshold(col("id")), runtime_env=env
    ).take_all()
    print("1. standalone ->", sorted(ok, key=lambda r: r["id"]))
    cases = {
        "2. partial pushdown": ray.data.read_parquet(path).filter(
            expr=(col("id") >= 0) & above_threshold(col("id")), runtime_env=env
        ),
        "3. chained filters": ray.data.read_parquet(path).filter(
            expr=above_threshold(col("id")),
            runtime_env={"env_vars": {"THRESHOLD": "3"}},
        ).filter(expr=above_threshold(col("id")), runtime_env=env),
        "4. after sort": ray.data.read_parquet(path).sort("id").filter(
            expr=above_threshold(col("id")), runtime_env=env
        ),
        "5. after union": (
            ray.data.read_parquet(path).union(ray.data.read_parquet(path))
            .filter(expr=above_threshold(col("id")), runtime_env=env)
        ),
    }
    for name, ds in cases.items():
        try:
            print(name, "->", sorted(ds.take_all(), key=lambda r: r["id"]))
        except Exception as e:
            print(
                f"{name} -> {type(e).__name__}: {repr(getattr(e, 'cause', e))}"
            )

Output:

1. standalone -> [{'id': 8}, {'id': 9}]
2. partial pushdown -> RayTaskError(KeyError): KeyError('THRESHOLD')
3. chained filters -> RayTaskError(KeyError): KeyError('THRESHOLD')
4. after sort -> RayTaskError(KeyError): KeyError('THRESHOLD')
5. after union -> RayTaskError(KeyError): KeyError('THRESHOLD')

Issue Severity

Medium: It is a significant difficulty but I can work around it.

m4ru1 avatar Nov 28 '26 15:11 m4ru1

I opened #68625 to fix this in PredicatePushdown (python/ray/data/_internal/logical/rules/predicate_pushdown.py) without changing datasource apply_predicate signatures:

  • Preserve options on pushdown / split: Rebind relocated and residual Filter operators via a shared _rebind_filter helper (dataclasses.replace with per_block_limit=None, processed_join_conjuncts=()) across passthrough, Union branches, Join side branches, and partial datasource pushdown.
  • Unwrap scanner-declined residuals: When input_op.apply_predicate(...) returns a residual Filter with default options, combine its predicate with any unconvertible conjuncts via combine_predicates into a single Filter carrying filter_op's original options.
  • Gate filter fusion on option compatibility: Check are_op_remote_args_compatible (shielding nested resources dicts from in-place canonicalization) and FuseOperators._fuse_compute_strategy in _try_fuse_filters, retaining upstream remote args like physical FuseOperators.

Unit and end-to-end regression tests covering all four rewrite paths are included in #68625. Happy to adjust if maintainers prefer a different boundary!

m4ru1 avatar Nov 28 '26 15:11 m4ru1