Skip to content

[Autoscaling] Fix request_remaining cases that #66001 missed - #66370

Merged
owenowenisme merged 1 commit into
ray-project:masterfrom
pseudo-rnd-thoughts:train/fix_test_data_resource_cleanup
Sep 22, 2026
Merged

owenowenisme merged 1 commit into
ray-project:masterfrom
pseudo-rnd-thoughts:train/fix_test_data_resource_cleanup

Conversation

@pseudo-rnd-thoughts

@pseudo-rnd-thoughts pseudo-rnd-thoughts commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Description

(SplitCoordinator pid=5837) Starting execution of Dataset dataset_034T4PAPkriY9ipgNj4aE9_0. Full logs are in /tmp/ray/session_2026-09-22_05-38-03_424978_5294/logs/ray-data
(SplitCoordinator pid=5837) Execution plan of Dataset dataset_034T4PAPkriY9ipgNj4aE9_0: InputDataBuffer[Input] -> TaskPoolMapOperator[ReadRange]
(SplitCoordinator pid=5837) [dataset]: A new progress UI is available. To enable, set `ray.data.DataContext.get_current().enable_rich_progress_bars = True` and `ray.data.DataContext.get_current().use_ray_tqdm = False`.
(SplitCoordinator pid=5837) Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): ray::_AutoscalingCoordinatorActor.request_resources() (pid=5838, ip=172.16.0.5, actor_id=e6ec4690ede4bc62b6d6549501000000, repr=<ray.data._internal.cluster_autoscaler.default_autoscaling_coordinator._AutoscalingCoordinatorActor object at 0x7fc9c6c86ba0>)
(SplitCoordinator pid=5837)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(SplitCoordinator pid=5837)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(SplitCoordinator pid=5837)   File "/rayci/python/ray/data/_internal/cluster_autoscaler/default_autoscaling_coordinator.py", line 402, in request_resources
(SplitCoordinator pid=5837)     share_leftover_resource_types = frozenset(request_remaining or ())
(SplitCoordinator pid=5837)                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(SplitCoordinator pid=5837) TypeError: 'bool' object is not iterable

#66001 updated the implementation of resource_remaining from bool to Optional[list[ExecutionResources]], however, there are two cases where this typing wasn't updated

@pseudo-rnd-thoughts pseudo-rnd-thoughts added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 22, 2026
@pseudo-rnd-thoughts
pseudo-rnd-thoughts marked this pull request as ready for review September 22, 2026 13:41
@pseudo-rnd-thoughts
pseudo-rnd-thoughts requested a review from a team as a code owner September 22, 2026 13:41

@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 updates the rate-based cluster autoscaler to request standard resource types and fixes an iteration bug in get_total_resources by iterating over resources.values() instead of resources. The reviewer suggested a more efficient and idiomatic way to sum the execution resources using ExecutionResources.combine_sum instead of a loop.

Comment on lines 606 to 609
total = ExecutionResources.zero()
for res in resources:
for res in resources.values():
total = total.add(ExecutionResources.from_resource_dict(res))
return total

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.

medium

Using ExecutionResources.combine_sum is more efficient and idiomatic here. It sums the resources in a single pass and avoids allocating intermediate ExecutionResources objects for each addition, which is especially beneficial if there are many nodes in the cluster.

Suggested change
total = ExecutionResources.zero()
for res in resources:
for res in resources.values():
total = total.add(ExecutionResources.from_resource_dict(res))
return total
return ExecutionResources.combine_sum(
ExecutionResources.from_resource_dict(res) for res in resources.values()
)

@iamjustinhsu

Copy link
Copy Markdown
Contributor

Duplicate of #66366

@iamjustinhsu iamjustinhsu marked this as a duplicate of #66366 Sep 22, 2026
@owenowenisme
owenowenisme merged commit d772999 into ray-project:master Sep 22, 2026
5 checks passed
xinyuangui2 added a commit to xinyuangui2/ray that referenced this pull request Sep 22, 2026
matthewdeng pushed a commit that referenced this pull request Sep 22, 2026
… from input to output (#66369)

## Description

A Ray Train job dies before it reads a single row. Its input pipeline
shuffles a dataset that was already materialized:

```python
ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
```

```
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.
```

### Why it happens

`BlockRefCounter` tracks object-store memory. To do that, it asks Ray
Core to call it back when a block is freed. Only the block's owner may
register that callback, and the owner is the process that created the
block.

`streaming_split` runs the plan inside a `SplitCoordinator` actor. But
the blocks were created earlier, by `materialize()` on the caller. The
same holds for any `InputData` source, such as `from_arrow` or
`from_pandas`.

```
  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed
```

`AllToAllOperator.all_inputs_done` registered a callback for every block
it sent downstream. That is right for sort, shuffle and repartition.
Their output blocks come from reduce tasks the operator itself
submitted, so it owns them.

It is wrong for `RandomizeBlocks`. That operator creates no blocks. It
reorders its input bundles and returns the same refs. So the actor asks
Ray Core to watch blocks the caller owns, Ray Core refuses, and the
execution fails.

### The fix

Register a block only when its ref was not among the operator's inputs:

```python
input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)
```

Returned refs are skipped. New ones are still registered.
`OutputSplitter` already uses the same test on `_split_block` output.

**Why not `RefBundle.owns_blocks`?** That flag says whether the blocks
may be destroyed, not who made them. The shuffle, sort and
split-repartition schedulers copy it from their input onto blocks their
own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)`
at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter
on that flag would drop real blocks from the counter whenever the source
is `from_*` or `materialize`, and under-report their memory. Bugbot
caught this in the first version of this PR.

### Where it came from

#64157 added `BlockRefCounter` to the operators in 2.57, and the crash
has been there since. It was reported from a Ray Train job on 2.58.0.
That job's input pipeline is `from_arrow → repartition → materialize →
randomize_block_order → map_batches → repartition → streaming_split`,
and all four splits fail at 0 rows.

## Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning
`BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and
the error text "Cannot register an out-of-scope callback". Two open PRs
touch the counter: #65878 (consumer-held bytes) and #65220 (deferring
gRPC frees). Neither changes this registration path, and no open issue
tracks the crash, so this is not duplicate work.

