Repository navigation
[Data] Iceberg DSv2 [1/5]: Let the shared Datasource V2 seams carry a source's own metadata - #67037
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
… source's own metadata Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
748f218 to
296ec07
Compare
There was a problem hiding this comment.
Code Review
This pull request simplifies scanner implementations by providing default concrete implementations for the SupportsColumnPruning and SupportsLimitPushdown mixins. It also introduces support for carrying source-specific extra columns in FileManifest through the OnlineBinPacker to ensure custom metadata survives packing. Additionally, a pushdown_is_final flag is added to ListFiles to preserve constraints during logical optimization rules. I have no feedback to provide as there are no review comments.
… test helper Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
| def _concat_extra_columns(per_row: List[Optional[pa.Table]]) -> Optional[pa.Table]: | ||
| """The bin's extra columns, one row per output row, or ``None`` for none.""" | ||
| # All-or-nothing: a manifest's rows all have the same columns, and a bin | ||
| # only ever holds rows from one manifest. |
There was a problem hiding this comment.
Can we verify this assumption with a test that calls add_input twice?
There was a problem hiding this comment.
That comment was wrong indeed. Bins stay open across add_input calls, so one bin can hold rows from several input manifests. The all-or-nothing check still holds for a different reason: every manifest one source lists carries the same extra columns (Iceberg builds each listing block with one fixed schema from the table metadata). I've fixed the comment to say that. The assert below it is what enforces this: a bin that mixes rows with and without extra columns fails loudly instead of misaligning them.
| run=run, | ||
| # Zero-copy view of this row's extra columns, if it has any. | ||
| extra_columns=( | ||
| None if extra_columns is None else extra_columns.slice(row_index, 1) |
There was a problem hiding this comment.
Here we make one tiny table per row and then concat them, which gives one chunk per row.
With many files this may be slow.
Could we store the row index and do one take() per bin instead?
Or at least call combine_chunks() after the concat?
There was a problem hiding this comment.
Agreed, but I went with combine_chunks() rather than take() because a bin mixes rows from several add_input calls, so take() would mean carrying a source table and row index on every BinItem and still concatenating across sources.
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
| ) | ||
| # Each row arrived as its own one-row slice; merge them into one chunk per | ||
| # column, since Ray serializes a column chunk by chunk. | ||
| return pa.concat_tables(present).combine_chunks() |
There was a problem hiding this comment.
A bin mixes rows from several add_input calls, and a column inferred from values can be null in one listing block and list in another. concat_tables raises on that. Either pass promote_options="default" or require the source to build every block with one explicit schema and assert it here.
There was a problem hiding this comment.
added the explicit schema.
| present = [table for table in per_row if table is not None] | ||
| if not present: | ||
| return None | ||
| assert len(present) == len(per_row), ( |
There was a problem hiding this comment.
Please add a test that calls add_input twice with extra columns and checks a bin that spans both. That is the case this assert and the concat exist for.
|
|
||
| A partitioner that rebuilds its output rows instead of slicing its | ||
| input must pass these to :meth:`construct_manifest`, or that state | ||
| never reaches the reader. |
There was a problem hiding this comment.
RoundRobinPartitioner.next_partition is exactly that partitioner and still drops them. Please fix it in this PR, or state that extra columns are only supported with OnlineBinPacker and assert that in the planner
There was a problem hiding this comment.
Added the assert
| assert derived.limit is None | ||
|
|
||
|
|
||
| def test_final_pushdown_is_left_alone(tmp_path): |
There was a problem hiding this comment.
This builds the MapBatches by hand. Please also run the real optimizer with PushdownCountFiles so the flag is exercised end to end.
There was a problem hiding this comment.
Added test_count_pushdown_marks_its_listing_final: it runs LogicalOptimizer on Count(ReadFiles) over a Parquet file and checks the real PushdownCountFiles produces a MapBatches whose ListFiles has pushdown_is_final set. A predicate can't be part of it in this PR: Parquet's scanner declines the count rewrite whenever a filter is set, so no source here reaches that path. Iceberg is the first that does, and a later PR in this stack runs a filtered count() through the real optimizer, asserting the listing keeps the predicate and the count matches take_all().
…RobinPartitioner, and test both review cases Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
abhishekverma-ray
left a comment
There was a problem hiding this comment.
Thanks for the fixes. Approving.
| def push_limit(self, limit: int) -> Self: | ||
| """Push a row limit down to the scanner. | ||
|
|
||
| Args: | ||
| limit: Maximum number of rows to read. | ||
|
|
||
| Returns: | ||
| New Scanner instance with the limit applied. | ||
| A copy of this scanner with the limit applied. | ||
| """ | ||
| ... | ||
| combined = limit if self.limit is None else min(self.limit, limit) | ||
| return replace(self, limit=combined) |
There was a problem hiding this comment.
By making this concrete, are you planning to remove these functions from the callers like (ArrowFileScanner, McapScanner etc.)?
There was a problem hiding this comment.
Yes. Of course I couldnt account for the changes that happened since the PR came out but that should be updated now.
| ) | ||
| # Each row arrived as its own one-row slice; merge them into one chunk per | ||
| # column, since Ray serializes a column chunk by chunk. | ||
| return pa.concat_tables(present).combine_chunks() |
There was a problem hiding this comment.
Let's use the concat method from transform_pyarrow.py
There was a problem hiding this comment.
Handles extension types
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
… concat extra columns with transform_pyarrow Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
#67951) ## Summary Adds `iceberg_manifest.py`, which carries each PyIceberg `FileScanTask` that `plan_files()` returns, pickled with Ray's `cloudpickle`, as one row of a Datasource V2 `FileManifest`, and hands the same task back on the read side. It is the data contract the rest of the port is written against; nothing calls it yet. 2 of 5 in the stack moving `read_iceberg` onto Datasource V2 (#66181), built on #67037 (merged), which lets a source carry its own manifest columns. ## Before Datasource V2 splits a read into a `ListFiles` task that decides what to read and `ReadFiles` tasks that read it, and the only thing passed between them is a `FileManifest`: path, size and chunk metadata per file. An Iceberg read needs more per data file (its delete files, partition values and residual filter), and a PyIceberg `Table` or `FileIO` can't cross the task boundary to look them up again. There was no way to express an Iceberg scan task in V2. ## After `manifest_from_scan_tasks(tasks)` writes one manifest row per task: the three required columns (chunk metadata is null, since a task is a whole file) plus `__ib_scan_task`, the pickled task. `scan_tasks_from_manifest(manifest)` unpickles them in row order, and the reader in [3/5] hands them to `ArrowScan` unchanged. V1 already ships these same objects to its read tasks inside `ReadTask` closures, which Ray serializes with the same `ray.cloudpickle`. An earlier revision rebuilt each task from seven typed columns. That needed PyIceberg internals (`DataFile.from_args`, `Record`) that change between releases. On PyIceberg 0.9, `DataFile.from_args` doesn't exist, so every V2 read failed. Listing and reading run in one cluster with one PyIceberg version, so the pickled task needs none of them. This example plans a two-file table partitioned by `identity(region)` with `row_filter="n >= 5"`, then encodes and decodes the tasks: ``` __path: string __file_size: int64 __file_chunk_metadata: null __ib_scan_task: binary {'__path': '.../00000-0-4e69...parquet', '__file_size': 927, '__file_chunk_metadata': None, '__ib_scan_task': '<1111 bytes>'} partitions: ['Record[eu]', 'Record[us]'] residuals: ["GreaterThanOrEqual(term=Reference(name='n'), literal=LongLiteral(5))", "GreaterThanOrEqual(term=Reference(name='n'), literal=LongLiteral(5))"] same as planned: True ``` The cost is manifest size, which grows with the table's column count because a task carries per-column stats: about 1.6 KB per file at 10 columns and 84 KB at 1,000 (PyIceberg 0.11.1). Unpickling takes at most 0.11 ms per file, against 25 ms to read even a 100-row, 1,000-column file. ```mermaid flowchart TD subgraph Before subgraph BS["Subsystem: IO"] subgraph BC["Component: Datasource V2 read"] B1["ListFiles task"] -->|"FileManifest: path, size, chunk metadata"| B2["ReadFiles task"] end end end subgraph After subgraph AS["Subsystem: IO"] subgraph AC["Component: formats/iceberg/iceberg_manifest.py"] A1["plan_files(), in the ListFiles task"] -->|"FileScanTask"| A2["manifest_from_scan_tasks"] A2 -->|"FileManifest: 3 required columns + pickled task"| A3["scan_tasks_from_manifest"] A3 -->|"the same FileScanTask"| A4["ArrowScan, in the ReadFiles task"] end end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class A2,A3 added ``` The callers on either side of the two new functions arrive in [3/5]. ## Subsystems IO: a new `_internal/datasource_v2/formats/iceberg/` package (`__init__.py`, `iceberg_manifest.py`); tests in `tests/datasource/test_iceberg.py`. ## Testing `pytest python/ray/data/tests/datasource/test_iceberg.py -v -x --tb=short`: 96 passed on this branch rebased onto master `5a7c85e587` (pyarrow 24.0.0, PyIceberg 0.11.1). The same file also passes with [3/5] to [5/5] stacked on top (104, 133 and 139 passed). The three new tests round-trip planned tasks: - every field the reader uses survives, including a real residual and the delete files; - hand-built position deletes survive; - decoded tasks read the same rows through `ArrowScan` as the originals. On the previous revision, which pickled with the standard library's `pickle`, a manifest round trip followed by an `ArrowScan` read also returned identical rows on PyIceberg 0.8.1, 0.9.0, 0.11.0, 0.11.1 and 0.12.0rc1. On 0.11.1, `cloudpickle` writes the same bytes for these tasks. ruff 0.8.4 (default and `--select I`), black 22.10.0, pydoclint 0.9.1 and pyrefly (in CI's environment) report no errors. Not a duplicate: no open PR moves `read_iceberg` to Datasource V2; the only other open Iceberg PR, #68252, changes actor-pool sizing in the executor and doesn't touch the read path. 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](https://claude.com/claude-code) --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
) ## 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 `FileScanTask`s 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 #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. ```mermaid flowchart TD subgraph Before subgraph BS["Subsystem: IO"] subgraph BC["Component: formats/iceberg/ (V2)"] B1["iceberg_manifest.py<br/>FileScanTask <-> 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 ``` ## 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](https://claude.com/claude-code) --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Three changes to shared Datasource V2 code so a source whose listing already knows
more than a path and a size can use the common machinery instead of forking it. 1 of
5 in a stack moving
read_icebergonto DSv2; this one touches only shared code.A source's own manifest columns survive bin packing —
interfaces/file_manifest.py,common/online_bin_packer.py.FileManifestalready lets a source add columns besidethe three required ones, but
OnlineBinPackerrebuilt each bin from those three alone,so the rest were dropped. Adds
FileManifest.extra_columnsand anextra_columnsargument to
construct_manifest, and carries a zero-copy one-row table on eachBinItem. Packing a manifest with two source columns and reading the names back out:flowchart TD L["ListFiles task"] -->|"FileManifest: 3 required + 2 source columns"| P["OnlineBinPacker"] P -->|"before: rebuilt from the 3 required"| B["ReadFiles sees 3"] P -->|"after: BinItem.extra_columns carries each row"| A["ReadFiles sees 5"]The pushdown mixins carry their own state —
interfaces/pushdown.py,common/arrow_file_scanner.py.SupportsColumnPruningandSupportsLimitPushdownwerepure interfaces, so every scanner rewrote the same field and the same
replace(self, ...)body. They are now frozen dataclasses with keyword-only fields anddefault implementations: pruning intersects, limit takes the smaller.
ArrowFileScannerdrops 46 lines. Intersecting also fixes a bug — the old bodies overwrote the projection
and tested it for truthiness, so an empty projection (what
count()pushes down)re-widened:
ListFiles.pushdown_is_final—logical/operators/read_operator.py,logical/rules/derive_list_files_pushdown.py,logical/rules/pushdown_count_files.py.DeriveListFilesPushdownclears a listing's constraints when the consumer is not aReadFiles, since an arbitrary consumer will not apply them.PushdownCountFilesrewrites
Count(ReadFiles(ListFiles))intoMapBatches(count_rows, ListFiles), and itscount_rowsdoes apply the scanner's filter, through the same reader the deletedReadFileswould have used. The flag lets that rule say so instead of silently losingthe predicate and returning an unfiltered count.
Tests:
pytest python/ray/data/tests/unit/datasource_v2/test_online_bin_packer.py test_pushdown_mixins.py test_derive_list_files_pushdown.py— 31 passed.test_pushdown_mixins.pyis new; the other two gain cases for extra columns survivingpacking/splitting/merging and for
pushdown_is_final. ruff 0.8.4 (default and--select I), black 22.10.0, pydoclint 0.9.1 and pyrefly 0.51.0 clean on these files.Not a duplicate: no open PR changes
OnlineBinPacker, the pushdown mixins orPushdownCountFiles. #66654 (MCAP) and #66573 (Hive HS2) consume this shared coderather than modify it, and the mixin consolidation is what review on #66654 asked for.
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