Skip to content

[Data] - Refactor Shuffle lifecycle for extensibility to other engines - #61636

Closed
goutamvenkat-anyscale wants to merge 21 commits into
ray-project:masterfrom
goutamvenkat-anyscale:goutam/shuffle_refactor
Closed

goutamvenkat-anyscale wants to merge 21 commits into
ray-project:masterfrom
goutamvenkat-anyscale:goutam/shuffle_refactor

Conversation

@goutamvenkat-anyscale

@goutamvenkat-anyscale goutamvenkat-anyscale commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR refactors the shuffle operator hierarchy to introduce a ShuffleEngine interface and ShuffleOperatorCore base class. The motivation is to support GPU shuffle (PR #61371) and future GPU joins without duplicating ~200 lines of operator lifecycle plumbing (metrics, progress bars, output queue, stats, completion tracking, resource accounting) across each new operator.

Before

HashShufflingOperatorBase was a monolithic base class that mixed transport logic (actor management, task submission, finalization) with generic operator plumbing. GPU shuffle (PR #61371) had to create a parallel class hierarchy that re-implemented all the same plumbing independently.

After

Refactors the hash shuffle operator into a clean operator/engine split with metrics-only phase hooks, preparing for GPU shuffle to reuse the same abstractions.

  • Extract ShuffleEngine ABC (shuffle_engine.py): Pure transport interface — actor management, task submission, finalization, resource accounting. No stats state. The
    operator wires output_ready_cb after construction so the engine can deliver output bundles without holding a reference to the operator.
  • Extract PhaseHooks hierarchy (shuffle_engine.py): ShufflePhaseHooks and ReducePhaseHooks are metrics-only — they record task lifecycle events, update progress bars,
    accumulate block stats, and compute estimates. They never manage data flow.
  • HashShufflingOperatorBase: Generic operator shell that owns all lifecycle state (output queue, block stats, output estimates, progress bars). Delegates transport to a
    pluggable ShuffleEngine. Subclassed by HashShuffleOperator, JoinOperator, and HashAggregateOperator.
  • CpuShuffleEngine: Concrete engine implementation using Ray object store + aggregator actors. Extracted from the old monolithic operator.

Design

  HashShufflingOperatorBase (owns state)        ShuffleEngine (pure transport)
  ├── output_queue                              ├── output_ready_cb (wired by operator)
  ├── shuffled_block_stats                      ├── submit_input(hooks) → actors
  ├── num_outputs_produced                      ├── try_finalize(hooks) → output_ready_cb(bundle)
  ├── shuffle_hooks (metrics-only)              └── shutdown()
  ├── reduce_hooks (metrics-only)
  └── _on_output_ready() ← callback
classDiagram
      class PhysicalOperator
      class SubProgressBarMixin

      class ProgressEstimate {
          <<frozen dataclass>>
          +num_blocks: Optional~int~
          +num_bundles: Optional~int~
          +num_rows: Optional~int~
      }

      class PhaseHooks {
          +on_task_submitted()
          +on_task_finished()
          +on_progress()
          +set_progress_bar()
          +metrics_as_dict()
          +estimate_progress() ProgressEstimate
      }

      class ShufflePhaseHooks {
          +on_input_received()
          +on_output_taken()
          +on_task_output()
          +on_block_shuffled()
      }

      class ReducePhaseHooks {
          +on_output_queued()
          +on_output_dequeued()
          +on_output_taken()
      }

      class HashShufflingOperatorBase {
          -engine: ShuffleEngine
          -output_queue: Deque
          -num_outputs_produced: int
          -shuffled_block_stats: List
          -output_block_stats: List
          -shuffle_hooks: _BoundShufflePhaseHooks
          -reduce_hooks: _BoundReducePhaseHooks
          +start()
          +has_next()
          +_get_next_inner()
          +_on_output_ready()
          +_update_output_estimates()
          +get_stats()
          +_extra_metrics()
          +current_logical_usage()
      }

      class ShuffleEngine {
          <<abstract>>
          +output_ready_cb: OutputReadyCallback
          +total_num_reduce_tasks()
          +start()*
          +submit_input(hooks: ShufflePhaseHooks)*
          +try_finalize(hooks: ReducePhaseHooks)*
          +get_active_tasks()*
          +has_completed()*
          +base_resource_usage()*
          +incremental_resource_usage()*
          +min_scheduling_resources()
          +current_processor_usage()
          +shutdown()*
          +progress_bar_names()*
      }

      class CpuShuffleEngine {
          -aggregator_pool: AggregatorPool
          -shuffling_tasks
          -finalizing_tasks
      }

      class HashShuffleOperator
      class JoinOperator
      class HashAggregateOperator

      PhysicalOperator <|-- HashShufflingOperatorBase
      SubProgressBarMixin <|-- HashShufflingOperatorBase

      PhaseHooks <|-- ShufflePhaseHooks
      PhaseHooks <|-- ReducePhaseHooks

      HashShufflingOperatorBase *-- ShufflePhaseHooks : shuffle_hooks
      HashShufflingOperatorBase *-- ReducePhaseHooks : reduce_hooks
      HashShufflingOperatorBase o-- ShuffleEngine : engine

      ShuffleEngine <|-- CpuShuffleEngine

      PhaseHooks ..> ProgressEstimate : returns

      HashShufflingOperatorBase <|-- HashShuffleOperator : CpuShuffleEngine
      HashShufflingOperatorBase <|-- JoinOperator : CpuShuffleEngine
      HashShufflingOperatorBase <|-- HashAggregateOperator : CpuShuffleEngine
Loading

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@goutamvenkat-anyscale
goutamvenkat-anyscale requested a review from a team as a code owner March 10, 2026 21:50

@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 well-designed refactoring of the shuffle operator hierarchy, creating a ShuffleEngine interface and a ShuffleOperatorCore base class. This change significantly improves code structure, reduces duplication, and enhances extensibility for future shuffle implementations like GPU-based shuffle. The implementation is solid and aligns with the stated goals. I have a couple of suggestions to improve consistency and encapsulation.

Signed-off-by: Goutam <[email protected]>
@goutamvenkat-anyscale goutamvenkat-anyscale added the data Ray Data-related issues label Mar 10, 2026
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
@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 a significant and well-executed refactoring of the shuffle operator hierarchy. By creating a ShuffleEngine interface and a ShuffleOperatorCore base class, it successfully decouples the shuffle transport logic from the operator lifecycle plumbing, which will make it much easier to add new shuffle engines like the planned GPU shuffle. The changes are consistently applied across HashAggregateOperator, JoinOperator, and HashShuffleOperator. My main feedback is a suggestion to improve encapsulation by introducing a public setter for the operator name on the CpuShuffleEngine, rather than modifying a private attribute directly. This would enhance the clarity and maintainability of the new abstraction.

@alexeykudinkin alexeykudinkin added the go add ONLY when ready to merge, run all tests label Mar 11, 2026
Comment on lines +149 to +152
def _aggregator_pool(self):
# TODO: Remove once tests use a ShuffleEngine-level interface instead
# of reaching into internal components.
return self._engine._aggregator_pool

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.

That should be fixed in this PR (or follow-up)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I can do this as a follow up

def __init__(
self,
metrics: OpRuntimeMetrics,
output_queue: Deque[RefBundle],

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.

Why's output queue here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

So the engine doesn't know about the output_queue but the hook does and we need to update its state during finalization

return self._metrics


class _BoundShufflePhaseHooks(_BoundPhaseHooks, ShufflePhaseHooks):

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.

What's the idea behind creating these?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Engine (CpuShuffleEngine) -- does the actual work. Manages actors, routes blocks, schedules shuffle and reduce tasks. When something happens, it tells the hooks: "I submitted a task", "a block was shuffled", "an output is ready". It has zero knowledge of metrics, progress bars, queues, or the operator.

Hooks (_BoundShufflePhaseHooks, _BoundReducePhaseHooks) -- translate engine events into operator bookkeeping. The hooks own the mapping from semantic events to internal state mutations.

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

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

left some higher level comments

num_rows: Optional[int] = None


class PhaseHooks:

@iamjustinhsu iamjustinhsu Mar 13, 2026 •

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.

how come the phase hooks are separate from the engine? From the docstring of the engine, I feel like the phase hooks may not be necessary, or maybe out of scope for this change since there's always shuffle, and finalize hooks (unless i'm mistaken). Like what happens if you do the metric counting the base class of the Engine, or the CPUEngine?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hmm the point is to not have the engine worry about metric counting. Also with the GPU shuffle and external shuffles if metrics need to overridden, for some reason, it's clear which phase needs to be overriden, depending on how the engine does shuffle or reduce.

My concern with tightly coupling it with the engine is that now every engine has to worry deeply about metrics

)


class _BoundShufflePhaseHooks(_BoundPhaseHooks, ShufflePhaseHooks):

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.

I think this hierarchy is a lil bit confusing, can you elarboate a bit why we have both _BoundPhaseHooks and ShufflePhaseHooks?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

 PhaseHooks
          /          \
  ShufflePhaseHooks (does shuffle specific accounting)  _BoundPhaseHooks (basically does the shared metrics + progress bar updates)
          \          /
    _BoundShufflePhaseHooks (concrete impl)

Hmm one option is to go for a composition approach

if partition_size_hint is not None:
# TODO replace with dataset-byte-size hint
estimated_dataset_bytes = partition_size_hint * target_num_partitions
estimated_dataset_bytes = partition_size_hint * self._num_partitions

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.

I feel like dataset estimation is more of a base regular engine, or maybe base hash shuffling operator

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

@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 and found 1 potential issue.

Fix All in Cursor

StatsDict = Dict[str, List[BlockStats]]


class _PhaseMetrics:

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.

is this supposed to inherit from PhaseHooks in shuffle_engine.py

@owenowenisme owenowenisme left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In my opinion, the GPU shuffle isn't blocked on this refactor and has already merged. Given that the actor-less CPU shuffle is also planned, I'd suggest we hold off on this — the ShuffleEngine interface here is shaped around the current actor-based implementation, which will be replaced. It would be better to revisit the engine/operator split after actor-less lands, so the abstraction is designed around the implementations that actually stay.

@github-actions

github-actions Bot commented Apr 4, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Apr 4, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Apr 18, 2026
owenowenisme added a commit that referenced this pull request Nov 10, 2026
## Description

Adds one shared component for per-phase shuffle metrics and exports each
phase to Prometheus under its own tag.

Today GPU shuffle keeps per-phase `OpRuntimeMetrics` objects but never
exposes them, so its dashboard task counts, shuffle progress bar, and
output estimate all stay at 0. Shuffle v2 reports correctly but
duplicates the estimate and progress-bar code across its map, reduce,
and disk variants.

`shuffle_phase_metrics.py` adds `ShufflePhaseMetrics` (one phase's
counters, block stats, progress bar) and `ShuffleOperatorMetrics` (an
operator's phases, answering `get_stats`, `_extra_metrics`,
`get_phase_metrics`, the sub-progress bar hooks, and `num_outputs_total`
from them). Phase events update the phase's own counters; task events
are also replayed on the operator's `self._metrics` under a
collision-free key, output events only from the output phase. A lone
phase is aliased to the operator's metrics, so single-phase operators
keep today's shapes.

## Related issues

Related to #61636, which proposed a `ShuffleEngine` abstraction for
shuffle v1 and was closed because v1 is being replaced. This PR keeps
only the metrics half, as a composed component, for GPU and v2.

## Additional information

```mermaid
flowchart LR
  classDef obj fill:#eef3ff,stroke:#4a6fd6,color:#111
  classDef comp fill:#e8f7ec,stroke:#2e8b57,color:#111
  classDef surface fill:#f3f3f3,stroke:#888,color:#111

  subgraph OP["Any shuffle operator (GPU: two phases · v2: one phase, aliased to the operator counters)"]
    direction LR
    som["ShuffleOperatorMetrics (new)<br/>holds the phases; rebuilds the four surfaces from them on request;<br/>keeps the output-total estimate"]:::comp
    p1["Phase 'shuffle' (ShufflePhaseMetrics, new)<br/>its own counters, block-stats list, progress bar,<br/>shuffle-specific numbers (partitions, bytes shuffled)"]:::comp
    p2["Phase 'finalize' = the output phase<br/>(ShufflePhaseMetrics, new)<br/>same contents as above"]:::comp
    base["Operator-level counters (_metrics, from base class)<br/>now complete: tasks of both phases,<br/>real outputs handed downstream"]:::obj
    som --> p1
    som --> p2
    p1 -- "forwards task started / finished" --> base
    p2 -- "forwards task started / finished<br/>and outputs produced / queued" --> base
  end

  subgraph SURF["What the user sees"]
    direction TB
    prom[("Grafana dashboard (Prometheus gauges)<br/>three series: the operator,<br/>operator/shuffle, operator/finalize")]:::surface
    stats[["ds.stats() summary table<br/>rows: OperatorNameShuffle,<br/>OperatorNameFinalize"]]:::surface
    extra[["ds.stats() 'Extra metrics' line<br/>{shuffle: {…}, finalize: {…}}"]]:::surface
    pm(["Progress manager<br/>one nested bar per phase,<br/>each handed to its phase"]):::surface
  end

  base -- "exported as the op's metrics" --> prom
  som -- "get_phase_metrics(): one extra series per phase" --> prom
  som -- "get_stats()" --> stats
  som -- "_extra_metrics()" --> extra
  som -- "sub-progress bar names / bar objects" --> pm
```

Tests: `test_shuffle_phase_metrics.py` (new, 17 cases) covers the
component and drives a minimal `PhysicalOperator` through all four
surfaces.

AI assistance (Claude Code) was used for drafting this PR (code and
description); every changed line was manually reviewed and the tests
above run locally.

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: HFFuture <[email protected]>
Co-authored-by: You-Cheng Lin <[email protected]>
owenowenisme pushed a commit that referenced this pull request Nov 12, 2026
## Description

Migrates GPU shuffle onto the `ShuffleOperatorMetrics` component from
#66968. PR 2 of 3, stacked on #66968.

Today `GPUShuffleOperator` keeps two private `OpRuntimeMetrics` that are
never exported, so it reports zero tasks on every surface, its "GPU
Shuffle" bar never moves, and `num_outputs_total()` stays 0.

This PR replaces them with a `shuffle` phase and a `finalize` phase. The
finalize phase forwards into the operator's own metrics, so the operator
tag, `<op>/shuffle`, and `<op>/finalize` are all exported. The bars now
advance by rows, and output estimates appear once the first rank
finishes. `GPUHashAggregateOperator` differs only by its bar label. The
PR modifies metrics only, and transport, lifecycle, and output ordering
are all untouched.

## Related issues

Stacked on #66968. Related to #61636.

## Additional information

The `shuffle` phase records tasks and input rows but no outputs:
`insert_batch` returns only a row count, and the output hook requires
exec stats that upstream blocks from `from_items` lack.

AI assistance (Claude Code) was used; every line was manually reviewed
and locally tested.

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: HFFuture <[email protected]>
richardliaw pushed a commit that referenced this pull request Nov 19, 2026
## Description

Migrates shuffle v2 onto the `ShuffleOperatorMetrics` component from
#66968. PR 3 of 3, stacked on #66968 and #67359.

Today the four v2 operators (`ShuffleMapOp`, `ShuffleReduceOp`,
`DiskHashShuffleMapOp`, `DiskHashShuffleReduceOp`) each keep their own
block-stats list and a copy of the output-estimate block. Map stages
report 0 worker time and `num_outputs_total() is None`; reduce stages
recompute the estimate on every output bundle, and the disk reduce's
estimate is stuck at 0.

This PR gives each operator one phase (`map` or `reduce`), aliased to
the operator's own metrics, so every exported metric name and stats row
is unchanged. What changes:

- Map tasks report their worker wall time; map operators report
`num_outputs_total() == num_partitions`.
- Reduce estimates are computed once per finished task, so the disk
reduce now reports a real estimate and non-row-preserving reduces return
a row estimate instead of `None`.
- The four copies of the estimate block are gone.

`SortShuffleMapOp` inherits the metrics unification changes introduced
in this PR as it subclasses `ShuffleMapOp`.

## Related issues

Stacked on #66968 and #67359. Related to #61636.

## Additional information

The disk reduce still submits its tasks with an empty metrics bundle.
Passing the wrapper's partition bytes would feed
`obj_store_mem_pending_task_inputs`, which the downstream capacity
backpressure policy reads, so that is a backpressure change rather than
a metrics one and is not made here.

AI assistance (Claude Code) was used; every line was manually reviewed
and locally tested.

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: HFFuture <[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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

4 participants