## Additional information

**Tests.** `test_streaming_split_over_materialized_all_to_all`
reproduces the failure end to end. The two tests in `test_operators.py`
cover both sides of the check; the second fails if the check uses
`owns_blocks`, which is what the first version of this PR did.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s
```

The last command needs #66366 applied locally. On master,
`request_remaining=True` in `rate_based_cluster_autoscaler.py` raises
`TypeError: 'bool' object is not iterable` in the autoscaling
coordinator, which makes these tests flaky.

**CI.** The `buildkite/premerge` failure here is that same master bug.
All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a
file this PR does not touch. #66366 and #66370 both fix it, and this PR
is unblocked once either one lands.

**AI assistance was used** for the diagnosis, the patch, and this
description.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
… from input to output (ray-project#66369)

## Description

A Ray Train job dies before it reads a single row. Its input pipeline
shuffles a dataset that was already materialized:

```python
ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
```

```
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.
```

### Why it happens

`BlockRefCounter` tracks object-store memory. To do that, it asks Ray
Core to call it back when a block is freed. Only the block's owner may
register that callback, and the owner is the process that created the
block.

`streaming_split` runs the plan inside a `SplitCoordinator` actor. But
the blocks were created earlier, by `materialize()` on the caller. The
same holds for any `InputData` source, such as `from_arrow` or
`from_pandas`.

```
  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed
```

`AllToAllOperator.all_inputs_done` registered a callback for every block
it sent downstream. That is right for sort, shuffle and repartition.
Their output blocks come from reduce tasks the operator itself
submitted, so it owns them.

It is wrong for `RandomizeBlocks`. That operator creates no blocks. It
reorders its input bundles and returns the same refs. So the actor asks
Ray Core to watch blocks the caller owns, Ray Core refuses, and the
execution fails.

### The fix

Register a block only when its ref was not among the operator's inputs:

```python
input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)
```

Returned refs are skipped. New ones are still registered.
`OutputSplitter` already uses the same test on `_split_block` output.

**Why not `RefBundle.owns_blocks`?** That flag says whether the blocks
may be destroyed, not who made them. The shuffle, sort and
split-repartition schedulers copy it from their input onto blocks their
own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)`
at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter
on that flag would drop real blocks from the counter whenever the source
is `from_*` or `materialize`, and under-report their memory. Bugbot
caught this in the first version of this PR.

### Where it came from

ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash
has been there since. It was reported from a Ray Train job on 2.58.0.
That job's input pipeline is `from_arrow → repartition → materialize →
randomize_block_order → map_batches → repartition → streaming_split`,
and all four splits fail at 0 rows.

## Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning
`BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and
the error text "Cannot register an out-of-scope callback". Two open PRs
touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring
gRPC frees). Neither changes this registration path, and no open issue
tracks the crash, so this is not duplicate work.

## Additional information

**Tests.** `test_streaming_split_over_materialized_all_to_all`
reproduces the failure end to end. The two tests in `test_operators.py`
cover both sides of the check; the second fails if the check uses
`owns_blocks`, which is what the first version of this PR did.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s
```

The last command needs ray-project#66366 applied locally. On master,
`request_remaining=True` in `rate_based_cluster_autoscaler.py` raises
`TypeError: 'bool' object is not iterable` in the autoscaling
coordinator, which makes these tests flaky.

**CI.** The `buildkite/premerge` failure here is that same master bug.
All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a
file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR
is unblocked once either one lands.

**AI assistance was used** for the diagnosis, the patch, and this
description.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
… from input to output (ray-project#66369)

## Description

A Ray Train job dies before it reads a single row. Its input pipeline
shuffles a dataset that was already materialized:

```python
ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
```

```
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.
```

### Why it happens

`BlockRefCounter` tracks object-store memory. To do that, it asks Ray
Core to call it back when a block is freed. Only the block's owner may
register that callback, and the owner is the process that created the
block.

`streaming_split` runs the plan inside a `SplitCoordinator` actor. But
the blocks were created earlier, by `materialize()` on the caller. The
same holds for any `InputData` source, such as `from_arrow` or
`from_pandas`.

```
  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed
