Repository navigation
[Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg - #67951
goutamvenkat-anyscale merged 8 commits into
Conversation
4ba3180 to
60959b1
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces the iceberg_manifest.py module to handle the serialization and deserialization of PyIceberg FileScanTask objects into PyArrow tables, along with comprehensive unit tests to verify the round-trip preservation of metadata, delete files, and partition columns. The review feedback highlights two key improvement opportunities: first, addressing a potential correctness issue when decoding partitions by explicitly checking the parent StructArray's null mask to prevent child arrays from ignoring parent nulls; second, optimizing the partition field name collision detection from O(N^2) to O(N) using collections.Counter.
| struct = column.combine_chunks() if isinstance(column, pa.ChunkedArray) else column | ||
| child_values = { | ||
| field.name: struct.field(index).to_pylist() | ||
| for index, field in enumerate(struct.type) | ||
| } | ||
| records = [] | ||
| for row, spec_id in enumerate(spec_ids): | ||
| values = [] | ||
| for field in specs[spec_id].fields: | ||
| value = child_values[names[field.field_id]][row] | ||
| values.append( | ||
| None | ||
| if value is None | ||
| else _to_partition_representation( | ||
| fields[field.field_id].field_type, value | ||
| ) | ||
| ) | ||
| records.append(Record(*values)) |
There was a problem hiding this comment.
In PyArrow, calling struct.field(index).to_pylist() retrieves the child array's values directly, which does not inherit or respect the parent StructArray's null bitmap. If the parent struct itself is null for a given row, the child array's value at that row might not be None (it could contain a default or garbage value). To prevent subtle correctness bugs when decoding partitions, we should explicitly check the parent struct's null mask and set the value to None if the parent struct is null.
struct = column.combine_chunks() if isinstance(column, pa.ChunkedArray) else column
null_mask = struct.is_null().to_pylist() if struct.null_count > 0 else None
child_values = {
field.name: struct.field(index).to_pylist()
for index, field in enumerate(struct.type)
}
records = []
for row, spec_id in enumerate(spec_ids):
values = []
for field in specs[spec_id].fields:
value = (
None
if (null_mask and null_mask[row])
else child_values[names[field.field_id]][row]
)
values.append(
None
if value is None
else _to_partition_representation(
fields[field.field_id].field_type, value
)
)
records.append(Record(*values))There was a problem hiding this comment.
The parent struct is never null here: _encode_partitions is the only writer of this column and builds it with StructArray.from_arrays and no mask, so a file with no partition values gets null children, not a null struct.
| collisions = { | ||
| name | ||
| for name in (field.name for field in fields.values()) | ||
| if sum(1 for f in fields.values() if f.name == name) > 1 | ||
| } |
There was a problem hiding this comment.
The current implementation of collision detection uses a nested generator expression with sum(), resulting in an collections.Counter.
from collections import Counter
counts = Counter(field.name for field in fields.values())
collisions = {name for name, count in counts.items() if count > 1}| # ``partition_type`` builds. | ||
| for position, field in enumerate(specs[task.file.spec_id].fields): | ||
| if position < len(record): | ||
| columns[names[field.field_id]][row] = record[position] |
There was a problem hiding this comment.
A UUID partition value read from a real manifest is a uuid.UUID object, not bytes. PyIceberg’s UUIDReader returns it that way. pyarrow then rejects it at line 185 with “Expected bytes, got a ‘UUID’ object”, so listing fails on any table partitioned by a UUID column. Please convert each value here with the same PyIceberg converter the decoder uses.
There was a problem hiding this comment.
Good catch, fixed. plan_files() does return a uuid.UUID, and pyarrow 23 (our minimum, and the CI pin) rejects it with that error. 24 and later accept it, which is why it passed for me. The encoder now converts it to its 16 bytes.
I didn't route every value through _to_partition_representation. A manifest's time value is already an int, and the converter calls .hour on it:
_to_partition_representation(TimeType(), 3_600_000_000)
# AttributeError: 'int' object has no attribute 'hour'| "us-west-2", | ||
| 19723, | ||
| decimal.Decimal("1.25"), | ||
| uuid.UUID(int=7).bytes, |
There was a problem hiding this comment.
This test passes because the UUID value is hand-built as bytes. More broadly, the typed-partition tests use hand-made records, so they check our guess about PyIceberg’s values. Please add real-table round trips: write a table per partition type, plan it, encode, decode, and compare rows through ArrowScan. Identity partitions need no extra dependency.
There was a problem hiding this comment.
Added test_real_table_partition_round_trip: one table per Iceberg primitive type, identity-partitioned with a null among the values, planned, encoded, decoded, and compared on both the partition records (values and Python types) and the rows through ArrowScan. It caught that a decoded UUID came back as bytes instead of the uuid.UUID PyIceberg plans, so the decoder now keeps the uuid.UUID, and the hand-built test uses one too.
| record_counts.append(data_file.record_count) | ||
| # Sorted so a manifest row is reproducible across executions; the set | ||
| # PyIceberg hands us has no order. | ||
| deletes = sorted(task.delete_files, key=lambda f: f.file_path) |
There was a problem hiding this comment.
The reader rebuilds every delete file as a position delete at line 342. That is safe today because PyIceberg rejects equality deletes during planning. Please assert here that each delete file’s content is POSITION_DELETES, so a newer PyIceberg fails loudly instead of returning deleted rows.
There was a problem hiding this comment.
Done: listing now raises NotImplementedError for any delete file that isn't a position delete. I used a raise rather than an assert, since this depends on the user's table rather than on our own invariant, and python -O strips asserts.
|
The design looks right to me: typed columns are smaller and safer than pickling the scan tasks. I ran the encode and decode against real PyIceberg 0.11.1 tables. Identity partitions on string, date, timestamp, time, decimal, boolean, binary and double all round-trip, and so does spec evolution on v1 and v2. The UUID case is the one real bug. Also, the Testing section still says “TBD” for the test run. Could you paste the result? |
| # ``partition_type`` builds. | ||
| for position, field in enumerate(specs[task.file.spec_id].fields): | ||
| if position < len(record): | ||
| value = record[position] |
There was a problem hiding this comment.
Not blocking, for [3/5].
With REST server-side scan planning (opt-in, PyIceberg 0.12), partition values come straight from the JSON response. A date arrives as a string like "2024-01-01", not as days since epoch. pyarrow will reject that when building the typed column here, so listing fails for those tables.
Could [3/5] either convert these values, or raise a clear error saying REST scan planning isn't supported yet?
abhishekverma-ray
left a comment
There was a problem hiding this comment.
Approved. Please check my request for PR 3/5.
| return records | ||
|
|
||
|
|
||
| def manifest_from_scan_tasks( |
There was a problem hiding this comment.
Where is this function being invoked?
There was a problem hiding this comment.
Nowhere in this PR yet. [3/5] (#68152) adds both callers: IcebergFileIndexer.list_files calls it in the listing task, once per 1024 planned files, and IcebergFileReader calls the inverse, scan_tasks_from_manifest, in each read task.
| columns[DELETE_FORMATS_COLUMN_NAME][i], | ||
| ) | ||
| } | ||
| yield FileScanTask(data_file, delete_files=deletes) |
There was a problem hiding this comment.
The rebuilt task gets PyIceberg's default residual=ALWAYS_TRUE, even though the manifest carries __ib_residual_is_true. Nothing on the read path uses it today (ArrowScan re-applies the full filter), but any code that checks task.residual on a rebuilt task will treat a filtered file as fully matching.
V1's metadata-only count() does exactly that check (isinstance(getattr(task, "residual", None), AlwaysTrue) for every task). If that logic is ported onto these tasks, count() with row_filter=col_a > 100 on an unpartitioned table returns the unfiltered total of record_count.
Could we restore it here (pass the scan's row filter in and use it whenever the flag is false)? If not, the docstring should say the rebuilt residual can't be trusted.
There was a problem hiding this comment.
Restored it: scan_tasks_from_manifest now takes the scan's row_filter and uses it as the residual of every file whose __ib_residual_is_true is false, AlwaysTrue otherwise. That's wider than Iceberg's own residual but equivalent on that file's rows, which already satisfy whatever their partition implies. Nothing reads it yet, but a rebuilt task no longer claims a filtered file fully matches.
| file_format=delete_format, | ||
| partition=partition, | ||
| spec_id=spec_id, | ||
| record_count=0, |
There was a problem hiding this comment.
The docstring says nothing downstream reads a delete file's record_count, but V1's exact count does: it subtracts the position-delete record_counts from the data files' totals. On rebuilt tasks that subtracts 0, so a 1M-row table with a position-delete file removing 10k rows would count 1,000,000 instead of 990,000.
The real delete counts also aren't stored in the manifest, so the V2 count can't match V1's metadata-only path whenever position deletes exist; it would have to fall back to reading those files. Could we carry the delete record_counts as another list column, next to __ib_delete_paths?
There was a problem hiding this comment.
This is fine for correctness: nothing in V2 subtracts delete counts. [5/5]'s count() decodes any file that has delete files, as PyIceberg's own DataScan.count() does, so that example counts 990,000. Answering those files from metadata instead is an optimization, so that will come in the next stack.
| # Iceberg's internal representations directly per child -- an int for a | ||
| # date, a ``Decimal`` for a decimal, 16 bytes for a UUID. | ||
| children = [ | ||
| pa.array(columns[field.name], type=field.type) for field in partition_type |
There was a problem hiding this comment.
If the source column of an old partition field was later dropped, spec.partition_type(schema) gives that field UnknownType (PyIceberg 0.11.1 added that fallback so such tables stay readable). schema_to_pyarrow maps it to a pa.null() child, and encoding any non-null value into it fails.
Example: spec 0 was identity(category). The spec later evolved to drop that field, and then the category column was dropped. Old data files under spec 0 still carry 'books'. pa.array(['books'], type=pa.null()) raises ArrowInvalid, so manifest_from_scan_tasks fails and the whole read crashes, though PyIceberg plans and reads these files fine. A time-travel read of an older snapshot hits the same thing.
There was a problem hiding this comment.
Ah yes. Fixed: a partition field typed pa.null() now stays null in the manifest.
| schema = table_metadata.schema() | ||
| for spec in table_metadata.partition_specs: | ||
| for field in spec.partition_type(schema).fields: | ||
| fields.setdefault(field.field_id, field) |
There was a problem hiding this comment.
The docstring above says partition-field ids are unique within a table, but the Iceberg spec only guarantees that from format v2. In v1 tables the reader assigns ids sequentially from 1000 in each spec, so two different fields can share an id, and setdefault keeps only the first.
Example: a v1 table with spec 0 = identity(region: string) (id 1000) and spec 1 = bucket(id, 16) (also id 1000). The union keeps only the string child, so encoding a spec-1 row puts an int into a string array and raises ArrowTypeError. When the two types happen to be compatible it's quieter and worse: values decode through the other field's type in _to_partition_representation.
There was a problem hiding this comment.
I see. Listing now raises an error in this situation.
| f"{_DB_NAME}.{_TABLE_NAME}" | ||
| ) | ||
|
|
||
| def test_manifest_preserves_every_field_the_reader_uses(self): |
There was a problem hiding this comment.
A few paths aren't covered:
- No test checks the
__ib_residual_is_truevalues. - Nothing exercises the equality-delete
NotImplementedError. - No manifest goes through
OnlineBinPacker/FileManifest.concat, so the chunked-struct branch in_decode_partitionsis untested. - Every read comparison projects columns that are also written into the data files, so
ArrowScannever fills a column from the rebuilt partition (_get_column_projection_values). Reads would stay identical even if the decoded partitions were wrong. A test where an identity-partition column is missing from the data file would cover this.
There was a problem hiding this comment.
No longer applies. The round-trip test now plans with a filter and checks the residual survives.
| _IDENTITY_PARTITION_CASES, | ||
| ids=[str(field_type) for field_type, _ in _IDENTITY_PARTITION_CASES], | ||
| ) | ||
| def test_real_table_partition_round_trip(self, tmp_path, field_type, column): |
There was a problem hiding this comment.
These 20 unit tests for an internal V2 module live in test_iceberg.py, which is bazel size = "medium" (300s) and exclusive. Every one of them first runs the autouse pyiceberg_table fixture, which creates the shared table, appends rows and runs a delete, though most of them build their own metadata or catalog. The PR description says the whole file was last run before the review fixes, so it isn't known whether the target still fits in 300s with the new cases. They'd fit better in tests/unit/datasource_v2/, next to the hive, orc and mcap V2 tests.
There was a problem hiding this comment.
After the rework this PR has 3 tests, and the V2 tests the later PRs add share this file's table fixture and need Ray, so they stay together here.
| PartitionField(3, 1002, IdentityTransform(), "amount"), | ||
| PartitionField(4, 1003, IdentityTransform(), "gid"), | ||
| PartitionField(5, 1004, IdentityTransform(), "blob"), | ||
| PartitionField(6, 1005, BucketTransform(16), "flag_bucket"), |
There was a problem hiding this comment.
Iceberg doesn't define bucket for boolean sources, so this case tests a spec no real table can have. PartitionSpec doesn't validate transforms, so it passes anyway. A bucket over a string or uuid column would cover a layout real tables use.
There was a problem hiding this comment.
No longer applies
| return records | ||
|
|
||
|
|
||
| def manifest_from_scan_tasks( |
There was a problem hiding this comment.
Bigger picture: rebuilding FileScanTask field by field from a hand-typed union struct is lossy by design. It drops the residual, delete counts, column_sizes and deletion-vector offsets, and most of the other comments on this file are edge cases of the typed partition encoding. An alternative is to carry the planned task (or its DataFiles) as one opaque serialized column, alongside the few columns the framework actually needs (path, size, record count, residual flag).
One concrete cost of dropping column_sizes: V1 uses them for a projection-aware size estimate (_estimate_inmemory_file_size). Without them the packer budgets on the whole compressed file size, which ignores both the projection (reading 1 of 100 columns is sized like reading all of them) and the decode ratio.
There was a problem hiding this comment.
Done: the manifest now carries the pickled FileScanTask next to the three columns the framework requires, so column_sizes travels too. Using it for a projection-aware size estimate is for the next stack.
| } | ||
|
|
||
|
|
||
| def partition_arrow_type(table_metadata: "TableMetadata") -> Optional[pa.DataType]: |
There was a problem hiding this comment.
_partition_fields plus partition_arrow_type largely re-implement PyIceberg's public TableMetadata.specs_struct(): the union of all specs sorted by field id, which inspect.files / inspect.entries pass to schema_to_pyarrow. Separately, each manifest_from_scan_tasks call computes the partition type twice (manifest_schema, then _encode_partitions) and _partition_fields / _child_names three times, each walking every spec. Computing fields, names and type once and passing them down would remove the repeated work.
There was a problem hiding this comment.
No longer applies
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 3e63152. Configure here.
| FILE_CHUNK_METADATA_COLUMN_NAME: pa.nulls(len(tasks)), | ||
| SCAN_TASK_COLUMN_NAME: pa.array( | ||
| [pickle.dumps(task) for task in tasks], type=pa.binary() | ||
| ), |
There was a problem hiding this comment.
Pickle column hits Arrow size limit
Medium Severity
Storing pickled FileScanTasks in a pa.binary() column is limited by Arrow’s 32-bit offsets, so one manifest whose pickled payloads sum to more than 2GB fails at listing. A pickled DataFile carries column stats and bounds that the previous typed columns did not, so a wide table with many data files can hit that cap.
Reviewed by Cursor Bugbot for commit 3e63152. Configure here.
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…deletes in the Iceberg manifest Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…nd keep UUID partition values as uuid.UUID Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…Ray's pyarrow 23 minimum makes dead Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…est instead of rebuilding it Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
…e, as V1's read tasks are Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Aarrya <[email protected]>
a7ef037 to
50ab231
Compare
…floop-input * upstream/master: [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366) [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329) [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118) [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947) [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117) [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318) [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988) [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259) [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177) [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302) [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085) [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162) [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161) [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248) [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951) [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317) [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306) [Train] Support post-mortem debugging for training function errors (ray-project#68296) [train][1/n] Give each health probe its own timeout (ray-project#68191) [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266) [Train] Add a guide to debugging failures and hangs (ray-project#68299) [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662) [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845) [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862) [doc] Refresh intersphinx inventory snapshots (ray-project#68303) [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467) [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243) [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218) [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803) [core][sandbox] Remove the readonly option (ray-project#68088) [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907) [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151) [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156) [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210) [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072) [serve][llm] Remove decode load progress (ray-project#68258) [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250) [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262) [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730) [serve] Observe the result of rank reassignment reconfigures (ray-project#67923) [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243) [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061) [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595) [Train] Remove local mode (ray-project#68239) [Data] Fix filtered Lance row-count metadata (ray-project#67228) [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437) [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079) [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242) [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888) [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542) [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004) [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171) [core] Send generator consumed-progress updates from io_service_ (ray-project#67160) [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154) [data][llm] Keep the prompt in vLLM error rows (ray-project#67665) [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699) [Data] Read text files on DataSource v2 (ray-project#68063) [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332) [Serve] Show progress of updating (ray-project#67107) [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009) [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175) [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788) [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974) [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816) [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360) [doc] Refresh intersphinx inventory snapshots (ray-project#68069) [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204) [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145) [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201) [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172) [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909) [Train] Count elastic workers in resource units for fractional resources (ray-project#68139) [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130) [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767) [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135) feat(core): add Cambricon MLU resource support (ray-project#66368) [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154) [data] Fix Parquet filename suffix detection (ray-project#67156) [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927) [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149) [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691) [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925) [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924) [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167) [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620) [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838) [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937) [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114) [Train] Count elastic workers in resource units for fractional resources (ray-project#68139) [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590) [data] Add Top-N execution (ray-project#66931) [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483) [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720) [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690) [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110) [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850) [core] Deflake tests that race on timing (ray-project#67717) [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285) [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109) [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166) [core][sandbox] Commit sandbox as new registry image (ray-project#67972) [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930) [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915) [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879) [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519) [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856) [Train] Do not start an elastic worker group with zero workers (ray-project#68101) [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070) [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359) [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065) [core][test] Create auth token in test_redis_wrong_password (ray-project#68014) [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698) [Data] Fix typing mismatches in Dataset public API (ray-project#62077) [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929) [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164) [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647) [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887) [Data] Eliminate redundant aggregation shuffle (ray-project#67198) [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005) [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045) [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006) [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878) [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837) [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122) [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900) [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899) [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898) [Core] Add initial foundational configurations and flags for fork server (ray-project#67356) [core][sandbox] Image layers caching (ray-project#67874) [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779) [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292) [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046) [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718) [train] Fix checkpoint sorting to support nested metrics (ray-project#59130) [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671) [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901) [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184) [core] Deflake `_run_hanging_command` tests (ray-project#67461) [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007) [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067) [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719) [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968) [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722) [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844) [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087) [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974) [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873) [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836) Add perf metrics for 2.60.0 (ray-project#67727) [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958) Signed-off-by: Eugene Paniot <[email protected]> # Conflicts: # python/ray/data/_internal/planner/plan_udf_map_op.py
) ## 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]>


Summary
Adds
iceberg_manifest.py, which carries each PyIcebergFileScanTaskthatplan_files()returns, pickled with Ray'scloudpickle, as one row of a Datasource V2FileManifest, 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 movingread_icebergonto Datasource V2 (#66181), built on #67037 (merged), which lets a source carry its own manifest columns.Before
Datasource V2 splits a read into a
ListFilestask that decides what to read andReadFilestasks that read it, and the only thing passed between them is aFileManifest: 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 PyIcebergTableorFileIOcan'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 toArrowScanunchanged. V1 already ships these same objects to its read tasks insideReadTaskclosures, which Ray serializes with the sameray.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_argsdoesn'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)withrow_filter="n >= 5", then encodes and decodes the tasks: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.
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 addedThe 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 intests/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 master5a7c85e587(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:
ArrowScanas the originals.On the previous revision, which pickled with the standard library's
pickle, a manifest round trip followed by anArrowScanread 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,cloudpicklewrites 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_icebergto 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