Skip to content

[Data] Cancel surplus task-pool reads once a downstream limit is satisfied - #68339

Open
wangzhigang1999 wants to merge 1 commit into
ray-project:masterfrom
wangzhigang1999:data-limit-surplus-taskpool-reads
Open

wangzhigang1999 wants to merge 1 commit into
ray-project:masterfrom
wangzhigang1999:data-limit-surplus-taskpool-reads

Conversation

@wangzhigang1999

Copy link
Copy Markdown

Description

Summary

Cancel outstanding task-pool reads that have exposed no output once all consumers have stopped requesting input after a limit. Downstream work can finish with the selected rows while the cancelled tasks clean up.

Before

A downstream map can receive the row selected by limit(1) and still lose the entire result if a surplus read fails. That read can also keep consuming CPU and fetching data until shutdown.

After

During the reverse walk of the physical plan, the executor follows a satisfied Limit through task-pool maps, including a separate Filter above a Read. It stops dispatching input to a producer once all its consumers have stopped requesting input. A task qualifies for graceful, recursive cancellation if it is active, has exposed no blocks, has no pending metadata emissions and has no tracked lineage. A normal shutdown skips a second interrupt to a task already cancelling, so its Python finally can finish. The caller can receive the selected result while cleanup continues.

A producer that has already delivered a block can still hold the only CPU needed by the next operator. The executor keeps polling its generator and discards unused references, including late error references. That frees space in the generator buffer and lets a finite producer finish. Already submitted metadata requests complete through the existing fetcher. While execution continues, the task completion callback runs once the stream has drained and its pending metadata emissions have been accounted for.

If the limit still needs the failed read, its error reaches the caller.

Subsystems

Execution (streaming executor and task-pool map operator), resource allocation/backpressure (draining discarded output).

Data flow

flowchart LR
    subgraph B["Before · Execution / streaming executor"]
        B1["Limit selects its rows"] --> B2["Poll surplus read as an ordinary task"]
        B2 --> B3["Late read error can fail dataset"]
    end
    subgraph A["After · Execution / streaming executor"]
        A1["Limit selects its rows"] --> A2["Stop dispatch to unneeded task-pool maps"]
        A2 --> A3["Cancel eligible tasks and drain unused refs"]
        A3 --> A4["Downstream map can finish with selected rows"]
    end
    classDef removed fill:#ffcdd2,color:#222
    classDef added fill:#c8e6c9,color:#222
    class B2,B3 removed
    class A2,A3,A4 added
Loading

Related issues

Fixes #68338.

Related to #47287. This change addresses in-flight tasks after the physical Limit has selected its result. #51966 concerns limit pushdown. #66143 fixed the ordering of a filter after a limit. A search for open Data PRs referencing #47287 or covering limit cancellation did not turn up a matching implementation.

Additional information

Testing

We ran the regression tests in an isolated CPU pod on a Kubernetes cluster. With the patch applied to the official Ray wheel at 9d5c32d1, all 114 related test executions passed. We also ran the new upstream test for a background metadata thread failure separately (1 passed). Coverage includes fused and unfused reads, ordered inputs, a required read that fails, nested tasks, returning the result while a gated finally is still running, and a single CPU shared by the read and the downstream map.

Pytest selections (paths shown relative to a Ray checkout)
t=python/ray/data/tests
cancel_cases='inflight_read or already_producing_read or nested_read_task or saturated_cpu'
for mode in 0 1; do
  RAY_DATA_METADATA_PREFETCH_ON_THREAD=$mode python -m pytest -q "$t/test_dataset_limits.py" -k "$cancel_cases"
done
python -m pytest -q "$t/test_streaming_executor.py" -k '(TestDataOpTask or TestOpTaskCancel or update_operator_states) and not preemption'
python -m pytest -q "$t/test_dataset_limits.py" "$t/test_execution_optimizer_limit_pushdown.py" "$t/unit/test_limit_operator.py" -k "not ($cancel_cases)"
python -m pytest -q "$t/test_streaming_executor.py::test_threaded_metadata_fetcher_propagates_unexpected_thread_failure"

The first selection passed 14 tests in each mode, followed by 27 lifecycle tests and 59 Limit/operator tests. Ruff, import order and Black also passed. The local macOS pyrefly process was killed during the Ray Data pre-commit check, including on a single-thread retry, so that check still needs a CI result.

Read resource usage and single-CPU timings

Read-side resource savings. A Paimon snapshot scan fed a filter and a 512-row limit, followed by GPU embedding and CPU clustering. We ran six stock and six patched trials in ABBA order on the same node. This experiment used an earlier backport to Ray 2.58.0 (cec0a091), PyPaimon 2.0.0 and Arrow 19.0.1. The clock starts when the limit reaches 512 rows.

Surplus read after the limit Stock Earlier backport
Time to the driver's task completion callback, median 42.766 s 0.236 s
Read worker process CPU time, mean 1.494 CPU·s 0.007 CPU·s
Bytes received on connections to object storage, mean 3,595,549 B 1,295 B

