Skip to content

[Data] [2/4] Add GeneratedIdColumnCheckpointManager with compact per-file checkpoint load - #65886

Closed
abhishekverma-ray wants to merge 1 commit into
ray-project:masterfrom
abhishekverma-ray:rg-chkpt-2-compact-checkpoint-load
Closed

abhishekverma-ray wants to merge 1 commit into
ray-project:masterfrom
abhishekverma-ray:rg-chkpt-2-compact-checkpoint-load

Conversation

@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Stack: PR 2 of 4 — stacked on #65885 (generated_id_column config + ID generation). Review scope: the last commit only ("Add GeneratedIdColumnCheckpointManager with compact per-file checkpoint load"). Follow-ups: [3/4] list/read-time skipping, [4/4] planner routing + docs.

Why are these changes needed?

Committed checkpoint files store one generated struct ID per output row. The existing restore path (CheckpointManager.load_checkpoint → convert_and_sort_checkpointed_ids → sorted numpy array → actor-pool NumpyArrayBasedCheckpointFilter) cannot consume a struct-typed ID column, and a per-row anti-join would defeat the point of row-group-addressed IDs.

This PR adds the load side of the generated-ID design: at restore time, raw committed IDs are compacted into one row per input file with schema
(checkpointed_file: string, checkpointed_file_fragments: struct{num_fragments, fully_checkpointed, fragments: list<struct{fragment_id, num_rows, num_checkpointed_rows, checkpointed_row_ids: list<bool>}>}).

Compact-representation semantics (consumed by PR 3/4): a never-seen file has no row; a fully committed row group stores an empty mask list; a partially committed row group stores a dense boolean mask. Unfinished work is encoded as absence — uncommitted rows are never stored.

