Skip to content

[data][WIP][Do not review] propose folder hierarchy - #62573

Draft
iamjustinhsu wants to merge 3 commits into
ray-project:masterfrom
iamjustinhsu:jhsu/reorganize-folder-structure
Draft

iamjustinhsu wants to merge 3 commits into
ray-project:masterfrom
iamjustinhsu:jhsu/reorganize-folder-structure

Conversation

@iamjustinhsu

@iamjustinhsu iamjustinhsu commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

ray/data/_internal/ Directory Structure

Overview

The _internal/ directory is organized into 15 semantic domains, each owning a
distinct area of responsibility in Ray Data's implementation.

_internal/
├── autoscaling/            # Worker pool and cluster autoscaling
│   ├── actor/              #   Actor pool scaling (per-operator)
│   ├── cluster/            #   Cluster-level autoscaling coordination
│   └── autoscaling_requester.py
│
├── blocks/                 # Block formats and data type extensions
│   ├── arrow_block.py      #   Arrow block implementation
│   ├── pandas_block.py     #   Pandas block implementation
│   ├── table_block.py      #   Base table block
│   ├── block_builder.py    #   Block building utilities
│   ├── numpy_support.py    #   NumPy interop
│   ├── output_buffer.py    #   Block output buffering
│   ├── pyarrow_version_check.py  # PyArrow install/version checks
│   ├── pyarrow_ext_utils.py      # PyArrow extension type helpers
│   ├── row.py              #   Row display helpers (row_str, row_repr)
│   ├── size_estimator.py   #   Serialization size sampling
│   ├── arrow_ops/          #   Arrow/Polars transform helpers
│   ├── tensor_extensions/  #   Arrow & Pandas tensor type extensions
│   └── object_extensions/  #   Arrow & Pandas Python object extensions
│
├── bundle_queue/           # RefBundle queue implementations
│   ├── base.py             #   Abstract base queue
│   ├── fifo.py             #   FIFO queue
│   ├── hash_link.py        #   Hash-linked queue
│   ├── reordering.py       #   Reordering queue
│   └── thread_safe.py      #   Thread-safe wrapper
│
├── execution/              # Runtime execution engine
│   ├── streaming_executor.py       # Main streaming executor
│   ├── streaming_executor_state.py # Executor state machine
│   ├── resource_manager.py         # Resource allocation
│   ├── dataset_state.py            # Dataset execution state
│   ├── legacy_compat.py            # Legacy API compatibility
│   ├── ranker.py                   # Operator ranking
│   ├── util.py                     # Execution utilities
│   ├── backpressure_policy/        # Backpressure strategies
│   ├── callbacks/                  # Execution lifecycle callbacks
│   └── interfaces/                 # Core interfaces
│       ├── execution_options.py    #   ExecutionOptions, ExecutionResources
│       ├── executor.py             #   Executor base class
│       ├── ref_bundle.py           #   RefBundle (unit of data exchange)
│       ├── task_context.py         #   TaskContext passed to UDFs
│       └── transform_fn.py        #   Transform function types
│
├── io/                     # Data I/O (sources and sinks)
│   ├── datasource/         #   Read connectors (one file per format)
│   │   ├── parquet_datasource.py
│   │   ├── csv_datasource.py
│   │   ├── json_datasource.py
│   │   ├── ...             #   ~30 datasource implementations
│   │   └── lance_utils.py  #   Shared utilities
│   ├── datasink/           #   Write connectors (one file per format)
│   │   ├── parquet_datasink.py
│   │   ├── csv_datasink.py
│   │   ├── ...             #   ~15 datasink implementations
│   │   └── webdataset_datasink.py
│   └── datasource_v2/      #   Next-gen scanner/reader framework
│       ├── datasource_v2.py
│       ├── listing/         #   File listing and indexing
│       ├── partitioners/    #   Input partitioning strategies
│       ├── readers/         #   Data readers
│       └── scanners/        #   File scanners
│
├── iteration/              # Dataset iteration and batching
│   ├── iterator_impl.py    #   Core iterator implementation
│   ├── stream_split_iterator.py  # Split-stream iteration
│   ├── equalize.py          #   Equalize row counts across splits
│   ├── batcher.py           #   Block batching logic
│   ├── torch_iterable_dataset.py # PyTorch IterableDataset adapter
│   ├── tensorflow_utils.py  #   NumPy/Arrow → TensorFlow conversion
│   └── batching/            #   Batch assembly pipeline
│       ├── block_batching.py
│       ├── iter_batches.py
│       └── interfaces.py
│
├── logical/                # Logical plan and optimization
│   ├── optimizers.py       #   Logical & physical optimizer entry points
│   ├── ruleset.py          #   Optimizer ruleset registry
│   ├── interfaces/         #   LogicalOperator, LogicalPlan, etc.
│   ├── operators/          #   Logical operator definitions
│   │   ├── map_operator.py
│   │   ├── read_operator.py
│   │   ├── write_operator.py
│   │   ├── all_to_all_operator.py
│   │   ├── join_operator.py
│   │   └── ...
│   └── rules/              #   Optimizer rules
│       ├── operator_fusion.py
│       ├── predicate_pushdown.py
│       ├── projection_pushdown.py
│       ├── limit_pushdown.py
│       └── ...
│
├── node_trackers/          # Actor/node location tracking
│   └── actor_location.py
│
├── observability/          # Stats, metrics, logging, diagnostics
│   ├── stats.py            #   DatasetStats collection
│   ├── op_runtime_metrics.py  # Per-operator runtime metrics
│   ├── common.py           #   Shared metrics types (histograms, etc.)
│   ├── logging.py          #   Ray Data logging configuration
│   ├── memory_tracing.py   #   Memory usage tracing
│   ├── dataset_repr.py     #   Dataset string representation
│   ├── average_calculator.py
│   ├── metadata_exporter.py
│   ├── operator_event_exporter.py
│   ├── operator_schema_exporter.py
│   ├── progress/           #   Execution progress reporting
│   │   ├── base_progress.py
│   │   ├── tqdm_progress.py
│   │   ├── rich_progress.py
│   │   └── logging_progress.py
│   └── diagnostics/        #   Issue detection
│       ├── issue_detector.py
│       ├── issue_detector_manager.py
│       ├── issue_detector_configuration.py
│       └── detectors/
│           ├── hanging_detector.py
│           ├── high_memory_detector.py
│           └── hash_shuffle_detector.py
│
├── physical/               # Physical operator implementations
│   ├── physical_operator.py       # PhysicalOperator base class
│   ├── base_physical_operator.py  # Mixin for internal queues
│   ├── map_operator.py            # MapOperator (core transform)
│   ├── map_transformer.py         # Transform function wrappers
│   ├── task_pool_map_operator.py  # Task-pool execution
│   ├── actor_pool_map_operator.py # Actor-pool execution
│   ├── heapdict.py                # Vendored heap-based priority dict
│   ├── hash_shuffle.py            # Hash shuffle operator
│   ├── hash_aggregate.py          # Hash aggregate operator
│   ├── join.py                    # Join operator
│   ├── limit_operator.py          # Limit operator
│   ├── output_splitter.py         # Output splitting for streaming_split
│   ├── split.py                   # Block splitting by indices/row counts
│   ├── union_operator.py          # Union operator
│   ├── zip_operator.py            # Zip operator
│   ├── input_data_buffer.py       # Leaf operator for materialized data
│   ├── aggregate_num_rows.py      # Row count aggregation
│   ├── sub_progress.py            # Sub-operator progress tracking
│   └── gpu_shuffle/               # GPU-accelerated shuffle
│       ├── hash_shuffle.py
│       └── rapidsmpf_backend.py
│
├── planner/                # Logical-to-physical plan translation
│   ├── planner.py          #   Main planner
│   ├── plan.py             #   ExecutionPlan
│   ├── plan_read_op.py     #   Plan: read operators
│   ├── plan_write_op.py    #   Plan: write operators
│   ├── plan_udf_map_op.py  #   Plan: UDF map operators
│   ├── plan_all_to_all_op.py  # Plan: all-to-all operators
│   ├── plan_download_op.py #   Plan: download operators
│   ├── random_shuffle.py   #   Shuffle planning
│   ├── repartition.py      #   Repartition planning
│   ├── sort.py             #   Sort planning
│   ├── randomize_blocks.py #   Block randomization
│   ├── aggregate.py        #   Aggregation planning
│   ├── random_config.py    #   Random seed configuration
│   ├── streaming_repartition.py  # Streaming repartition bundler
│   ├── checkpoint/         #   Checkpoint read/write planning
│   ├── exchange/           #   Exchange task specs (shuffle, sort, aggregate)
│   └── plan_expression/    #   Expression evaluation planning
│
├── public_api/             # Public-facing classes (canonical location)
│   ├── compute.py          #   ComputeStrategy, TaskPoolStrategy, ActorPoolStrategy
│   └── savemode.py         #   SaveMode enum
│
└── utils/                  # Shared cross-domain utilities
    ├── util.py             #   General helpers (autodetect parallelism, etc.)
    ├── remote_fn.py        #   Cached remote function helpers
    ├── compute.py          #   [shim] → public_api/compute.py + get_compute()
    └── savemode.py         #   [shim] → public_api/savemode.py