That workload saved about 1.49 CPU·s and 3.43 MiB of socket traffic per run. Socket counts include HTTP/TLS overhead. All 12 runs produced the same 512 IDs, byte-identical embedding vectors and identical cluster memberships. These measurements describe the surplus read's lifetime and resource consumption. Whole-job latency was outside the measurement window.

Current patch on master. In the single-CPU comparison, all three variants used the same official Linux x86_64 wheel at 9d5c32d1, Python 3.11 and identical dependencies. A finite read holds the only logical CPU and produces 19 more rows after a downstream limit selects the first. The final CPU map needs that CPU to run. Times below are from take_all() to return, excluding ray.init().

Metadata mode Unmodified master, median of 3 Current patch, median of 3 Earlier patch that skipped polling, 1 run
Inline 1.996 s 1.981 s Timed out at 20 s
Background thread 3.023 s 2.089 s Timed out at 20 s

Both stock and current code returned exactly row 0 in all six runs per variant. Only the intermediate patch stranded the read at generator backpressure and prevented the map from starting. This comparison checks forward progress under CPU contention.

AI assistance was used to develop the patch, prepare the reproducer and run the comparisons.

@wangzhigang1999
wangzhigang1999 marked this pull request as ready for review November 19, 2026 09:59
@wangzhigang1999
wangzhigang1999 requested a review from a team as a code owner November 19, 2026 09:59

@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 a mechanism to gracefully cancel and drain unneeded upstream tasks when downstream early termination (such as a satisfied limit) makes their output unnecessary. It adds a CANCELLING state to the task generator lifecycle, implements output discarding and draining in DataOpTask, and propagates input abandonment upstream through the operator topology. Feedback on these changes suggests catching TimeoutError and other exceptions in _drain_discarded_output to prevent executor crashes, defensively checking for dependency existence in topology to avoid KeyErrors, and performing a reverse topological pass during operator state updates to eliminate propagation lag.

@cursor cursor Bot 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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit d640490. Configure here.

@wangzhigang1999

Copy link
Copy Markdown
Author
  • Draining: _next_sync(0) returns a nil ref when nothing’s ready and an error ref if the reader fails. We mark the drain done on StopIteration. Catching every exception could finish it too early.
  • Topology: I checked 13 plans, including shared Dataset branches and shuffle rewrites. Every consumer was present. Skipping a missing one could cancel a read too early.
  • Traversal order: The cancel check already walks the plan in reverse, so a satisfied limit reaches the filter and then the read in the same pass.
  • Lineage: Ray Data disables reconstruction for plans containing a Limit, so they don’t hit that reset path today. We can revisit the flag when Limit supports reconstruction.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 19, 2026
sampan-s-nayak pushed a commit that referenced this pull request Nov 24, 2026
## Summary

Stop a DataSource V2 file reader as soon as it yields its pushed-down
row budget. A zero-row budget skips Arrow dataset construction.

## Before and after

Previously the reader pulled another batch before checking its budget.
In an ordered two-file ORC read, both files were scanned even when the
first batch satisfied the limit. The check now runs before the next
pull. Errors still propagate from fragments needed to fill the budget,
and parallel scans may already have prefetched data.

## Subsystem

IO (DataSource V2 shared file reader).

```mermaid
flowchart LR
    subgraph Before["Before · IO / FileReader"]
        A1["Yield the final batch"] --> A2["Pull another batch"] --> A3["Check the budget and stop"]
    end
    subgraph After["After · IO / FileReader"]
        B1["Yield the final batch"] --> B2["Check the budget and stop"]
    end
    classDef removed fill:#ffcdd2,color:#222
    classDef added fill:#c8e6c9,color:#222
    class A2 removed
    class B2 added
```

## Related work

Fixes #68341. #51966 tracks propagating limits into reads. #68338 and
#68339 address surplus tasks after the downstream physical limit is
satisfied. This change addresses the iterator inside a single read task
after the limit has already reached the reader. The open-PR search found
no change to this reader loop.

## Testing

```bash
python -m pytest -q \
  python/ray/data/tests/unit/datasource_v2/test_file_reader.py \
  python/ray/data/tests/unit/datasource_v2/test_orc_file_reader.py \
  python/ray/data/tests/unit/datasource_v2/test_orc_datasource_v2.py
```

391 passed on `2c9d2b98b1` using the branch's Ray Data code with Python
3.12, PyArrow 26.0.1, and Ray Core nightly `eb50407602`.

Both shared-reader regression tests raise `OSError` with the PR base
reader (`3cba3775f0`). On this branch, both pass.

- `limit=0` returns `[]` for a corrupt gzip file.
- `limit=1` returns the first row and the iterator finishes normally
when a corrupt file follows a valid one, using the default execution
settings.

---------

Signed-off-by: zzchun <[email protected]>
Signed-off-by: will <[email protected]>

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] A late read error can fail a dataset after limit() has delivered the requested rows

1 participant