Repository navigation
[Data][Chkpt][4/4] Parquet DSv2: honor read unit boundaries by splitting batches when no filter is pushed down - #66734
Conversation
f90c831 to
91fdb21
Compare
…as a DSv2 synthesized column (#66732) ## Why are these changes needed? Job-level checkpointing (`CheckpointConfig(id_column=...)`) needs a unique ID column in the input. Many batch-inference datasets don't have one. Ray Data generates a stable ID for every row from where it lives in its Parquet file, and a resumed job skips committed work at the source. This is a redo of #65885, which was reverted (#66183) so the DSv2 reorg could land first. The reorg added the seams this needs (`SynthesizedColumn`, `ReadUnit`, the `excluded_read_unit_ids` listing hook), so this version adds **no reader code** for the ID itself. This PR (1/4) adds the config and the ID column. Restore comes in 3/4. ## What changes - **`CheckpointConfig(generated_id_column=...)`**, exactly one of `id_column` / `generated_id_column`. The generated name is also exposed as `id_column`, so the existing checkpoint write (two-phase commit) works unchanged. - **`GeneratedIdColumn`** (`checkpoint/generated_id.py`), a `SynthesizedColumn` with `requires_read_unit_boundaries = True`. It builds a struct ID per row from the batch's `ReadUnitPosition`: `path_prefix`, `file_name`, `fragment` (row group), `num_fragments`, `num_rows`, `row_id` (position in the row group). - **Whole-file guard:** if a batch comes from a whole-file read unit (no row-group info), the column raises instead of writing IDs that can't name a row group. Parquet always lists by footer today, so this isn't reachable in normal reads. - **Explicit plumbing, no public API change:** `read_parquet` builds the column from the checkpoint config and passes it to `ParquetDatasourceV2(extra_synthesized_columns=...)`. Ray Data's own checkpoint reads opt out with an internal `_add_generated_id_column=False`, popped from `**arrow_parquet_args` like the existing `_block_udf`. Checkpoint files are Parquet too and must never get the column. - **Name clash:** `ParquetDatasourceV2.infer_schema` raises if a file already has a column with the requested name, instead of silently replacing user data the way `path` / `row_hash` do. - **Safe on its own:** until 3/4 wires up restore, the planner plans only the checkpoint write for generated-ID configs (plus cleanup of a crashed run's pending checkpoints). A rerun redoes every row instead of sending struct IDs into the numpy-based `id_column` filter. ## Related issue number N/A. Not a duplicate: I searched open PRs for `generated_id_column`, "row group checkpoint", `excluded_rows` and `requires_read_unit_boundaries`. The only matches are my earlier pre-reorg drafts #65886–#65888, which this stack replaces and which I'm closing. **Stack:** 1/4 (this, #66732) → 2/4 (#66733) → 3/4 (#66736) is the feature chain. 4/4 (#66734) is an independent speed-up that lands last. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit (`ruff`, `black`, `pydoclint`, Ray import/doc style) on all changed files: clean. The API-annotation check (`ci/lint/check_api_annotations.py`, scoped to `ray.data`) reports nothing unannotated. - [x] AI assistance (Claude Code) was used for the development of this PR. I, Abhishek Verma, am the human submitter signing off on it: I have reviewed every changed line, run the tests below locally, and can defend the change end-to-end. - Testing (macOS, nightly wheel + this branch's `ray/data`): - `pytest python/ray/data/tests/unit/datasource_v2/test_generated_id_column.py`: 10 passed. Covers ID fields per row group, uniqueness across files and row groups, `row_id` continuing across batches, determinism under a pushed-down filter, whole-file guard, projection, schema advertisement, name clash, and no-op without config. - `pytest python/ray/data/tests/test_checkpoint.py` (run from `python/ray/data/tests/`): 88 passed, 1 failed. The failure, `test_skip_checkpoint_flag[s3]`, is a pre-existing local moto-S3 timing flake that also fails on unmodified master. New tests: config validation, `read_parquet` adds the column and the checkpoint read opts out, rerun redoes rows with no filter op planned, pending-checkpoint cleanup before rerun (verified it fails without the fix). - `pytest python/ray/data/tests/unit/datasource_v2 python/ray/data/tests/datasource_v2`: 214 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…ng committed work at the source (#66736) Follow-up to 1/4 (#66732) and 2/4 (#66733), both merged. 4/4 (#66734) is an independent speed-up that lands last; this PR doesn't need it. ## Why are these changes needed? This switches the feature on. A resumed `generated_id_column` job now skips work it already committed, as early as possible. It doesn't run the actor-pool `CheckpointFilter` that the `id_column` path applies to every row. ## What changes - **Planner routing** (`planner.py`). Generated-ID jobs get: - `ListFiles` → `plan_list_files_op_with_done_read_units`: passes the checkpoint's done unit ids as `EXCLUDED_READ_UNIT_IDS_KWARG_NAME` (the hook from #66398). Fully committed files are never listed, and fully committed row groups are never read. - `ReadFiles` → `plan_read_files_op_with_done_rows`: the normal read followed by a `DropCommittedRows` step for row groups that were only partly committed. - Each row's generated ID names its file, row group and `row_id`, so the step looks up the row group's mask and drops rows where `mask[row_id]` is set. - The step fuses into the read task (`ReadFilesParquetV2->DropCommittedRows->...`), so no extra stage runs. - Thanks @AarryaSaraf for suggesting this over a new reader hook (the former 4/5, #66735, now closed). - The checkpoint's masks arrive as an Arrow table; each task indexes them once (`_partial_mask_lookup`) and reuses the lookup for every block. Masks stay numpy. - `Write` → the existing checkpoint two-phase commit. - The `id_column` path is unchanged. 1/4's interim write-only gate is removed. - **Listing accepts Arrow ids** (`listing_utils.py`): the checkpoint passes done unit ids as an Arrow array. Listing converts them to Python strings before building its lookup set; a set built straight from an Arrow array would hold Arrow values and never match. - **Loading:** `LoadCheckpointCallback` loads the checkpoint once when execution starts (`load_generated_id_checkpoint`, from 2/4). Both plan functions read it through task kwargs set lazily (`add_map_task_kwargs_fn`), because it isn't loaded at planning time. A crashed run's pending checkpoints are still cleaned up while planning, before the load. - **Runs that don't restore** (`CheckpointConfig._should_restore`, from #66563): after a successful run sets it to `False` (e.g. later training epochs), the planner plans only the checkpoint write, as for `id_column`, and `LoadCheckpointCallback` skips loading the generated-ID checkpoint, since no operator reads it. - **Validation:** plans whose sources aren't V2 Parquet reads (`ReadFiles` over a `ParquetScanner`) raise `InvalidCheckpointingConfig` with a pointer to `id_column`. This covers the V1 `Read` path and non-Parquet V2 scanners. - **Docs:** a "Checkpoint without an ID column" section in `doc/source/data/execution-configurations.md`. Note: like the `id_column` path's filter, `DropCommittedRows` runs after the read, so a `limit` pushed into the read counts rows before they're dropped. ## Related issue number N/A. Not a duplicate (see 1/4). Replaces my pre-reorg drafts #65886, #65887 and #65888. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit on all changed files: clean. `vale` (v3.17.1, as in CI) on the docs page: 0 errors, 0 warnings, 0 suggestions. - [x] AI assistance (Claude Code) was used for the development of this PR. I, Abhishek Verma, am the human submitter signing off on it: I have reviewed every changed line, run the tests below locally, and can defend the change end-to-end. - Testing: - `pytest python/ray/data/tests/unit/test_generated_id_checkpoint.py`: 15 passed. New: masked rows dropped per row group in a block mixing row groups and files; rows past a short mask kept; no matching mask means no change; mask lookup across table chunks. - `test_read_units.py`: listing skips done units whether the ids arrive as a set, an Arrow array, or a chunked array. The Arrow cases fail without the conversion. - With `_should_restore=False`, a run ignores the kept checkpoint, reads every row, never loads the checkpoint, and still writes checkpoints. I checked that this test fails without the callback fix. - On current master, `pytest python/ray/data/tests/test_checkpoint.py python/ray/data/tests/test_data_iterator_checkpointer.py python/ray/data/tests/unit/test_generated_id_checkpoint.py python/ray/data/tests/unit/datasource_v2`: 299 passed, 1 failed. The failure, `test_skip_checkpoint_flag[s3]`, is a pre-existing local moto-S3 flake that also fails on unmodified master. - New end-to-end tests in `python/ray/data/tests/test_checkpoint.py`: - Crash partway, then rerun: no missing rows, and the checkpoint is deleted on success. - Resume skips a fully committed file, a committed row group, and the committed rows of a partly committed row group, and reads a never-seen file in full. The output is exactly the uncommitted rows. I checked that this test fails with `DropCommittedRows` disabled. - A rerun after a full success writes nothing. - The plan has no `CheckpointFilter` op, and `DropCommittedRows` is fused into the read. - Non-Parquet and V1 inputs are rejected. - `pytest python/ray/data/tests/unit/test_generated_id_checkpoint.py`: 15 passed. New: masked rows dropped per row group in a block mixing row groups and files; rows past a short mask kept; no matching mask means no change; mask lookup across table chunks. - Block sizing: a `generated_id_column` read produces the same number of blocks per task as a plain read (`DropCommittedRows` keeps `target_max_block_size`). - `test_read_units.py`: listing skips done units whether the ids arrive as a set, an Arrow array, or a chunked array. The Arrow cases fail without the conversion. - With `_should_restore=False`, a run ignores the kept checkpoint, reads every row, never loads the checkpoint, and still writes checkpoints. I checked that this test fails without the callback fix. - On current master, `pytest python/ray/data/tests/test_checkpoint.py python/ray/data/tests/test_data_iterator_checkpointer.py python/ray/data/tests/unit/test_generated_id_checkpoint.py python/ray/data/tests/unit/datasource_v2`: 299 passed, 1 failed. The failure, `test_skip_checkpoint_flag[s3]`, is a pre-existing local moto-S3 flake that also fails on unmodified master. - `pytest python/ray/data/tests/unit python/ray/data/tests/datasource_v2`: 1500 passed. - Five modules didn't collect locally for missing optional dependencies (torch, pyiceberg, freezegun). - Two failures in `test_dynamic_work_queue.py`, which also fail on unmodified master. - **Together with 4/4** (local combined branch): 237 DSv2/unit and 38 checkpoint tests passed. In a manual resume run (4 files × 4 row groups, 16 write tasks), I deleted 6 committed checkpoint files and the rerun wrote **exactly those 6,000 rows**. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces _ScanGroup to allow scanning multiple consecutive read units of a file together (enabling pyarrow to coalesce reads) and splitting them back into per-unit tables. The ParquetFileReader is updated to override _get_scan_groups so that row groups can be scanned together when no filter is pushed down, even if they require read unit boundaries. Comprehensive unit tests have been added to verify this behavior. There are no review comments to address, and I have no additional feedback to provide.
| @property | ||
| def _needs_read_unit_boundaries(self) -> bool: | ||
| # A column whose value depends on the row's position in the file | ||
| # (``RowHashColumn``) needs each row group as its own read unit; | ||
| # otherwise a file's groups are one unit, scanned together. | ||
| return any(c.requires_read_unit_boundaries for c in self._synthesized_columns) |
There was a problem hiding this comment.
Can't this value be cached?
There was a problem hiding this comment.
Yes, it can't change after the reader is built. Switched it to cached_property, like _file_dataset_schema.
| """Unit tests for how the Parquet reader honors read unit boundaries. | ||
|
|
||
| A column with ``requires_read_unit_boundaries`` needs every batch to come | ||
| from one row group. Without a pushed-down filter, the reader scans a manifest | ||
| row's row groups together and splits the batches at their footer row counts; | ||
| with a filter it scans each row group on its own. Either way, every row must | ||
| get the same unit and position. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| import numpy as np | ||
| import pyarrow as pa | ||
| import pyarrow.dataset as pds | ||
| import pyarrow.parquet as pq | ||
| import pytest | ||
|
|
||
| from ray.data._internal.datasource_v2.common.synthesized_columns import ( | ||
| RowHashColumn, | ||
| ) | ||
| from ray.data._internal.datasource_v2.formats.parquet.parquet_file_reader import ( |
There was a problem hiding this comment.
from dataclasses import dataclass
import numpy as np
import pyarrow as pa
import pyarrow.dataset as pds
import pyarrow.parquet as pq
import pytest
from ray.data._internal.datasource_v2.common.synthesized_columns import (
RowHashColumn,
)
from ray.data._internal.datasource_v2.formats.parquet.parquet_file_reader import (
ParquetFileReader,
)
from ray.data._internal.datasource_v2.interfaces.file_manifest import (
FileChunk,
FileManifest,
)
from ray.data._internal.datasource_v2.interfaces.synthesized_columns import (
ReadUnitPosition,
SynthesizedColumn,
)
from ray.data.expressions import col
ROW_GROUP_SIZE = 25
NUM_ROW_GROUPS = 4
NUM_ROWS = ROW_GROUP_SIZE * NUM_ROW_GROUPS
ALL_ROW_GROUPS = tuple(range(NUM_ROW_GROUPS))
@dataclass(frozen=True)
class _PositionColumn(SynthesizedColumn):
"""Records each row's read unit and its position within the unit."""
name = "position"
type = pa.struct([("unit", pa.string()), ("row", pa.int64())])
requires_read_unit_boundaries = True
def compute(self, position: ReadUnitPosition, num_rows: int) -> pa.Array:
rows = np.arange(position.rows_before, position.rows_before + num_rows)
return pa.StructArray.from_arrays(
[pa.array([position.unit.id] * num_rows), pa.array(rows)],
fields=list(self.type),
)
def _write_file(path):
pq.write_table(
pa.table({"id": list(range(NUM_ROWS))}), path, row_group_size=ROW_GROUP_SIZE
)
return str(path)
def _reader(**kwargs):
kwargs.setdefault("synthesized_columns", (_PositionColumn(),))
return ParquetFileReader(**kwargs)
def _chunk(row_group_ids):
row_group_ids = tuple(row_group_ids)
return FileChunk(
unit_ids=row_group_ids,
num_rows=ROW_GROUP_SIZE * len(row_group_ids),
size_bytes=ROW_GROUP_SIZE * 8 * len(row_g
).to_metadata()
def _manifest(rows):
return FileManifest.construct_manifest(
paths=[path for path, _ in rows],
sizes=[0] * len(rows),
chunk_metadatas=[chunk for _, chunk in ro
)
def _unit_id(path, row_group):
return f"{path}#rg{row_group}"
def _read(reader, manifest):
return pa.concat_tables(list(reader.read(manifest)))
def _assert_positions(table, path, row_within_gro
"""Row ``id`` lives in row group ``id // ROW_GROUP_SIZE``;
``row_within_group(id)`` says where the posit""
assert table.num_rows > 0
for row_id, position in zip(
table["id"].to_pylist(), table["position"].to_pylist()
):
assert position == {
"unit": _unit_id(path, row_id // ROW_
"row": row_within_group(row_id),
}
@pytest.mark.parametrize(
"batch_size", [7, 25, 1000], ids=["sub_group"
)
@pytest.mark.parametrize(
"row_group_ids", [ALL_ROW_GROUPS, (1, 3)], ids=["contiguous", "pruned"]
)
def test_one_unit_per_batch_with_correct_positions(
tmp_path, batch_size, row_group_ids
):
"""The contract itself: every yielded batch h
each tagged with its row group and offset — for batches that undershoot,
hit, and overshoot a row group, over contiguo
path = _write_file(tmp_path / "data.parquet")
reader = _reader(batch_size=batch_size)
tables = list(reader.read(_manifest([(path, _
for table in tables:
assert len({p["unit"] for p in table["position"].to_pylist()}) == 1
combined = pa.concat_tables(tables)
assert sorted(combined["id"].to_pylist()) == [
i
for g in row_group_ids
for i in range(g * ROW_GROUP_SIZE, (g + 1
]
_assert_positions(combined, path, lambda row_E)
def test_multi_unit_scan_table_is_split_at_footer_counts(tmp_path, monkeypatch):
"""The splitting loop in isolation: force thele
spanning three pruned row groups; the reader must cut it back apart."""
path = _write_file(tmp_path / "data.parquet")
reader = _reader()
scan_one_fragment = reader._iter_fragment_tab
def scan_as_one_table(fragment, scanner_kwarg
yield pa.concat_tables(list(scan_one_fragment(fragment, scanner_kwargs)))
monkeypatch.setattr(reader, "_iter_fragment_tables", scan_as_one_table)
tables = list(reader.read(_manifest([(path, _chunk([0, 1, 3]))])))
assert [t.num_rows for t in tables] == [ROW_GROUP_SIZE] * 3
_assert_positions(
pa.concat_tables(tables), path, lambda row_id: row_id % ROW_GROUP_SIZE
)
@pytest.mark.parametrize(
"reader_kwargs, expected_group_unit_ids",
[
pytest.param(
{"synthesized_columns": ()},
lambda path: [[path]],
id="no_boundary_column__one_whole_file_scan",
),
pytest.param(
{},
lambda path: [[_unit_id(path, g) for g in ALL_ROW_GROUPS]],
id="no_filter__one_combined_scan",
),
pytest.param(
{"predicate": (col("id") % 2) == 0},
lambda path: [[_unit_id(path, g)] for
id="filter__one_scan_per_row_group",
),
],
)
def test_scan_group_strategy(tmp_path, reader_kwargs, expected_group_unit_ids):
"""Which scans get built: combined without a
one, and a single whole-file scan when no column needs boundaries."""
path = _write_file(tmp_path / "data.parquet")
reader = _reader(**reader_kwargs)
dataset = pds.dataset([path], format="parquet
groups = reader._get_scan_groups(
dataset, _manifest([(path, _chunk(ALL_ROW_GROUPS))])
)
assert [
[u.unit.id for u in g.units] for g in groups
] == expected_group_unit_ids(path)
def test_filtered_positions_count_surviving_rows(tmp_path):
"""With a filter, ``rows_before`` is a post-f
count the rows that survive the predicate within each row group."""
path = _write_file(tmp_path / "data.parquet")
reader = _reader(predicate=(col("id") % 2) == 0)
table = _read(reader, _manifest([(path, _chunk(ALL_ROW_GROUPS))]))
assert table.num_rows == NUM_ROWS // 2
_assert_positions(table, path, lambda row_id: // 2)
def test_row_hash_unchanged_by_combined_scans(tmp_path):
"""``row_hash`` was defined against whole-fil
with splitting must reproduce it exactly, even over pruned groups."""
path = _write_file(tmp_path / "data.parquet")
reader = ParquetFileReader(batch_size=7, synthesized_columns=(RowHashColumn(),))
whole = _read(reader, _manifest([(path, None)]))
chunked = _read(reader, _manifest([(path, _ch
expected = dict(zip(whole["id"].to_pylist(), t()))
got = dict(zip(chunked["id"].to_pylist(), chunked["row_hash"].to_pylist()))
assert len(got) == 3 * ROW_GROUP_SIZE
assert got == {i: expected[i] for i in got}
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", __file__]))
There was a problem hiding this comment.
Thanks, adopted this structure: shared _reader / _unit_id / _assert_positions helpers, the merged one-unit-per-batch test, and the parametrized scan-group strategy test.
…no filter is pushed down A synthesized column with `requires_read_unit_boundaries` (today `row_hash`) needs every batch to come from one row group. The Parquet reader got that by scanning every row group on its own, which gives up pyarrow's coalesced reads across row groups and adds a scan per row group. When no filter is pushed down, every on-disk row comes out of the scan, so a manifest row's row groups can be scanned together and the batches split back at the row groups' footer row counts. The reader now does that (`_get_scan_groups`); with a pushed-down filter it keeps scanning each row group on its own, since rows dropped inside the scan hide the boundaries. Synthesized columns see the same units and positions either way. Local benchmark (2M rows, 3 columns, one task): with 2,000 row groups of 1,000 rows, a row_hash read drops from 535 ms to 106 ms (88 ms without row_hash); with 200 row groups of 10,000 rows, from 39 ms to 16 ms. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
91fdb21 to
2c95991
Compare
|
This pull request has been automatically marked as stale because it has not had 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. |
|
closing this for now since stale/checkpointing is done |
Why are these changes needed?
A synthesized column with
requires_read_unit_boundaries(todayrow_hash, and the checkpoint ID column from 1/4) needs every batch to come from a single row group. The Parquet reader gets that by scanning every row group on its own. That gives up pyarrow's coalesced reads across row groups and adds a scan per row group, which is costly with many small row groups, especially on object storage.What changes
FileReadergains_get_scan_groups, where one pyarrow scan can cover several consecutive read units in order._read_fragments_sequentialsplits each scanned table at unit boundaries. The default is one unit per scan, which is today's behavior.ParquetFileReader._get_scan_groupsbuilds the combined scans. Per-row logic moves into a small helper shared with_get_fragments_to_read.ReadUnits andReadUnitPositions either way. Therequires_read_unit_boundariesdocstring is updated to say the reader guarantees one unit per batch, not one scan per unit.cc @AarryaSaraf, since this changes how the reader serves read unit boundaries (discussed on Slack).
Benchmark
Local, one read task, 2M rows × 3 columns,
row_hashon, median of 5:row_hash)row_hash, per-row-group scans (before)row_hash, combined scans (after)Related issue number
N/A. Not a duplicate (no open PR touches read unit boundaries; see 1/4 for the search).
Stack: this is an independent speed-up, branched off master; it lands last, after 1/4 (#66732) → 2/4 (#66733) → 3/4 (#66736). Nothing depends on it for correctness: without it, row groups with a boundary-needing column are scanned one at a time, as today. It touches only the reader, and 3/4 touches only planner and checkpoint code, so they don't conflict.
Checks
pytest python/ray/data/tests/unit/datasource_v2/test_read_unit_boundaries.py: 13 passed.row_hashequals the whole-file read.pytest python/ray/data/tests/unit/datasource_v2 python/ray/data/tests/datasource_v2: 217 passed.pytest python/ray/data/tests/datasource/test_read_parquet_v2.py: 37 passed.pytest python/ray/data/tests/datasource/test_parquet.py: 275 passed, 21 failed. The failures are the identical set on unmodified master in my environment: pandas 3 returnslarge_stringwhere the tests expectstring(test_parquet_read_basic,test_parquet_read_partitioned*,test_get_parquet_dataset_fs_serialization_fallback).🤖 Generated with Claude Code