Key pieces:

  • GeneratedIdColumnCheckpointManager (in checkpoint_filter.py): overrides the existing _preprocess_data_pipeline hook — map_batches extracts (path_prefix, file_name) from the struct → hash-shuffle groupby → map_groups compacts each file → sort(checkpointed_file) — and _validate_loaded_checkpoint (schema check). New load_checkpoint_as_block() returns the compact block ref (empty sentinel pa.table({}) when there's no checkpoint data).
  • Refactor: CheckpointManager.load_checkpoint now shares _load_checkpoint_block (pending-2PC cleanup first, then read committed IDs, preprocess, repartition to one block) with the new block-returning path. The numpy tail of the id_column path is unchanged.
  • generated_id.py gains the compact schema constants plus its consumers: parse_checkpointed_fragment_info / exclude_checkpointed_rows (read-time row filtering, used in PR 3) and index_checkpointed_fragments / get_checkpoint_fragments_info_for_file / is_file_fragments_fully_checkpointed (list-time lookup, used in PR 3). Struct fields are always resolved by name (get_struct_field_index) because Parquet round-trips don't preserve struct field order.
  • LoadCheckpointCallback loads the compact block in before_execution_starts for generated-ID configs and exposes load_checkpoint() (consumed by the ListFiles plan function in PR 4). Delete-on-success is unchanged for both paths; failures still leave pending files as the recovery record.

Nothing routes to this code yet — the planner switch-on is PR 4.

Related issue number

N/A. Not a duplicate: searched open PRs/issues in ray-project/ray for generated_id_column, "row group checkpoint" — no overlapping work.

Checks

  • I've signed off every commit (DCO).
  • I've run pre-commit hooks on all touched files — clean.
  • 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:
    • New tests in python/ray/data/tests/test_checkpoint.py: TestGeneratedIdFragmentParsing (parse full/partial/no-entry/never-seen, num_rows-mismatch assertion, exclude with batch offsets and bounds, index/lookup) and test_generated_id_checkpoint_compaction / test_generated_id_checkpoint_load_empty (end-to-end compaction through real Ray groupby/map_groups; mixed full/partial/never-seen files; empty sentinel) — 12 passed.
    • Regression: full test_checkpoint.py — 97/98 locally (the one failure is the pre-existing test_skip_checkpoint_flag[s3] local moto-server slowness, also failing on clean master).

…heckpoint load

Ports the generated-ID checkpoint load path from RayTurbo:

- generated_id.py gains the compact checkpoint table schema
  (checkpointed_file, checkpointed_file_fragments struct) and its
  consumers: parse_checkpointed_fragment_info / exclude_checkpointed_rows
  (read-time row filtering) and index/lookup helpers (list-time file
  skipping). Semantics: never-seen file has no row (null struct); a fully
  committed row group stores an empty mask list; a partial row group
  stores a dense boolean mask. Struct fields are always resolved by name
  because Parquet round-trips don't preserve struct field order.
- CheckpointManager.load_checkpoint is refactored around a shared
  _load_checkpoint_block (clean pending 2PC leftovers first, read
  committed IDs, preprocess, repartition to one block).
  GeneratedIdColumnCheckpointManager overrides the preprocess hook to
  compact raw struct IDs (hash-shuffle groupby file -> one row per file,
  sorted by path) and exposes load_checkpoint_as_block, since the
  numpy-based actor-pool filter can't consume struct IDs.
- LoadCheckpointCallback loads the compact block before execution for
  generated-ID configs and exposes load_checkpoint() for the upcoming
  ListFiles kwarg injection; delete-on-success is unchanged for both
  paths and failures still leave pending files as the recovery record.

Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the rg-chkpt-2-compact-checkpoint-load branch from 479a969 to 4f847c3 Compare September 11, 2026 17:08
@abhishekverma-ray
abhishekverma-ray marked this pull request as ready for review September 11, 2026 17:11
@abhishekverma-ray
abhishekverma-ray requested a review from a team as a code owner September 11, 2026 17:11

@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 the GeneratedIdColumnCheckpointManager and associated helpers to support auto-generated row-ID columns in Ray Data checkpointing by compacting committed IDs into a per-file representation. The review feedback highlights several important issues: a potential ArrowInvalid error in _process_file_group due to array length mismatch when no row groups are processed, a potential AttributeError in is_file_fragments_fully_checkpointed when handling unseen files, a performance bottleneck from repeatedly converting blocks to PyArrow Tables in a loop, and a robust schema comparison fix in _validate_loaded_checkpoint.

Comment on lines +544 to +547
else:
checkpointed_row_ids_array = pyarrow.array(
[[]], type=pyarrow.large_list(pyarrow.bool_())
)

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.

high

If checkpointed_row_ids_arrays is empty (i.e., len(grouped) == 0), creating checkpointed_row_ids_array with [[]] results in an array of length 1. However, other arrays like fragments_array and num_rows_array will have length 0. This mismatch in lengths will cause pyarrow.StructArray.from_arrays to raise an ArrowInvalid error. Using an empty list [] instead of [[]] ensures the array has length 0, matching the other fields.

Suggested change
else:
checkpointed_row_ids_array = pyarrow.array(
[[]], type=pyarrow.large_list(pyarrow.bool_())
)
else:
checkpointed_row_ids_array = pyarrow.array(
[], type=pyarrow.large_list(pyarrow.bool_())
)

Comment on lines +400 to +407
fully_checkpointed_field_idx = get_struct_field_index(
checkpointed_fragments_info.checkpointed_file_fragments,
CHECKPOINTED_FILE_FULLY_CHECKPOINTED_FIELD,
)
return pc.struct_field(
checkpointed_fragments_info.checkpointed_file_fragments,
[fully_checkpointed_field_idx],
).as_py()

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.

high

If checkpointed_fragments_info.checkpointed_file_fragments is None (which is the case for any never-seen/unseen file), calling get_struct_field_index will raise an AttributeError because None has no .type attribute. Adding a guard to return False when the fragments are None or invalid prevents this crash.

Suggested change
fully_checkpointed_field_idx = get_struct_field_index(
checkpointed_fragments_info.checkpointed_file_fragments,
CHECKPOINTED_FILE_FULLY_CHECKPOINTED_FIELD,
)
return pc.struct_field(
checkpointed_fragments_info.checkpointed_file_fragments,
[fully_checkpointed_field_idx],
).as_py()
if (
checkpointed_fragments_info.checkpointed_file_fragments is None
or not checkpointed_fragments_info.checkpointed_file_fragments.is_valid
):
return False
fully_checkpointed_field_idx = get_struct_field_index(
checkpointed_fragments_info.checkpointed_file_fragments,
CHECKPOINTED_FILE_FULLY_CHECKPOINTED_FIELD,
)
return pc.struct_field(
checkpointed_fragments_info.checkpointed_file_fragments,
[fully_checkpointed_field_idx],
).as_py()

Comment on lines +362 to +393
def get_checkpoint_fragments_info_for_file(
checkpointed_ids: Optional[Block],
path: str,
checkpointed_fragments_by_path: Dict[str, int],
) -> CheckpointFragmentsInfo:
"""Look up one file's checkpoint struct from the compact checkpoint block.

Args:
checkpointed_ids: Block with
``CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA``, or None.
path: The file path to look up.
checkpointed_fragments_by_path: Index built by
:func:`index_checkpointed_fragments` over the same block.

Returns:
The file's :class:`CheckpointFragmentsInfo`; its struct scalar is
None when the file has no checkpoint entry.
"""
if checkpointed_ids is None or path not in checkpointed_fragments_by_path:
return CheckpointFragmentsInfo(path=path, checkpointed_file_fragments=None)

checkpointed_ids_table = BlockAccessor.for_block(checkpointed_ids).to_arrow()
if checkpointed_ids_table.num_rows == 0:
return CheckpointFragmentsInfo(path=path, checkpointed_file_fragments=None)

file_index = checkpointed_fragments_by_path[path]
checkpointed_file_fragments = checkpointed_ids_table[
CHECKPOINTED_FILE_FRAGMENTS_COLUMN_NAME
][file_index]
return CheckpointFragmentsInfo(
path=path, checkpointed_file_fragments=checkpointed_file_fragments
)

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.

medium

Calling BlockAccessor.for_block(checkpointed_ids).to_arrow() inside get_checkpoint_fragments_info_for_file is a performance bottleneck if this function is called repeatedly in a loop (once per file). Since the caller already has or can easily obtain the pa.Table representation, changing the parameter to accept pa.Table directly avoids this redundant overhead on every lookup.

def get_checkpoint_fragments_info_for_file(
    checkpointed_ids_table: Optional[pa.Table],
    path: str,
    checkpointed_fragments_by_path: Dict[str, int],
) -> CheckpointFragmentsInfo:
    """Look up one file's checkpoint struct from the compact checkpoint table.

    Args:
        checkpointed_ids_table: Table with
            ``CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA``, or None.
        path: The file path to look up.
        checkpointed_fragments_by_path: Index built by
            :func:`index_checkpointed_fragments` over the same block.

    Returns:
        The file's :class:`CheckpointFragmentsInfo`; its struct scalar is
        None when the file has no checkpoint entry.
    """
    if checkpointed_ids_table is None or path not in checkpointed_fragments_by_path:
        return CheckpointFragmentsInfo(path=path, checkpointed_file_fragments=None)

    if checkpointed_ids_table.num_rows == 0:
        return CheckpointFragmentsInfo(path=path, checkpointed_file_fragments=None)

    file_index = checkpointed_fragments_by_path[path]
    checkpointed_file_fragments = checkpointed_ids_table[
        CHECKPOINTED_FILE_FRAGMENTS_COLUMN_NAME
    ][file_index]
    return CheckpointFragmentsInfo(
        path=path, checkpointed_file_fragments=checkpointed_file_fragments
    )

Comment on lines +618 to +621
assert schema == CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA, (
f"Schema mismatch: {schema} != "
f"{CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA}"
)

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.

medium

Comparing a Ray Schema wrapper directly with a pyarrow.Schema using == may return False even if they are semantically identical, depending on how Schema.__eq__ is implemented. Converting the Ray Schema to a pyarrow.Schema using schema.to_arrow_schema() is more robust and guarantees a correct comparison.

Suggested change
assert schema == CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA, (
f"Schema mismatch: {schema} != "
f"{CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA}"
)
assert schema.to_arrow_schema() == CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA, (
f"Schema mismatch: {schema} != "
f"{CHECKPOINTED_GENERATED_ID_COLUMN_TABLE_SCHEMA}"
)

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 4f847c3. Configure here.

checkpointed_row_count = checkpointed_row_counts[i].as_py()
row_ids_list = row_ids_lists[i]

if checkpointed_row_count == num_rows:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicate IDs falsely mark groups done

High Severity

A row group is marked fully checkpointed when the raw committed-ID list length equals num_rows, without uniquing. Duplicate IDs from a retried task that reccommits earlier batches can make that count match even when some rows were never written, so restore skips unfinished work.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4f847c3. Configure here.

"""
path_prefix = file_group_batch[PATH_PREFIX_FIELD][0].as_py()
file_name = file_group_batch[FILE_NAME_FIELD][0].as_py()
file_path = f"{path_prefix}/{file_name}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Rebuilt file paths fail to round-trip

Medium Severity

Compaction rebuilds the file path by concatenating path_prefix, /, and file_name. That is not the inverse of os.path.dirname / os.path.basename used when IDs are generated, so root-relative files and files at / get a different string than fragment.path and will not match at lookup time.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4f847c3. Configure here.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Sep 11, 2026
@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.

@abhishekverma-ray

Copy link
Copy Markdown
Contributor Author

Superseded by the redo on top of the DSv2 reorg: #66732, #66733, #66734, #66735, #66736.

goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 8, 2026
…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]>
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]>
richardliaw pushed a commit that referenced this pull request Nov 6, 2026
…, row_id (#66654)

## Description

Part 1 of 3 of the `read_mcap` move to Datasource V2, based on master.
#67166 is stacked on it, and #67167 on #67166. The rest of the
`read_mcap` stack (#67189 onward) sits on top.

**Problem.** One task reads one whole file:

- Parallelism is capped by the file count: ten 30 GB recordings are ten
tasks.
- Every file is opened, even when its index shows it holds nothing
selected.
- Rows have no stable id, so a checkpointed pipeline cannot resume.

**Change.** `read_mcap` moves to Datasource V2, on by default as for
`read_parquet` (`DataContext.use_datasource_v2`). The legacy datasource
stays as the fallback.

```
files
  │  listing: read each file's index (a few ranged reads)
  │           one row per chunk, weighted by the memory reading it takes
  │           drop chunks that cannot match topics / time_range
  ▼
chunk rows
  │  packing: about 128 MiB per read task
  │           one big file ──► many tasks;  small files ──► one task
  │           with preserve_order: one task per file, in listing order
  ▼
read tasks: seek to their chunks, merge them by log time
```

- New code lives in `datasource_v2/formats/mcap/`. The V2 interfaces do
not change.
- Columns and types match the legacy path, with two changes.
`schema_data` is dictionary-encoded. A new `channel_metadata` column
holds each channel's metadata map as JSON text, dictionary-encoded, so a
block stores it once per channel.
- `data` holds decoded JSON only when every selected channel is JSON.
Otherwise it holds bytes. Planning types it from the selected messages
of the first chunk that holds one, as a read task types the messages it
holds.
- `row_id` is `<path>#c=<chunk offset>:<index>`, stable however the read
is split. It is on with `include_row_id=True`, or automatically under
`CheckpointConfig(id_column="row_id")`.
- New `log_time_order` argument, default `True`. Each task returns each
of its files in `log_time` order. With `preserve_order`, each file is
read by one task, so it comes out in order from start to end, and files
come out in the order they were listed. #67166 splits a large file there
too, only where its order holds.
- A file whose summary cannot be read gets a read task of its own, so
`max_errored_blocks` can skip it alone.
- The task size is `RAY_DATA_MCAP_BIN_PACKING_BYTES` (128 MiB).

**Changed after the first review round.** Each is its own commit:

- Summaries and chunks are read in a few ranged requests, not a few
bytes per GET.
- An unreadable file gets a read task of its own.
- Tables are built column by column, cut counting every column, and
chunks are weighted by the memory reading them takes.
- The read stops at the row limit.
- A file without a chunk index is sorted by log time.
- `channel_metadata` is JSON text, stored once per block.
- With `preserve_order`, each file is kept in one read task, and files
keep their listing order.
- Planning skips a chunk it cannot decode, and types `data` from the
first chunk's messages.

**Measured** on an 845 MB recording with 1,052 chunks: reading its 125
KB summary took about 20,000 GETs and now takes 3.

**Decisions to confirm:**

- Splitting is on by default. Block boundaries change; rows do not.
- With `preserve_order`, this PR reads each file in one task, as the
legacy reader does. #67166 lets it split a large file where its log-time
order holds.
- `ds.schema()` comes from the first chunk that holds a selected
message. A field that first appears later is missing from it; the
docstring says so.

## Related issues

- Related to #65640 and #65641.
- No open PR moves MCAP to Datasource V2. #66524 (ORC) and #66182
(Iceberg) are other formats moving to V2.
- The generated-ID stack (#65886 to #65888) is orthogonal.
- `log_time_order` comes from my #66653, now closed. My legacy-path PRs
#65912, #65913 and #65916 are closed in favour of this one.

## Additional information

```
PYTHONPATH=python/ray/data/tests pytest python/ray/data/tests/datasource/test_mcap.py \
  python/ray/data/tests/unit/datasource_v2/test_mcap_*.py \
  python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py
```

178 passed, 3 skipped. pre-commit and pyrefly clean.

AI assistance (Claude Code) was used to draft this change; I reviewed
every line and ran the tests above locally.

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

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant