Skip to content

[Data][Chkpt] [1/4] Add generated_id_column checkpointing: row IDs as a DSv2 synthesized column - #66732

Merged
goutamvenkat-anyscale merged 1 commit into
ray-project:masterfrom
abhishekverma-ray:rgc2-1-generated-id-column
Oct 8, 2026
Merged

goutamvenkat-anyscale merged 1 commit into
ray-project:masterfrom
abhishekverma-ray:rgc2-1-generated-id-column

Conversation

@abhishekverma-ray

@abhishekverma-ray abhishekverma-ray commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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

  • I've signed off every commit (DCO).
  • 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.
  • 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

@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 support for generating row IDs automatically when a dataset lacks a unique ID column, using CheckpointConfig(generated_id_column=...). It implements a new GeneratedIdColumn synthesized column for the V2 Parquet reader, integrates it with the checkpointing configuration and query planner, and adds comprehensive tests. The review feedback highlights two main improvements: making path splitting in generated_id.py robust to Windows-style paths, and wrapping global DataContext modifications in tests within try...finally blocks to prevent test state leakage.

@goutamvenkat-anyscale goutamvenkat-anyscale added the go add ONLY when ready to merge, run all tests label Oct 7, 2026
…d column

Adds `CheckpointConfig(generated_id_column=...)` for Parquet inputs that
have no unique ID column. Ray Data stamps each row with a struct ID naming
where it lives (file, row group, position in the row group) through a new
`GeneratedIdColumn`, built on DSv2's `SynthesizedColumn` / `ReadUnit`.

- CheckpointConfig: `generated_id_column`, mutually exclusive with
  `id_column`; the generated name is also exposed as `id_column`, so the
  existing checkpoint write path works unchanged.
- `GeneratedIdColumn` sets `requires_read_unit_boundaries` and refuses to
  build IDs for a whole-file read unit instead of writing wrong ones.
- `read_parquet` builds the column from the checkpoint config and passes it
  to `ParquetDatasourceV2(extra_synthesized_columns=...)` explicitly. Ray
  Data's own checkpoint reads opt out with an internal
  `_add_generated_id_column=False` (same pattern as `_block_udf`), so the
  public signature is unchanged and checkpoint files never get the column.
- `ParquetDatasourceV2.infer_schema` raises if a file already has a column
  with the requested name, rather than silently replacing user data.
- Until restore is wired up, 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
  through the numpy-based ID filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the rgc2-1-generated-id-column branch from b54d98b to c225127 Compare October 8, 2026 03:38
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 98f29e9 into ray-project:master Oct 8, 2026
6 checks passed
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 14, 2026
…and partial row masks (#66733)

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 a `GeneratedIdCheckpoint`, 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 hook `excluded_read_unit_ids` (#66398) expects.
- `partial_masks`: an Arrow table, one row per row group with only some
rows committed: `unit_id` and a boolean `partial_mask` indexed by
`row_id`. These are small: only row groups in flight when a job stopped
are partly done.
- **Compaction:** committed IDs are grouped per file with Ray Data
(`groupby(path_prefix, file_name).map_groups`) into one row per done or
partly done read unit: `unit_id` plus `partial_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.
- **Refactor:** `CheckpointManager.load_checkpoint` is split so the
shared steps live in `_load_checkpoint_block`: clean pending
checkpoints, list committed files only (#66387), read, preprocess, one
block. The `id_column` path's behavior is unchanged. The generated-ID
manager's `load_checkpoint` (the numpy array path) raises, because
struct IDs can't go there.
- The checkpoint read opts out of the generated ID column (from 1/4).
- **CI:** `checkpoint/generated_id.py` joins
`ci/lint/pyrefly-excluded-files.txt`. Its `pyarrow.compute` calls
(`pc.struct_field` and 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

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit on all changed files: clean. The
API-annotation check 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:
- `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.
- pyrefly (CI's file set and flags) on the changed files: 0 errors. API
parameter coverage check: nothing newly undocumented.

🤖 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]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 16, 2026
…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]>
goutamvenkat-anyscale added a commit that referenced this pull request Oct 31, 2026
#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]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 9, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants