Repository navigation
[Data][Chkpt] [2/4] Load generated-ID checkpoints as done read units and partial row masks - #66733
Conversation
91072eb to
4513037
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]>
4513037 to
f5cfdff
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces GeneratedIdColumnCheckpointManager and helper utilities to support compacting committed generated IDs into done read units and row masks for partly done row groups, along with comprehensive unit tests. The review feedback highlights two critical issues: a potential indexing bug in _compact_file_ids when handling negative or out-of-bounds values, and an invalid schema comparison in _validate_loaded_checkpoint where a ray.data.Schema is compared directly with a pyarrow.Schema.
f5cfdff to
f0fa3fd
Compare
| if loaded is None: | ||
| return GeneratedIdCheckpoint() | ||
| block_ref, _ = loaded | ||
| compacted = BlockAccessor.for_block(ray.get(block_ref)).to_arrow() |
There was a problem hiding this comment.
Should use timeout=0 inside ray.get to make it non-blocking, and add some retries. Let's make this a shared utility that can be reused
There was a problem hiding this comment.
I don't think timeout=0 helps here.
It just raises if the block isn't local yet, so with retries it becomes a busy loop that still waits.
We do need to wait: this runs once before the job starts, and listing and reading both need the result.
Ray already retries fetches and rebuilds lost objects, and the id_column path uses a plain ray.get too.
Were you worried about a hang? If so, I can add a timeout with a clear error as a shared helper.
| """ | ||
| done_unit_ids = set() | ||
| partial_masks: Dict[str, np.ndarray] = {} | ||
| for row in compacted.to_pylist(): |
There was a problem hiding this comment.
Why are we converting to python here?
There was a problem hiding this comment.
Fair point. Only the unit ids need to be Python strings, since listing matches on them. The masks now stay as numpy arrays the whole way.
There was a problem hiding this comment.
Follow-up: the whole checkpoint now stays in Arrow (see the newer thread).
f0fa3fd to
4856638
Compare
| unit_ids = compacted["unit_id"].to_pylist() | ||
| masks = compacted["partial_mask"].combine_chunks() | ||
| is_done = masks.is_null().to_numpy(zero_copy_only=False) | ||
| offsets = masks.offsets.to_numpy() | ||
| values = masks.values.to_numpy(zero_copy_only=False) | ||
| done_unit_ids = frozenset( | ||
| unit_id for unit_id, done in zip(unit_ids, is_done) if done | ||
| ) | ||
| partial_masks: Dict[str, np.ndarray] = { | ||
| unit_id: values[offsets[i] : offsets[i + 1]] | ||
| for i, (unit_id, done) in enumerate(zip(unit_ids, is_done)) | ||
| if not done | ||
| } | ||
| return GeneratedIdCheckpoint(done_unit_ids, partial_masks) |
There was a problem hiding this comment.
is_done = pc.is_null(compacted["partial_mask"])
done_unit_ids = pc.filter(compacted["unit_id"], is_done).combine_chunks()
partial_masks = (
compacted.filter(pc.invert(is_done))
.select(["unit_id", "partial_mask"])
.combine_chunks()
)
return GeneratedIdCheckpoint(done_unit_ids, partial_masks)
You can keep it in arrow
There was a problem hiding this comment.
Done, the checkpoint now stays in Arrow. One catch: listing builds a frozenset from the excluded ids, and a set built straight from an Arrow array holds Arrow values, so nothing would match. Listing now calls .to_pylist() first (in #66736), inside the listing task, so the driver stays light and each task gets a small payload.
…ow masks Adds `GeneratedIdColumnCheckpointManager.load_generated_id_checkpoint()`, which turns the committed generated IDs into what a resumed job can skip, in DSv2 read-unit terms (`GeneratedIdCheckpoint`): - `done_unit_ids`: a file's path when all its row groups are committed, otherwise `"<path>#rg<N>"` per committed row group. These are the ids the listing hook `excluded_read_unit_ids` drops. - `partial_masks`: for row groups with only some rows committed, the read unit id mapped to a boolean mask indexed by `row_id`. The committed IDs are grouped per file with Ray Data (groupby + map_groups) and compacted per row group; duplicate IDs from rows written more than once are counted once. `CheckpointManager.load_checkpoint` is split so the clean / read-committed-files / preprocess steps (`_load_checkpoint_block`) are shared with the existing `id_column` path, which is otherwise unchanged. The checkpoint read itself opts out of the generated ID column. Nothing calls the new load yet; the planner wiring follows separately. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
4856638 to
db73425
Compare
…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]>
#66800) > Stacked on #66680 (which is stacked on #66562 and #66563). Only review the last commit: "[Data][Train] Support generated ID columns for mid-epoch resumption". > > **Depends on the generated-ID checkpointing stack:** #66732 adds `CheckpointConfig(generated_id_column=...)`, and #66733 / #66736 skip committed rows on restore. This PR assumes that API and can't merge before #66732. ## Description Adds `DatasetCheckpointConfig(generate_id_column=True)` for mid-epoch resumption. Users whose datasets have no unique ID column can then checkpoint the data iterator with row IDs that Ray Data generates from each row's location in its Parquet file. Changes: - **`DatasetCheckpointConfig`:** `generate_id_column=True` no longer raises `NotImplementedError`. Only Parquet reads on the V2 datasource path are supported. - **`CheckpointingBatchIterator`:** when the ID column is generated, it's recorded in `BatchMetadata.row_ids` for checkpointing, then removed from the batch before it's yielded, so users only see their own columns. A user-provided `id_column` is kept. - **`DatasetManager._build_restoration_checkpoint_config`:** builds the dataset's `CheckpointConfig` with `generated_id_column=` instead of `id_column=` when generating. The config is set even when there's nothing to restore, because the reader needs it to generate the ID column. - **Release test:** `mid_epoch_resume_benchmark_{{scale}}` passes `--generate_id_column`. ## Related issues Not a duplicate: this adds Train-ingest support on top of the generated-ID checkpointing stack (#66732, #66733, #66736), which covers batch inference only. ## Additional information Tests (run locally, Python 3.11, macOS): - `pytest python/ray/data/tests/test_data_iterator_checkpointer.py`: 25 passed. This includes the new `test_generated_id_column_removed_from_batches`, which checks that the column is removed from batches when generated and kept otherwise, and that the IDs are checkpointed either way. - `RAY_TRAIN_V2_ENABLED=1 pytest python/ray/train/v2/tests/test_dataset_checkpointing.py python/ray/train/v2/tests/test_dataset_manager.py`: - **On this branch alone, all e2e cases fail** with `TypeError: CheckpointConfig.__init__() got an unexpected keyword argument 'generated_id_column'`, because that argument comes from #66732. This is expected until #66732 lands. - With a temporary stand-in `generated_id_column=None` parameter on `CheckpointConfig` (not committed): 12 passed. The only 2 failures were the two `generate_id_column=True` e2e cases, which need the generated-ID reader support from that stack. - `pre-commit run` on the changed files: passed. AI assistance (Claude Code) was used to develop this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Justin Yu <[email protected]> Signed-off-by: Goutam <[email protected]> Co-authored-by: Goutam <[email protected]>
## Why are these changes needed?
In `ray.data.checkpoint.generated_id._compact_file_ids`, compacting
committed generated row IDs for a Parquet file previously performed
three avoidable (N)$ / (N \cdot G)$ operations ($ = committed rows in
the file, $ = distinct row groups in the file):
1. **Redundant (N)$ dictionary string decoding for file-constant
metadata**: `_id_field(ids, PATH_PREFIX_FIELD, pa.string())[0]`,
`_id_field(ids, FILE_NAME_FIELD, pa.string())[0]`, and `_id_field(ids,
NUM_FRAGMENTS_FIELD, pa.int32())[0]` cast and materialized all $ entries
into NumPy arrays just to read index `[0]`. Slicing `ids.slice(0, 1)`
first decodes only a single element ((1)$).
2. **(N \cdot G)$ full-array equality scans across row groups**: `for
row_group in np.unique(row_groups): in_group = row_groups == row_group`
scanned all $ rows once for each of the $ unique row groups. Sorting
once via `np.argsort(row_groups, kind="stable")` only when `row_groups`
is not already non-decreasing and finding contiguous group boundaries
via `np.flatnonzero(row_groups[1:] != row_groups[:-1]) + 1` reduces
grouping to a single (N)$ pass when ordered ((N \log N)$ when
unordered).
3. **Per-group (K \log K)$ `np.unique` sorting**: `committed =
np.unique(row_ids[in_group])` sorted each group's row IDs to count
unique valid indices or populate the boolean mask. Because boolean mask
indexing (`mask[valid_ids] = True`) is idempotent on duplicate row IDs
and all valid row IDs lie in `[0, size)`, populating `mask` directly and
checking `len(valid_ids) >= size and mask.all()` determines whether the
row group is fully committed in (K + \text{size})$ time without sorting
or allocating a separate array.
On a file with 4,000 row groups (126,000 committed rows),
`_compact_file_ids` wall time drops from **817.8 ms to 166.1 ms (4.92x
speedup)**.
## Duplicate-work & attribution check
- Searched open and closed issues and PRs in `ray-project/ray` for
`_compact_file_ids` and `generated_id`; no existing issue or PR
addresses this optimization.
- Credits to the original generated-ID checkpointing implementation in
#66732 and #66733.
- AI assistance was used in profiling and drafting this change; all
changes and tests were reviewed and verified locally.
## Checks
- [x] I've signed off every commit(`by: git commit -s`) in this PR.
- [x] I've run `pytest -v
python/ray/data/tests/unit/test_generated_id_checkpoint.py` locally
(**16 passed in 0.36s**, including a new unit test covering unsorted and
interleaved row-group chunks).
---------
Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
Follow-up to 1/4 (#66732, merged). 3/4 (#66736) builds on this.
Why are these changes needed?
A resumed generated-ID job has to know what's already done, in terms the DSv2 read path understands: read units (files and Parquet row groups). This PR turns the committed generated IDs into exactly that, so the planner in 3/4 (#66736) can skip it: listing drops the done units, and a step after the read drops the done rows of partly done row groups.
What changes
GeneratedIdColumnCheckpointManager.load_generated_id_checkpoint()returns aGeneratedIdCheckpoint, kept in Arrow so it stays small on the driver and cheap to send to tasks:done_unit_ids: an Arrow string array. A file's path when every row group of the file is committed, otherwise"<path>#rg<N>"per committed row group. Ids come from DSv2's_row_group_unit_id, so they match what the listing hookexcluded_read_unit_ids([Data] DSv2 Reorg [3.5/6]: Let a listing task leave out read units a checkpoint already finished #66398) expects.partial_masks: an Arrow table, one row per row group with only some rows committed:unit_idand a booleanpartial_maskindexed byrow_id. These are small: only row groups in flight when a job stopped are partly done.groupby(path_prefix, file_name).map_groups) into one row per done or partly done read unit:unit_idpluspartial_mask(null when done). A file whose row groups are all done is a single row with its path. Masks stay numpy end to end. Duplicate IDs, from rows written more than once, are counted once, so a partly done row group never looks done.CheckpointManager.load_checkpointis split so the shared steps live in_load_checkpoint_block: clean pending checkpoints, list committed files only ([Data][1/4] Iceberg Checkpoint: only read committed parquet on checkpoint restore #66387), read, preprocess, one block. Theid_columnpath's behavior is unchanged. The generated-ID manager'sload_checkpoint(the numpy array path) raises, because struct IDs can't go there.checkpoint/generated_id.pyjoinsci/lint/pyrefly-excluded-files.txt. Itspyarrow.computecalls (pc.struct_fieldand friends) are generated at runtime, so pyrefly reports them as missing; other pyarrow-heavy checkpoint files (checkpoint_filter.py,interfaces.py) are excluded for the same reason.Nothing calls the new load yet; 3/4 does.
Related issue number
N/A. Not a duplicate (see 1/4).
Checks
pytest python/ray/data/tests/unit/test_generated_id_checkpoint.py: 9 passed. Covers done vs. partial row groups, duplicates counted once, whole file named when all row groups are done, and compacted paths matching the source path exactly (bare file name, absolute path, and a backslash Windows-style path) and IDs outside a row group never marking it done.pytest python/ray/data/tests/test_checkpoint.py(on current master): 92 passed, 1 failed (the same pre-existing local moto-S3 flake as 1/4). New: loading real checkpoint files with pending files ignored and the generated-ID config active during the load; empty checkpoint.🤖 Generated with Claude Code