Design Principles

  1. One domain per directory — each top-level folder owns a single area of concern.
  2. Absolute imports across domains — e.g., from ray.data._internal.physical.map_operator import MapOperator.
  3. Public API classes live in public_api/ — old locations remain as deprecation shims.
  4. [shim] files forward imports with a DeprecationWarning so external code that
    references old paths continues to work during migration.

@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 performs a comprehensive refactoring of the ray.data._internal package to improve modularity and code organization. It redistributes internal logic into several new sub-packages, including blocks for data format implementations, physical for operator logic, io for datasource and datasink management, and observability for stats and logging. The changes involve moving a large number of files and updating internal imports across the repository. I have no feedback to provide as there were no review comments to assess.

Signed-off-by: iamjustinhsu <[email protected]>
@bveeramani

Copy link
Copy Markdown
Member

I think the public_api/ thing seems a bit weird to me. If it's public, feel like it shouldn't go in _internal.

├── public_api/             # Public-facing classes (canonical location)
│   ├── compute.py          #   ComputeStrategy, TaskPoolStrategy, ActorPoolStrategy
│   └── savemode.py         #   SaveMode enum
│

Otherwise LGTM

@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor

A couple of things:

  • We can organize the shuffles into a separate dir, cause they are fundamentally different
  • Where do the expressions live in this design?
  • utils/ seems to mix across domains

Signed-off-by: iamjustinhsu <[email protected]>
@github-actions

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 29, 2026
@iamjustinhsu iamjustinhsu added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Apr 30, 2026
@richardliaw richardliaw added the data Ray Data-related issues label Jul 23, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Sep 29, 2026
…mmon/ and formats/parquet/ (#66497)

## Description

`python/ray/data/_internal/datasource_v2/` grouped files by role
(`listing/`,
`scanners/`, `readers/`, `partitioners/`, `chunkers/`), and each role
folder
mixed the abstract class, the format-independent implementation and the
Parquet one. `listing/file_indexer.py` held `FileIndexer` next to
`NonSamplingFileIndexer`, with `FooterFileIndexer` two files over.
Someone
adding a format could not tell from the tree what they must implement,
what
they may reuse, and what is Parquet's business.

This PR regroups the package by kind: `interfaces/` is what a format
implements, `common/` is what it may reuse, `formats/<name>/` is one
folder
per format. `interfaces/` imports nothing else in the package, `common/`
imports only `interfaces/`, `formats/` may import both. No class,
signature
or behaviour changes; every import path changes.

### The layout

```
python/ray/data/_internal/datasource_v2/
  __init__.py                      InputSplit TypeVar (unchanged)
  README.md                        new: layout rule, how a read flows, what a format implements
  interfaces/                      abstract classes and the types their signatures use
    datasource_v2.py               DataSourceV2, DatasourceCategory, FileDataSourceV2, DataSourceWithMetadata
    scanner.py                     Scanner
    reader.py                      Reader
    file_indexer.py                FileIndexer, FileInfo
    file_pruner.py                 FilePruner
    file_partitioner.py            FilePartitioner, PartitionHints
    in_memory_size_estimator.py    InMemorySizeEstimator
    supports_metadata.py           SupportsMetadata, MetadataType
    pushdown.py                    SupportsFilterPushdown, SupportsColumnPushdown, SupportsLimitPushdown, SupportsPartitionPruning, ListFilesPushdown
    read_units.py                  ReadUnit, ReadUnitFragment
    synthesized_columns.py         SynthesizedColumn, ReadUnitPosition
    file_manifest.py               FileManifest, ChunkMetadata, create_chunk_metadata
  common/                          format-independent implementations
    non_sampling_file_indexer.py   NonSamplingFileIndexer
    listing_utils.py, indexing_utils.py
    file_pruners.py                FileExtensionPruner, PartitionPruner, PartitionPredicatePruner
    round_robin_partitioner.py     RoundRobinPartitioner
    online_bin_packer.py           OnlineBinPacker, BinItem, Bin
    size_estimators.py             SamplingInMemorySizeEstimator
    file_scanner.py                FileScanner
    arrow_file_scanner.py          ArrowFileScanner
    file_reader.py                 FileReader
    synthesized_columns.py         PathColumn, RowHashColumn
    pushdown_utils.py              derive_list_files_pushdown, combine_predicates
  formats/
    parquet/
      parquet_datasource_v2.py     ParquetDatasourceV2
      parquet_scanner.py           ParquetScanner
      parquet_file_reader.py       ParquetFileReader
      footer_file_indexer.py       FooterFileIndexer
      footer_reader.py             FooterReader actor
      parquet_footer_types.py      RowGroupInfo, FileChunks, ParquetRowGroupChunkMetadata
      parquet_size_estimator.py    ParquetInMemorySizeEstimator
      parquet_file_chunking_utils.py, parquet_row_group_coalescing.py, parquet_utils.py
```

### What changes
1. **32 renames** into the three folders; `git diff -M` pairs them, most
at 90%+ similarity with the rest being import lines.
2. **7 files split** where an interface sat next to its implementations:
`listing/file_indexer.py`, `listing/file_pruners.py`,
`readers/in_memory_size_estimator.py`, `readers/synthesized_columns.py`,
`logical_optimizers.py` (mixins to `interfaces/pushdown.py`, helpers to
`common/pushdown_utils.py`), `chunkers/file_chunker.py` (dissolved into
`interfaces/file_manifest.py` and
`formats/parquet/parquet_footer_types.py`) and
`chunkers/parquet_footer_types.py` (`BinItem`/`Bin` to
`common/online_bin_packer.py`).
3. **27 files outside the package** change import lines only:
`read_api.py`, the legacy `ParquetDatasource`, logical rules, planners,
tests. Tests keep their locations.
4. **Nine type errors fixed** in `common/indexing_utils.py`,
`common/non_sampling_file_indexer.py` and `interfaces/file_manifest.py`.
These three files were in `ci/lint/pyrefly-excluded-files.txt` under
their old paths, so the move puts them under pyrefly for the first time.
The fixes: re-raise after `_handle_read_os_error` returns instead of
reading an unbound `file_info`; the threaded lister always wraps results
in `OrderedFileResult` and unwraps on yield, so `input_path_index` is an
`int` and there is no `FileInfo | OrderedFileResult` union;
`FileManifest.__init__` asserts a `TableBlockAccessor` before calling
`column_names()`. `ci/` is not touched.
5. **`README.md`** (new) for the package.

One import still crosses the layering line:
`common/online_bin_packer.py` reads and writes
`ParquetRowGroupChunkMetadata` from `formats/parquet/`. The packer is
meant for any format with sized sub-file units, so it stays in
`common/`. A follow-up PR, once #66121 has settled the packer's fields,
adds a generic chunk-run type in `interfaces/` that the packer works on
and makes the Parquet type a subclass of it. Doing that here would turn
a reviewable set of renames into content changes.

## Additional information
Follows #66450 (`[4/6]`) and #66478 (`[5/6]`), both merged; the branch
sits directly on `master`. Not a duplicate: #62573 (WIP, `_internal/`
wide) does not touch `datasource_v2/`.