```

`AllToAllOperator.all_inputs_done` registered a callback for every block
it sent downstream. That is right for sort, shuffle and repartition.
Their output blocks come from reduce tasks the operator itself
submitted, so it owns them.

It is wrong for `RandomizeBlocks`. That operator creates no blocks. It
reorders its input bundles and returns the same refs. So the actor asks
Ray Core to watch blocks the caller owns, Ray Core refuses, and the
execution fails.

### The fix

Register a block only when its ref was not among the operator's inputs:

```python
input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)
```

Returned refs are skipped. New ones are still registered.
`OutputSplitter` already uses the same test on `_split_block` output.

**Why not `RefBundle.owns_blocks`?** That flag says whether the blocks
may be destroyed, not who made them. The shuffle, sort and
split-repartition schedulers copy it from their input onto blocks their
own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)`
at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter
on that flag would drop real blocks from the counter whenever the source
is `from_*` or `materialize`, and under-report their memory. Bugbot
caught this in the first version of this PR.

### Where it came from

ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash
has been there since. It was reported from a Ray Train job on 2.58.0.
That job's input pipeline is `from_arrow → repartition → materialize →
randomize_block_order → map_batches → repartition → streaming_split`,
and all four splits fail at 0 rows.

## Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning
`BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and
the error text "Cannot register an out-of-scope callback". Two open PRs
touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring
gRPC frees). Neither changes this registration path, and no open issue
tracks the crash, so this is not duplicate work.

## Additional information

**Tests.** `test_streaming_split_over_materialized_all_to_all`
reproduces the failure end to end. The two tests in `test_operators.py`
cover both sides of the check; the second fails if the check uses
`owns_blocks`, which is what the first version of this PR did.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s
```

The last command needs ray-project#66366 applied locally. On master,
`request_remaining=True` in `rate_based_cluster_autoscaler.py` raises
`TypeError: 'bool' object is not iterable` in the autoscaling
coordinator, which makes these tests flaky.

**CI.** The `buildkite/premerge` failure here is that same master bug.
All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a
file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR
is unblocked once either one lands.

**AI assistance was used** for the diagnosis, the patch, and this
description.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
sai-miduthuri added a commit that referenced this pull request Oct 26, 2026
Reverts #66002 on `releases/2.60.0`. This is the release-branch
counterpart of #67337, which reverts #66646 and then #66002 on master.
This branch never had #66646, so only #66002 is reverted here.

## Why

#66002 pins every Train V2 worker to a node from the
AutoscalingCoordinator's reservation. #67337 explains why that
reservation isn't accurate enough to pin to:

- It counts draining nodes and capacity held by work that never went
through the coordinator.
- It moves when nodes join.

When a pin is wrong, the pinned placement group never gets placed, and
the controller retries the same pins indefinitely.

On this branch, the `train_elastic_e2e_with_node_killing.aws` release
test failed in 3 of its 5 weekly release-pipeline runs. In builds 109533
and 111090 it looped on `WorkerGroupStartupTimeoutError` until the job
timed out. #66766, where STRICT_SPREAD runs can wait forever, also
bisects to #66002.

After this revert, Train V2 schedules workers the way it did in 2.59.
#66001 and #66370 stay, as in #67337, so Train still uses the
coordinator's reservation to count how many workers fit.

This is the alternative to #67327, which cherry-picks #66646 onto this
branch instead. If this PR merges, #67327 should be closed.

## Revert details

`git revert e39557f` applied with no conflicts, and git merged
#66225's later change to `controller.py` automatically. The revert
touches 11 files, with 70 insertions and 759 deletions.

- The diff is byte-identical to #67337's revert of #66002 (deb5235),
index lines included.
- Before the revert, the 11 files on this branch were identical to
master right after #67337 reverts #66646. After the revert, they match
#67337's head.
- No code on this branch references the functions or classes the revert
removes. The few names that still have references are definitions that
existed before #66002, such as the Ray Data coordinator's
`get_reserved_resources`.

Not a duplicate: no PR against `releases/2.60.0` reverts #66002. #67337
targets `master`.

## Testing

| Command | Result |
|---|---|
| pre-commit, run as the commit hook on the 11 changed files | Passed
(ruff, black, pydoclint, Ray Train circular imports, and the other
applicable hooks) |

I didn't run the unit tests locally. CI runs them on this PR:

- `:bullettrain_front: ml: train v2 tests` runs the `train_v2`-tagged
tests, including `test_controller.py`, `test_elastic_scaling_policy.py`,
`test_autoscaling_coordinator_client.py` and `test_failure_policy.py`.
- `:train: ml: train v1 tests` runs
`python/ray/train/tests/test_autoscaling_coordinator_client.py`.
- `:train: ml: data integration tests` runs `test_data_integration.py`.

#67337 ran the same test files against the same resulting code on
master, and they passed.

AI assistance was used to prepare this revert.

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

Signed-off-by: Sai Miduthuri <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[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.

3 participants