Skip to content

[Data] Iceberg DSv2 [3/5]: Listing, scanning and reading Iceberg - #68152

Merged
sampan-s-nayak merged 8 commits into
ray-project:masterfrom
AarryaSaraf:iceberg-dsv2-parity-3-read
Nov 23, 2026
Merged

sampan-s-nayak merged 8 commits into
ray-project:masterfrom
AarryaSaraf:iceberg-dsv2-parity-3-read

Conversation

@AarryaSaraf

@AarryaSaraf AarryaSaraf commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the three components that list, plan and read an Iceberg table on Datasource V2: IcebergFileIndexer, IcebergScanner and IcebergFileReader, written against the manifest from #67951 (merged). Nothing calls them yet; [4/5] wires them into read_iceberg behind a flag, so this PR changes no behaviour. 3 of 5 in the stack moving read_iceberg onto Datasource V2 (#66181).

It also switches that manifest's scan-task column to large_binary, a fix that landed after #67951 merged, and moves the Iceberg filter translation and empty-projection helpers out of the V1 module so datasource_v2 doesn't import from it.

Before

formats/iceberg/ had only the manifest codec: manifest_from_scan_tasks turns PyIceberg FileScanTasks into FileManifest rows and scan_tasks_from_manifest turns them back, but nothing produced those tasks in a ListFiles task or read them in a ReadFiles task. read_iceberg runs entirely on the V1 datasource, which also owns the Ray-to-Iceberg filter visitor.

After

  • iceberg_file_indexer.py: runs plan_files() inside the ListFiles task and writes one manifest row per surviving data file, 1024 files per manifest block (only to amortize building Arrow arrays, since OnlineBinPacker regroups the rows into read units). It plans from the table metadata and FileIO the driver already loaded, never from the catalog, because the catalog's config (.pyiceberg.yaml, PYICEBERG_CATALOG__*) may exist only on the driver; V1 never loads it in a task either. Listing reads Iceberg metadata only, no data files. A pushed predicate is ANDed into the scan's row filter so partitions and files are pruned during listing, and excluded_read_unit_ids is matched against file paths because a read unit is always a whole file.
  • iceberg_scanner.py: frozen dataclass pickled to every read task, with filter, column and limit pushdown. A predicate that doesn't translate to an Iceberg filter is handed back and applied above the read instead of being dropped. A bare column filter (col("is_valid")) stays there too, because it translates to a term that plan_files rejects. Pruned columns come back in the order asked for, not schema order.
  • iceberg_file_reader.py: one PyIceberg ArrowScan per file, which applies position deletes, field-ID schema resolution, type promotion and partition backfill without reimplementing any of them. One file per call because ArrowScan holds every batch of every task it is handed, so passing a whole read unit would hold the whole unit. Each batch is checked with raise_on_pickle_object_columns and then cast to the projected schema, since two files can disagree on string vs large_string; V1 does the same cast.
  • iceberg_utils.py: _IcebergExpressionVisitor (Ray Expr to PyIceberg filter) and _get_empty_projection_schema move here unchanged from V1's _internal/datasource/iceberg_datasource.py, plus the new combine_row_filter. V1's datasource and datasink now import them from here (iceberg_datasource.py +5/-211, iceberg_datasink.py and test_conversion.py one import each).
  • iceberg_manifest.py: __ib_scan_task is now pa.large_binary() instead of pa.binary(). OnlineBinPacker merges a read unit's rows into one array, and a binary array holds at most 2 GiB, so a unit whose pickled tasks passed that would fail. Column stats can't get there (a task stays under 1.6× its file), but attached position delete files can: each adds about 370 bytes to its task, so it takes thousands of un-compacted deletes on every data file in a 128 MiB unit. Cursor Bugbot flagged it on [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg #67951 after that PR merged.

There is no Iceberg partitioner: the shared OnlineBinPacker groups the rows into read units and, since #67037, carries the __ib_scan_task column through. Bins are sized by each file's on-disk size for now; sizing by the projected columns only, from the column_sizes each task already carries, is a follow-up.

One fix no design anticipated: count() projects no columns, and PyIceberg returns zero-row batches for an empty projection. On a 5-row table, ArrowScan.to_record_batches with an empty projection yields 0 rows. The scanner projects V1's stub field instead (no file has it, so Iceberg fills it with nulls and decodes no data column), which yields 5, and the reader turns it into the same all-null stub column the other V2 readers use, because Arrow tables with no columns lose their row count on concat.

flowchart TD
    subgraph Before
        subgraph BS["Subsystem: IO"]
            subgraph BC["Component: formats/iceberg/ (V2)"]
                B1["iceberg_manifest.py<br/>FileScanTask &lt;-&gt; FileManifest row"]
            end
            subgraph BV["Component: datasource/ (V1)"]
                B2["iceberg_datasource.py<br/>owns the filter visitor + stub schema"]
            end
        end
    end
    subgraph After
        subgraph AS["Subsystem: IO"]
            subgraph AC["Component: formats/iceberg/ (V2)"]
                A1["IcebergFileIndexer<br/>(ListFiles task)"] -->|"FileScanTasks from plan_files()"| A2["iceberg_manifest.py<br/>scan task as large_binary"]
                A2 -->|"FileManifest rows, packed by OnlineBinPacker"| A3["IcebergScanner.create_reader<br/>(ReadFiles task)"]
                A3 -->|"read unit"| A4["IcebergFileReader<br/>one ArrowScan per file"]
                A4 -->|"pa.Table, pickle-checked, cast"| A5["blocks"]
                A6["iceberg_utils.py<br/>filter visitor, stub schema, combine_row_filter"]
                A6 -.-> A1
                A6 -.-> A3
            end
            subgraph AV["Component: datasource/ (V1)"]
                A7["iceberg_datasource.py, iceberg_datasink.py<br/>import the helpers from iceberg_utils"]
            end
            A6 -.-> A7
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A3,A4,A6 added
    class A2,A7 changed
Loading

Subsystems

IO: _internal/datasource_v2/formats/iceberg/ (iceberg_file_indexer.py, iceberg_scanner.py, iceberg_file_reader.py, iceberg_utils.py, iceberg_manifest.py); V1 _internal/datasource/iceberg_datasource.py and iceberg_datasink.py change imports only. Tests in tests/datasource/test_iceberg.py and tests/unit/expressions/test_conversion.py (import path).

Testing

pytest python/ray/data/tests/datasource/test_iceberg.py: 100 passed on master a24e301204 (pyarrow 24.0.0, PyIceberg 0.11.1). The same file also passes with the two PRs stacked on this one, which wire it into read_iceberg (130 and 136 passed); tests/unit/expressions/test_conversion.py 60 passed. Four new tests drive the components directly, since nothing wires them up yet: a pickled-object column is rejected before anything is unpickled, a pushed predicate prunes files during listing, an excluded file stays unlisted, and a bare column filter is not pushed. Packing and delete handling belong to OnlineBinPacker and PyIceberg's ArrowScan and are tested there; column order is tested through read_iceberg in [4/5]. ruff 0.8.4 (default and --select I), black 22.10.0, pydoclint 0.9.1 and pyrefly 0.51.0 clean.

Not a duplicate: apart from this stack, no open PR moves read_iceberg to Datasource V2 (searched open PRs for "iceberg").

AI assistance (Claude Code) was used. I have reviewed every changed line and ran the tests above locally.

Signed-off-by: Aarrya [email protected]

🤖 Generated with Claude Code

@AarryaSaraf
AarryaSaraf force-pushed the iceberg-dsv2-parity-3-read branch 2 times, most recently from 0203ef2 to 6aeebaa Compare November 18, 2026 21:51
AarryaSaraf and others added 3 commits November 18, 2026 13:58
…y so a packed bin can pass 2 GiB

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf
AarryaSaraf force-pushed the iceberg-dsv2-parity-3-read branch from 6aeebaa to 5a82244 Compare November 18, 2026 22:11
if predicate is None:
return row_filter, None
try:
translated = _IcebergExpressionVisitor().visit(predicate)

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.

A predicate can translate but still fail to bind to the table's types.

col("id") >= 1.5 on a long column translates, push_filters reports it as fully pushed, and then plan_files() fails in the listing task with TypeError: Cannot convert DoubleLiteral into long.

Without pushdown, Ray's filter returns ids 2-6 (V1 fails the same way).

Could we bind the translated filter against the table schema here (pyiceberg.expressions.visitors.bind(schema, expr, case_sensitive)) and hand the predicate back on failure?

Then it stays above the read, as the design intends.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These PRs don't focus on pushdown; that's for the stack after this.

literal,
)

RAY_DATA_OPERATION_TO_ICEBERG = {

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.

Iceberg handles nulls and NaN differently from Ray:

  • ~col("x").is_in([1]): Ray keeps the null rows (ids 2, 3, 5, 6). Pushed down, we get only 3 and 6.
  • col("f") != 0.1: Ray keeps the NaN row. Pushed down, it's dropped.

Ray drops its own filter when it's pushed down, so users silently get different rows. V1 has the same issue. Could we push down only =, <, <=, >, >=, in, is_null, is_not_null, and, or, and leave the rest to Ray? Or file an issue if that's out of scope here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and V1 has the same bug. #68325 adds a shared is_statistics_safe check for the NaN case in Parquet; I'll fix Iceberg V1 and V2 together in a follow-up once it merges, reusing that check plus one Iceberg-only rule for the null case (PyIceberg turns a one-value not in into !=, which drops nulls).

)

rows_read = 0
for task in scan_tasks_from_manifest(manifest=input_split):

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.

This reads one file per ArrowScan call, so DataContext.iceberg_config.read_file_tasks_sequentially = False does nothing here. That costs a lot on tables with delete files: every call re-reads the delete files for its file, so a delete file shared by 100 data files is read 100 times. Could we pass all the files in one call when the setting is False, as V1 does?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: when read_file_tasks_sequentially is False, the reader now passes the whole read unit to one ArrowScan call, as V1 does, so a shared delete file is read once per unit. The default stays one file per call.


if predicate is None:
return row_filter, None
try:

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.

If any part of A & B can't be converted, nothing gets pushed down. So (col("date") == d) & some_udf doesn't skip any files and lists the whole table. Could we split on &, push the parts that convert, and hand back only the rest?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These PRs don't focus on pushdown; that's for the stack after this.


assert read(rebuilt).equals(read(tasks))

def test_reader_rejects_pickle_object_columns(self, monkeypatch, tmp_path):

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.

None of the new tests read rows through IcebergFileReader. count(), limit, column order and filters are only tested in [4/5]. One test that lists and reads the existing test table (all columns, reordered columns, zero columns, a limit, a filter) would cover this PR on its own. It could also include col("id") >= 1.5 on an integer column, which crashes the read today.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[4/5] runs the existing read tests on both V1 and V2 (all columns, selected columns, zero columns and count(), filters), so I'd rather not repeat them here. The >= 1.5 crash is gone now that this stack has no filter pushdown.

…asks_sequentially

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@abhishekverma-ray abhishekverma-ray added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 20, 2026
@abhishekverma-ray

Copy link
Copy Markdown
Contributor

Thanks, LGTM for this layer. I checked the sequential-read fix locally: with read_file_tasks_sequentially = False, a read unit now goes to one ArrowScan call, so delete files load once per unit instead of once per file.

Two things for the next PRs:

  1. V2 is on by default, and row_filter is deprecated in favor of .filter(). If [4/5] sends read_iceberg to V2 before filter pushdown is back, .filter() won't skip any files and every read scans the whole table. Can we keep read_iceberg on V1 until the pushdown stack lands?
  2. V1 still returns wrong rows for != and ~is_in with null/NaN values, and still crashes on col("id") >= 1.5 on an integer column. Could you file an issue for the follow-up you described? Please also include read_file_tasks_sequentially = False when [4/5] runs the read tests on V2.

…lter helpers

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@AarryaSaraf

Copy link
Copy Markdown
Contributor Author

Thanks, LGTM for this layer. I checked the sequential-read fix locally: with read_file_tasks_sequentially = False, a read unit now goes to one ArrowScan call, so delete files load once per unit instead of once per file.

Two things for the next PRs:

  1. V2 is on by default, and row_filter is deprecated in favor of .filter(). If [4/5] sends read_iceberg to V2 before filter pushdown is back, .filter() won't skip any files and every read scans the whole table. Can we keep read_iceberg on V1 until the pushdown stack lands?
  2. V1 still returns wrong rows for != and ~is_in with null/NaN values, and still crashes on col("id") >= 1.5 on an integer column. Could you file an issue for the follow-up you described? Please also include read_file_tasks_sequentially = False when [4/5] runs the read tests on V2.
  1. V2 will be on once we are at least at parity with V1. This wont happen until the second PR from our optimization stack.
  2. Iceberg metadata tracks NaNs which can allow us to do better pushdown and not just guard against this case so we wont need that check. This comes in the optimization stack

@AarryaSaraf
AarryaSaraf marked this pull request as ready for review November 20, 2026 22:22
@AarryaSaraf
AarryaSaraf requested review from a team as code owners November 20, 2026 22:22

@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 V2 datasource implementation for Iceberg, adding IcebergFileIndexer, IcebergFileReader, and IcebergScanner, while moving shared utilities to a common iceberg_utils.py. It also updates manifest serialization to use large_binary to handle larger tasks. The review feedback highlights two important issues: first, IcebergScanner.read_schema should return a schema with the stub column when the pruned schema is empty to avoid downstream mismatches; second, IcebergFileReader should slice record batches to strictly respect the remaining limit when reading sequentially.

Comment on lines +78 to +84
def read_schema(self) -> pa.Schema:
from pyiceberg.io.pyarrow import schema_to_pyarrow

if self.columns is None:
return self.schema
# The schema the reader projects to, so the column order matches.
return schema_to_pyarrow(self._pruned_schema(), include_field_ids=False)

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

When self.columns is empty (e.g., during a count() operation), self._pruned_schema() has 0 fields, causing read_schema() to return an empty schema. However, create_reader() returns an IcebergFileReader with drop_all_columns=True, which yields tables containing the batch-size-preserving stub column (_BATCH_SIZE_PRESERVING_STUB_COL_NAME) of type pa.null(). This schema mismatch can cause errors downstream. read_schema() should return a schema containing the stub column when the pruned schema is empty.

Suggested change
def read_schema(self) -> pa.Schema:
from pyiceberg.io.pyarrow import schema_to_pyarrow
if self.columns is None:
return self.schema
# The schema the reader projects to, so the column order matches.
return schema_to_pyarrow(self._pruned_schema(), include_field_ids=False)
def read_schema(self) -> pa.Schema:
from pyiceberg.io.pyarrow import schema_to_pyarrow
if self.columns is None:
return self.schema
pruned = self._pruned_schema()
if len(pruned.fields) == 0:
from ray.data._internal.arrow_block import _BATCH_SIZE_PRESERVING_STUB_COL_NAME
return pa.schema([(_BATCH_SIZE_PRESERVING_STUB_COL_NAME, pa.null())])
# The schema the reader projects to, so the column order matches.
return schema_to_pyarrow(pruned, include_field_ids=False)

Comment on lines +119 to +121
for record_batch in self._scan(limit=remaining).to_record_batches([task]):
rows_read += record_batch.num_rows
yield record_batch

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

When reading file tasks sequentially, PyIceberg's to_record_batches might return a batch that exceeds the remaining limit (since it may not slice the last batch to the exact limit). To ensure we strictly respect the limit and do not return more rows than requested, we should slice the record batch to remaining if it exceeds it.

Suggested change
for record_batch in self._scan(limit=remaining).to_record_batches([task]):
rows_read += record_batch.num_rows
yield record_batch
for record_batch in self._scan(limit=remaining).to_record_batches([task]):
if remaining is not None and record_batch.num_rows > remaining:
record_batch = record_batch.slice(0, remaining)
rows_read += record_batch.num_rows
yield record_batch

@abhishekverma-ray abhishekverma-ray 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.

Looks fine. Just one thing, if the user turns on REST server-side planning, V1 lets the catalog plan, but V2 plans by itself and ignores the setting. Can #68436 handle that case, by planning on the driver? Avoid falling back to V1.

@sampan-s-nayak
sampan-s-nayak merged commit 5b7f03e into ray-project:master Nov 23, 2026
5 checks passed
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