Checks run locally from this branch (macOS, `~/ray/.venv`):
```
pytest -q tests/unit/datasource_v2   # 146 passed
```
`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed Python file; `tests/test_import.py` (from #66463) passes;
`pyrefly` via `ci/lint/pyrefly-check.sh` reports 59 errors, identical to
`master`, none new.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…mmon/ and formats/parquet/ (ray-project#66497)

## Description

`python/ray/data/_internal/datasource_v2/` grouped files by role
(`listing/`,
`scanners/`, `readers/`, `partitioners/`, `chunkers/`), and each role
folder
mixed the abstract class, the format-independent implementation and the
Parquet one. `listing/file_indexer.py` held `FileIndexer` next to
`NonSamplingFileIndexer`, with `FooterFileIndexer` two files over.
Someone
adding a format could not tell from the tree what they must implement,
what
they may reuse, and what is Parquet's business.

This PR regroups the package by kind: `interfaces/` is what a format
implements, `common/` is what it may reuse, `formats/<name>/` is one
folder
per format. `interfaces/` imports nothing else in the package, `common/`
imports only `interfaces/`, `formats/` may import both. No class,
signature
or behaviour changes; every import path changes.

### The layout

```
python/ray/data/_internal/datasource_v2/
  __init__.py                      InputSplit TypeVar (unchanged)
  README.md                        new: layout rule, how a read flows, what a format implements
  interfaces/                      abstract classes and the types their signatures use
    datasource_v2.py               DataSourceV2, DatasourceCategory, FileDataSourceV2, DataSourceWithMetadata
    scanner.py                     Scanner
    reader.py                      Reader
    file_indexer.py                FileIndexer, FileInfo
    file_pruner.py                 FilePruner
    file_partitioner.py            FilePartitioner, PartitionHints
    in_memory_size_estimator.py    InMemorySizeEstimator
    supports_metadata.py           SupportsMetadata, MetadataType
    pushdown.py                    SupportsFilterPushdown, SupportsColumnPushdown, SupportsLimitPushdown, SupportsPartitionPruning, ListFilesPushdown
    read_units.py                  ReadUnit, ReadUnitFragment
    synthesized_columns.py         SynthesizedColumn, ReadUnitPosition
    file_manifest.py               FileManifest, ChunkMetadata, create_chunk_metadata
  common/                          format-independent implementations
    non_sampling_file_indexer.py   NonSamplingFileIndexer
    listing_utils.py, indexing_utils.py
    file_pruners.py                FileExtensionPruner, PartitionPruner, PartitionPredicatePruner
    round_robin_partitioner.py     RoundRobinPartitioner
    online_bin_packer.py           OnlineBinPacker, BinItem, Bin
    size_estimators.py             SamplingInMemorySizeEstimator
    file_scanner.py                FileScanner
    arrow_file_scanner.py          ArrowFileScanner
    file_reader.py                 FileReader
    synthesized_columns.py         PathColumn, RowHashColumn
    pushdown_utils.py              derive_list_files_pushdown, combine_predicates
  formats/
    parquet/
      parquet_datasource_v2.py     ParquetDatasourceV2
      parquet_scanner.py           ParquetScanner
      parquet_file_reader.py       ParquetFileReader
      footer_file_indexer.py       FooterFileIndexer
      footer_reader.py             FooterReader actor
      parquet_footer_types.py      RowGroupInfo, FileChunks, ParquetRowGroupChunkMetadata
      parquet_size_estimator.py    ParquetInMemorySizeEstimator
      parquet_file_chunking_utils.py, parquet_row_group_coalescing.py, parquet_utils.py
```

### What changes
1. **32 renames** into the three folders; `git diff -M` pairs them, most
at 90%+ similarity with the rest being import lines.
2. **7 files split** where an interface sat next to its implementations:
`listing/file_indexer.py`, `listing/file_pruners.py`,
`readers/in_memory_size_estimator.py`, `readers/synthesized_columns.py`,
`logical_optimizers.py` (mixins to `interfaces/pushdown.py`, helpers to
`common/pushdown_utils.py`), `chunkers/file_chunker.py` (dissolved into
`interfaces/file_manifest.py` and
`formats/parquet/parquet_footer_types.py`) and
`chunkers/parquet_footer_types.py` (`BinItem`/`Bin` to
`common/online_bin_packer.py`).
3. **27 files outside the package** change import lines only:
`read_api.py`, the legacy `ParquetDatasource`, logical rules, planners,
tests. Tests keep their locations.
4. **Nine type errors fixed** in `common/indexing_utils.py`,
`common/non_sampling_file_indexer.py` and `interfaces/file_manifest.py`.
These three files were in `ci/lint/pyrefly-excluded-files.txt` under
their old paths, so the move puts them under pyrefly for the first time.
The fixes: re-raise after `_handle_read_os_error` returns instead of
reading an unbound `file_info`; the threaded lister always wraps results
in `OrderedFileResult` and unwraps on yield, so `input_path_index` is an
`int` and there is no `FileInfo | OrderedFileResult` union;
`FileManifest.__init__` asserts a `TableBlockAccessor` before calling
`column_names()`. `ci/` is not touched.
5. **`README.md`** (new) for the package.

One import still crosses the layering line:
`common/online_bin_packer.py` reads and writes
`ParquetRowGroupChunkMetadata` from `formats/parquet/`. The packer is
meant for any format with sized sub-file units, so it stays in
`common/`. A follow-up PR, once ray-project#66121 has settled the packer's fields,
adds a generic chunk-run type in `interfaces/` that the packer works on
and makes the Parquet type a subclass of it. Doing that here would turn
a reviewable set of renames into content changes.

## Additional information
Follows ray-project#66450 (`[4/6]`) and ray-project#66478 (`[5/6]`), both merged; the branch
sits directly on `master`. Not a duplicate: ray-project#62573 (WIP, `_internal/`
wide) does not touch `datasource_v2/`.

Checks run locally from this branch (macOS, `~/ray/.venv`):
```
pytest -q tests/unit/datasource_v2   # 146 passed
```
`ruff`, `black` and `pydoclint` at the pre-commit pins are clean on
every changed Python file; `tests/test_import.py` (from ray-project#66463) passes;
`pyrefly` via `ci/lint/pyrefly-check.sh` reports 59 errors, identical to
`master`, none new.

Written with Claude Code; I reviewed every changed line and ran the
tests above.

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

---------

Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Fable 5.1 <[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

data Ray Data-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants