Repository navigation
[Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader - #67887
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for a null_fallback parameter in Hive partitioning, allowing partition values that represent nulls (such as __HIVE_DEFAULT_PARTITION__) to be parsed as None. It updates ORC and Parquet datasources to preserve this configuration using dataclasses.replace. Additionally, it fixes a pickling regression in ParquetFileReader by replacing an object() sentinel with None for the unset sampled batch size. There are no review comments, so I have no feedback to provide.
0fd4678 to
33b803d
Compare
| #: HIVE partition value that stands for a null value, such as | ||
| #: ``HIVE_DEFAULT_PARTITION``. Path values equal to it parse as ``None``. | ||
| #: Specify `None` to keep every path value as written. | ||
| null_fallback: Optional[str] = None |
There was a problem hiding this comment.
PathPartitionFilter.of has no null_fallback, so a partition_filter still sees the placeholder string while the column is None. For eg., with root/grp=a/0.parquet and root/grp=__HIVE_DEFAULT_PARTITION__/0.parquet:
ds = ray.data.read_parquet(
root,
partitioning=Partitioning("hive", null_fallback=HIVE_DEFAULT_PARTITION),
partition_filter=PathPartitionFilter.of(lambda d: d["grp"] is not None),
)
ds.count()
# 2It shouldve been 1.
There was a problem hiding this comment.
Good catch. Fixed in ddd6ec8: PathPartitionFilter.of now takes null_fallback. With the same value as the read’s Partitioning, the filter function sees None, and your example now counts 1. Added a test.
| @@ -27,6 +27,10 @@ | |||
| PartitionDataType = Type[Union[int, float, str, bool]] | |||
| logger = logging.getLogger(__name__) | |||
|
|
|||
| #: Directory value that Hive, Spark and Delta Lake write for a null partition | |||
| #: value, e.g. ``year=__HIVE_DEFAULT_PARTITION__``. | |||
| HIVE_DEFAULT_PARTITION = "__HIVE_DEFAULT_PARTITION__" | |||
There was a problem hiding this comment.
Should null_fallback default to HIVE_DEFAULT_PARTITION, as in PyArrow? Today Ray doesn't read back its own null partitions:
There was a problem hiding this comment.
Agreed, it’s a gap: write_parquet(partition_cols=...) writes nulls as HIVE_DEFAULT_PARTITION but reads them back as that string. I’d like to keep it opt-in here and flip the default in its own PR. The flip changes what every Hive-partitioned read returns (that string becomes None), so it deserves its own review and a release note. The Delta reader sets it explicitly, so this stack doesn’t depend on the default. I’ll open the follow-up once this lands.
| ({"year": int}, {"year": None, "region": "us"}), | ||
| ], | ||
| ) | ||
| def test_path_partition_parser_hive_null_fallback(field_types, expected): |
There was a problem hiding this comment.
Some test cases don't catch anything the others don't:
test_path_partition_parser_hive_null_fallback: thefield_types=Nonecase; theintcase covers it.test_hive_partitioning_null_fallback_to_pyarrow: theHIVE_DEFAULT_PARTITIONcase; it's PyArrow's default, so it passes without the change.test_read_hive_null_fallback: thefield_names=["grp"]cases pass with thedataclasses.replacefix reverted.test_add_partitions_to_table_null_partition: the two non-null cases run the unchanged branch.test_parquet_file_reader_reads_after_pickling: bothtarget_block_sizevalues fail the same way on master.
Also, row["grp"] or "" in test_read_hive_null_fallback can't tell None from ""; asserting {None, "a"} would.
There was a problem hiding this comment.
Agreed on all of them. I dropped:
- the field_types=None parser case
- the HIVE_DEFAULT_PARTITION case in the to_pyarrow test
- the field_names=["grp"] read cases
- the non-null _add_partitions_to_table cases
- one target_block_size value
The read test now asserts {None, "a"}.
Changes to shared Parquet and partitioning code that the Delta Lake DataSourceV2 reader builds on. Each one stands on its own: - `Partitioning.null_fallback`: an opt-in Hive path value that parses as null, such as the new `HIVE_DEFAULT_PARTITION` constant (`__HIVE_DEFAULT_PARTITION__`, which Hive, Spark and Delta write for a null partition value). Null values skip the partition type cast. The Delta writer uses the constant instead of its own literal. - Null partition values work in partition pruning and in the check of a partition column the file also stores (CSV, JSON). Pruning without a schema types a null like the path's other values (from `field_types`, else string), so `is_in` and `not_in` no longer raise on a null-typed column, and a null partition value matches a file column that is all null. - `ParquetFileReader` marks "batch size not sampled yet" with `None` instead of an `object()` sentinel. A reader pickled before its first read got a copy of the sentinel that no longer compared identical, and passed it to PyArrow as the batch size. Read tasks create their reader from the scanner, so no read path hit this yet. - Move the row-group `OnlineBinPacker` setup out of `ParquetDatasourceV2` into `make_row_group_bin_packer`, for other sources whose listing goes through `FooterFileIndexer`. No behavior change. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
… PathPartitionFilter
- A partition column the CSV/JSON reader or the V1 Parquet reader adds from
a null path value is now typed like the field's other values (from
`field_types`, else string) instead of Arrow `null`. Before, a dataset
whose first file was in the null folder reported the column as `null`.
- `PathPartitionFilter.of` takes `null_fallback`, so the filter function
sees `None` for the same paths the data has nulls for.
- Shared `_null_partition_type` helper, also used by partition pruning.
- Tests: trim cases that didn't catch anything the others don't, assert
`{None, "a"}` instead of `row["grp"] or ""`, and add tests for the typed
column and the filter.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
…mn it stores When a CSV/JSON file stores the partition column and a null path value is checked against it, build the nulls with the file column's type. The `field_types`/string type from the previous commit could not be cast to a `null`-typed column (an all-empty CSV column), so the check raised instead of matching. The `field_types`/string type is now only used for a column the reader adds. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
49f1c8f to
d065d30
Compare
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 d065d30. Configure here.
`_PartitionValueParser`, which the Parquet and ORC V2 readers use for
schema inference, pruning and reads, casts each path value with
`field_types` after its parent `PathPartitionParser` returns. A
`null_fallback` value parses as None, so with `field_types` set the read
raised `TypeError` from `int(None)`. Skip the cast for None, as
`PathPartitionParser` does.
`test_read_hive_null_fallback` now also runs with `field_types={"grp": int}`
for Parquet and ORC, and checks a filter on the partition column.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
ray-project#67887 added opt-in null_fallback for Hive null partitions, which covers the parser, Parquet and the Arrow path. Keep only what it leaves out on the pandas path: a null partition vs the file column in _add_partitions_to_dataframe, and is_in on a null-typed column. Signed-off-by: hzmsh <[email protected]>
) ## Summary Adds the file listing for the Delta Lake DataSourceV2 reader: indexers that list a table version's data files from its transaction log. Second part of the split of #67676. Builds on #67887 (merged). Nothing uses the indexers until #67889 and #67890. The review changes are in the second commit (443b3a1cdb). ## Before No DataSourceV2 listing for Delta. `read_delta` lists files on the driver with `DeltaTable.to_pyarrow_dataset()`. ## After New `_internal/datasource_v2/formats/delta/delta_file_indexer.py`: - `DeltaTableSnapshot`: a picklable reference to one table version (`deltalake.DeltaTable` can't be pickled). Listing tasks reopen the table from it at the version the driver pinned. - `DeltaFileIndexer(_DeltaLogListing, FooterFileIndexer)`: lists the version's `add` actions instead of walking the directory, which also holds removed and uncommitted files, then reads each file's Parquet footer. Listing rows are row-group runs, so predicate pruning, read units and resume work as for Parquet. - `DeltaWholeFileIndexer`: the log-based listing for metadata-only reads. `FooterFileIndexer.as_whole_file_indexer` would walk the directory. - Paths are relative to the table root and URL-decoded exactly once; an absolute path fails with a pointer to the V1 reader. - Partition values come from the log's `add` actions, not from the paths: the Delta protocol doesn't require partition directories, and Delta stores a null and the string `__HIVE_DEFAULT_PARTITION__` in the same one. `partition_values_as_strings` casts them to the table's types and back to strings with Arrow, the form the reader casts back exactly, as it does a value parsed from a path. `DeltaPartitionPruner` prunes files on them, and both indexers add them to each manifest in `__delta_partition_values`, which `OnlineBinPacker` carries to the read tasks. The reader that uses it comes in #67889. - The indexer carries the table's filesystem and the read's shuffle, because the framework passes neither to a metadata-backed source. ```mermaid flowchart LR subgraph IO["Subsystem: IO"] subgraph D["Component: datasource_v2/formats/delta"] S["DeltaTableSnapshot<br/>(uri, pinned version)"] --> L["ListFiles task: _DeltaLogListing<br/>add actions → relative paths, sizes,<br/>partition values (pruned, added to manifests)"] L --> F["FooterFileIndexer<br/>footer reads → row-group runs"] L --> W["DeltaWholeFileIndexer<br/>one row per file"] end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class S,L,F,W added ``` ## Subsystems IO (`_internal/datasource_v2/formats/delta/`). ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author) on the current DSv2 layout. No other open PR reads Delta through DSv2. ## Testing Same env as #67887: - `pytest python/ray/data/tests/unit/datasource_v2/test_delta_file_indexer.py`: 18 passed. Covers what `read_delta` can't reach: absolute paths, partition values from the log (a null and the literal `__HIVE_DEFAULT_PARTITION__` told apart, a file outside partition directories), their string round trip for each type, pruning on them, path pruners, log sizes and the manifest column. Listing through `read_delta` (pinned version, path decoding, shuffle, resume) is tested in #67890's `test_delta_v2.py`. - `pytest python/ray/data/tests/unit/datasource_v2/`: 933 passed; `tests/unit/datasource/` (pickle gate scan): 110 passed. - pre-commit and pyrefly (CI file set) pass. AI assistance was used (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…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 #67887 added opt-in `Partitioning("hive", null_fallback=HIVE_DEFAULT_PARTITION)`, which reads a `__HIVE_DEFAULT_PARTITION__` directory as `None`. With it set, two cases still go wrong when a reader produces pandas blocks, for example `read_json(..., lines=True)`. ## Before 1. Filtering a null partition column with `is_in` raises `ArrowTypeError`. On the pandas path, a null partition column is filled with `None`. When that block is converted to Arrow, the all-`None` column gets type `null`, which `pc.is_in` rejects against a non-null value set: ```python partitioning = Partitioning("hive", null_fallback=HIVE_DEFAULT_PARTITION) ds = ray.data.read_json(path, lines=True, partitioning=partitioning) ds = ds.map_batches(lambda batch: batch, batch_format="pyarrow") ds.filter(expr=col("year").is_in(["1970"])).count() # ArrowTypeError: Array type doesn't match type of values set: null vs string ``` 2. When the file also contains the partition column, `_add_partitions_to_dataframe` casts the partition values `[None, ...]` to the file column's dtype (`column.astype(df[field].dtype)`) before checking for conflicts: - Boolean column with `False`: `astype(bool)` turns `None` into `False`, so the conflict is silently accepted instead of raising `ValueError`. - Integer column: `astype(int)` raises `TypeError` instead of the usual "different from in-data values" `ValueError`. ## After - `_pa_is_in`: a null-typed array is cast to the value set's type before `pc.is_in`. This also fixes `is_in` on any all-`None` pandas column. - `_add_partitions_to_dataframe`: a `None` partition value is not cast; it matches only a column that is all null, the same rule #67887 uses in `_add_partitions_to_table`. ## Testing Run on this branch (b5f742a) and on master (71a71b8), WSL2, PyArrow 23.0.1: | Test target | This branch | master | |---|---|---| | `test_partitioning.py` | 166 passed | 160 passed | | `expressions/test_predicate.py` | 20 passed | 18 passed | | `unit/test_expression_evaluator.py` | 38 passed | 38 passed | | `datasource/test_json.py` | 64 passed | 64 passed | | `datasource/test_csv.py` | 14 passed | 14 passed | | `datasource/test_parquet.py` | 296 passed, 1 failed | 296 passed, 1 failed | - 8 new tests: 4 fail on master (`test_read_json_pandas_null_partition_is_in`, `in_data=[False]`, `in_data=[1]`, and `is_in` with strings on an all-null column), and 4 already pass on master (`in_data=[None]`, `in_data=[True]`, `in_data=[None, True]`, and `is_in` with integers on an all-null column). - The `test_parquet.py` failure is `test_get_parquet_dataset_fs_serialization_fallback`, which fails on master too in my setup. - `pre-commit run --files <changed files>` passed. Related to #67362: with #67887, `null_fallback=HIVE_DEFAULT_PARTITION` reads the null partition as `None`; this PR fixes the pandas path for it. ## AI assistance Co-developed with Claude Code (Claude Opus 5.5): the investigation, the fix, the tests and this description. I reviewed every changed line and ran the test commands above locally. I also used `gemini 4 argon (high)` for additional review and audit. --------- Signed-off-by: hzmsh <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…68282) ## Summary Adds `DeltaDatasourceV2` and `DeltaScanner`, the DataSourceV2 datasource for one version of a Delta Lake table. Third part of the split of #67676. `read_delta` starts using it in #68283. Replaces #67889, which was opened from a fork; earlier review is there. This PR is part of a GitHub stack, so its diff shows only this layer. ## Before No DataSourceV2 datasource for Delta. ## After - `DeltaDatasourceV2(DataSourceWithMetadata)`: the driver pins the version and takes the schema and partition columns from the log. The file list is built from the log in a Ray task, not on the driver; deltalake 1.6 and later load it when the table is opened anyway (`without_files` is ignored there). `_get_file_indexer()` returns the `DeltaFileIndexer` from #67888, and `get_file_partitioner()` the shared row-group bin packer from #67887. #68407 opens the table only once, in a Ray task. - `DeltaScanner(ParquetScanner)`: data files are Parquet, so filter, column and limit pushdown are inherited. Partition columns keep their place in the output; an `include_paths` `path` column comes last, as with the V1 reader. - Partition values come from the log, not the paths (#67888): `DeltaScanner` prunes partitions with `DeltaPartitionPruner`, which the listing applies to each file's values, and reads with `DeltaFileReader`, a `ParquetFileReader` that takes each file's values from the manifest's `__delta_partition_values` column. `ParquetScanner` gets a `reader_class` class attribute so the scanner can swap the reader without copying `create_reader`. - Everything is read through a filesystem rooted at the table directory, as `DeltaTable.to_pyarrow_dataset` does: the caller's, or `deltalake`'s `DeltaStorageHandler` built from `storage_options`. Credentials and `az://` behave as in V1. - Data files are opened with their sizes from the log, so S3 gets no HEAD request per open: - With `deltalake`'s filesystem, `DeltaTableFileSystemHandler` wraps `DeltaStorageHandler`. The listing gives it every file's size before the footer reads, and `DeltaFileReader` gives it each manifest's sizes. It builds the deltalake handler on first use. - With a caller's `SubTreeFileSystem` over S3 (what `read_unity_catalog` passes), `filesystem_for_sized_opens` now unwraps it, as it already did a plain `S3FileSystem`. - `count()` takes each file's row count from the log (`numRecords`), not from its Parquet footer: the whole-file listing that `count()` uses carries the counts in a `__delta_num_records` manifest column, and `DeltaFileReader.read_metadata` reads a footer only for a file whose writer recorded no stats. Tables with deletion vectors, whose counts include deleted rows, never reach this reader. - `delta_datasource_v2_unsupported_reason()` says when a table must stay on the V1 reader: reader features beyond `timestampNtz` (deletion vectors, ...), column mapping, a partition column type whose values don't round-trip through a string (binary, ...), PyArrow scan options, or a table `path` column with `include_paths`. It fails closed. V1 reads some of these tables; it rejects the others (column mapping, deletion vectors) with the same error as before. #68408 replaces this fallback with errors, before #68286 makes V2 the default. - `generated_id_column` rejects Delta reads for now (#68285 adds support). - The pickle gate scan allowlists `delta_datasource_v2.py`: its only match is a schema `.to_arrow()`; data files are read and gated in `ParquetFileReader`. ```mermaid flowchart LR subgraph IO["Subsystem: IO"] subgraph D["Component: datasource_v2/formats/delta"] DS["driver: DeltaDatasourceV2<br/>log schema, pinned version"] --> IX["DeltaFileIndexer (2/11)"] DS --> BP["make_row_group_bin_packer (1/11)"] DS --> SC["DeltaScanner → DeltaFileReader<br/>partition values from the manifest,<br/>table-rooted filesystem"] end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 class DS,SC added ``` ## Subsystems IO (`_internal/datasource_v2/formats/delta/`; `ParquetScanner.reader_class`; `filesystem_for_sized_opens` in `_internal/util.py`). Ripple: logical planning (`bind_generated_id_column.py` rejects Delta scanners). ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author). No other open PR reads Delta through DSv2. ## Testing Same env as #67887: - `pytest python/ray/data/tests/unit/datasource_v2/test_delta_datasource_v2.py`: 20 passed. It covers: - the schema and partitioning from the log, and version pinning; - column order and `path` placement, and unknown-column errors; - pickling the indexer and scanner, and reading through the unpickled reader: each row gets its file's partition values from the log, and every data file opens with its size from the log (fails if the reader doesn't pass the sizes, or if two files' partition values are swapped); - `count()`'s row counts: from the log with no file opened, and from the footers when the log has no counts (with the reader change reverted, the first case opens all 3 files and fails); - every fallback reason, and a real table passing the eligibility check; - the `generated_id_column` rejection. - `pytest python/ray/data/tests/unit/datasource_v2/`: 1546 passed (rerun after the review round in a fresh env with the Nov 18 Ray nightly and CI pins). At the top of the stack (#68287), after the `count()` change: unit 1740 passed, `test_delta.py` and `test_delta_v2.py` 138 passed, 1 skipped. I skipped `test_text_datasource_v2.py`, which master added this week and which needs `snappy`, not installed locally. - `tests/unit/datasource/` (pickle gate scan): 125 passed. - `pytest python/ray/data/tests/test_util.py`: 51 passed, including `filesystem_for_sized_opens` on a `SubTreeFileSystem` over S3. - The S3 request count is tested end to end in #68283. - pre-commit and pyrefly (CI file set) pass. AI assistance was used (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…(opt-in) (#68283) ## Summary Routes `ray.data.read_delta` through the Delta Lake DataSourceV2 reader behind the private, temporary `DataContext._use_delta_datasource_v2` (off by default). Last part of the split of #67676. #68284, #68285, #68330, #68407 and #68408 build on it. #68286 deletes the switch, so `use_datasource_v2` alone decides, as it does for `read_parquet` and `read_orc`. Replaces #67890, which was opened from a fork; earlier review is there. This PR is part of a GitHub stack, so its diff shows only this layer. ## Before `read_delta` opens the whole table on the driver (`DeltaTable.to_pyarrow_dataset()`), builds the full file list there, and reads it through the V1 `ParquetDatasource`, one read task per file. ## After With the switch on (and `use_datasource_v2`, already the default), `read_delta` reads through `DeltaDatasourceV2` (#68282): - The table on the driver is used only for its log metadata (`without_files=True` on deltalake before 1.6; later versions ignore it). - The file list is built in a Ray task from the log at the pinned version (#67888). - Files are split into row-group read units, and DSv2 pushdown and resume apply. - Files are listed in path order, so one version lists its files in one order however its log is checkpointed. `deltalake`'s own order follows the row layout of the latest checkpoint, which the protocol leaves to the writer. - `filesystem=`, `storage_options`, `catalog=` and `include_paths` behave as before. Some reads keep using the V1 reader, with an info log saying why: - Tables that `delta_datasource_v2_unsupported_reason()` rejects. V1 then reads the table that was checked, at the same version. On deltalake 1.6+ it reuses that table rather than loading it again; before 1.6 it reopens it with its file list. - Reads that pass `partition_filters` (added in #67900). The V2 reader doesn't apply them yet and would read every partition, so these reads go to V1 without opening the table for the V2 check, with their own info log. #68330 applies them in V2. `filter(expr)` on partition columns already prunes in V2. Later layers change this before #68286 makes V2 the default: - #68407 opens the table only once, in a Ray task, instead of on the driver and again in the listing. That task also rejects a log that names data files by absolute path (as a shallow clone's does), so `read_delta` fails right away. V1 can't read such tables either. - #68408 replaces the V1 fallback with errors. ### Changes from V1 - An empty table's `schema()` is the schema in the log. V1 returns `None`. - `input_files()` is empty until the read runs, because the files are listed in Ray tasks (as for `read_parquet` on DataSourceV2). - Read tasks hold row-group runs packed by size, not one file each. A large file can be split across tasks, and small files share one. - The log is read in Ray tasks (the listing here; from #68407 also the table open), so worker nodes, not only the driver, need read access to the table's `_delta_log`. Credentials in `storage_options` travel with the tasks. #68286 says so in the `read_delta` docstring. - A data file whose size is missing from the log is still read (its footer read finds the size); only files of size 0 are skipped. - With `preserve_order=True`, rows come back in path order. V1 reads files in `deltalake`'s order (newest commit first for JSON commits), which can change for one version when a checkpoint lays out its rows in another order. - Unchanged: the version is pinned when `read_delta` is called. ```mermaid flowchart TD subgraph Before subgraph BS[Subsystem: IO] subgraph BC["Component: read_delta (read_api.py)"] B1["driver: DeltaTable(...).to_pyarrow_dataset()<br/>(full file list)"] --> B2["V1 ParquetDatasource.from_pyarrow_dataset"] B2 --> B3["Read: one task per file"] end end end subgraph After subgraph AS[Subsystem: IO] subgraph AC["Component: read_delta → DataSourceV2 formats/delta"] A0{"_use_delta_datasource_v2, table supported<br/>and no partition_filters?"} -->|no| A5["V1 path (unchanged)"] A0 -->|yes| A1["driver: DeltaTable (log metadata)<br/>pin version, schema, partition cols"] A1 --> A2["ListFiles task: DeltaFileIndexer<br/>add actions at pinned version, sorted by path, footer reads"] A2 --> A3["OnlineBinPacker: row-group read units"] A3 --> A4["ReadFiles: DeltaScanner / ParquetFileReader"] end end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A0 changed class A1,A2,A3,A4 added ``` ## Subsystems API (`read_api.read_delta`, the private `DataContext._use_delta_datasource_v2`) carries the change; IO for the listing order, the README and the tests. ## Not a duplicate Split out of #67676, which takes over #65142 (tobby168, credited as co-author). richardliaw asked for a restart on the current DSv2 layout. No other open PR reads Delta through DSv2. ## Testing Same env as #67887 (deltalake 1.5.0, pyarrow 23). Each module runs in its own pytest process, as CI runs one `py_test` per file: - `test_delta.py`: 54 passed. `test_delta_v2.py`: 35 passed. `tests/datasource_v2/test_delta_footer_listing.py`: 2 passed. - `test_delta.py` runs under both readers through conftest's `datasource_v2` fixture. Tests that take the V1 path with either reader run once: the `partition_filters` tests (until #68330), the multiple-paths check, `_delta_file_sizes` and `use_datasource_v2 = False`. An empty table's schema from the log is a separate V2-only test. - The no-`get_file_info` check (`test_delta_read_takes_file_sizes_from_the_log`) runs under both readers. Its handler records each call in a file, so calls made inside Ray tasks count too. - What `test_delta_v2.py` checks, V2 only (`datasource_v2` fixture, `ray_start_regular_shared`), through `read_delta` and `Dataset` methods. It tells the readers apart by the read operator's name in `ds.stats()`. - V2 returns the same rows and schema as V1 for partitioned tables (special-character, null, int and date partitions). - Filters on partition and data columns, `columns=`, `include_paths` and a table-rooted `filesystem=`. - Count after overwrite, version pinning at call time, row-group splitting, the read order, a seeded shuffle, and each V1 fallback. - `test_delta_footer_listing.py` builds the indexer as `read_delta` does and lists the table: the row groups a resumed job skips, and those a filter prunes. Footer reads run in Ray actors, so these live in `tests/datasource_v2/`, not `tests/unit/`. - Tests that fail without this layer's fixes: - `test_a_version_reads_its_files_in_one_order` reads a table, rewrites its checkpoint with the rows in reverse order (as the protocol allows), and reads the same version again, through the same Dataset and a new `read_delta`. Without the path sort, the order changes; so does the listing-order check in `test_indexer_and_scanner_survive_worker_serialization`. - `test_snapshot_repr_leaves_out_storage_options` fails when `storage_options` is in the snapshot's `repr`. - `test_partition_filters_fall_back_to_v1` fails without the fallback (the read goes to V2). - `test_skips_only_empty_files` fails with the old size check, which also dropped files of unknown size. - `test_falls_back_to_v1_with_pyarrow_scan_options` appends to the table right after the check, with deltalake reporting 1.5 and 1.6. It checks that V1 reads the checked version and, on 1.6, opens the table once. Both cases fail with the old code, which reopened the latest version. - `test_partition_values_come_from_the_log` reads tables whose paths don't give their partition values: random file prefixes, timestamp partitions with a time zone, and the string `__HIVE_DEFAULT_PARTITION__` next to nulls. It reads them through V2 and matches V1, with and without a filter on the partition column. - `test_delta_read_does_not_unpickle_a_tampered_data_file`: a data file swapped for one with a pickled-object column reads as plain bytes under both readers, and its pickle never runs. The test also writes the swapped file's size into the log, because V2 opens data files with the log's sizes, as Delta readers do. - `test_s3_reads_send_no_head_requests` reads a table on moto S3, through deltalake's filesystem and through a caller's `SubTreeFileSystem` over S3. Using moto's request recorder, it checks that no data file gets a HEAD request. - `tests/unit/datasource_v2/` and `tests/unit/datasource/`: 1521 passed, 225 skipped. `test_write_delta.py`: 105 passed. - Each guard was removed one at a time, and a test failed each time: path decoding, the log-based whole-file indexer, version pinning, projection pinning, the protocol fallback, shuffle, the indexer's own filesystem, schema pinning against tampered files, the path order and the `repr`. - pre-commit and pyrefly (CI file set, with deltalake 1.5 and pyarrow 23 resolved) pass. AI assistance was used (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: tobby168 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>

Summary
Fixes and a small refactor in shared Parquet and partitioning code that the Delta Lake DataSourceV2 reader (#67888, #67889, #67890) builds on. Split out of #67676 so the Parquet/partitioning changes get their own review. Each change stands on its own and none is Delta-specific.
Before
year=__HIVE_DEFAULT_PARTITION__(what Hive, Spark and Delta write for a null value) always read back as the string"__HIVE_DEFAULT_PARTITION__".ParquetFileReaderpickled before its first read passed its "not sized yet"object()sentinel to PyArrow as the batch size (TypeError: an integer is required): the unpickled copy no longer compared identical. Read tasks create their reader from the scanner, so no read path hit this yet.OnlineBinPackersetup lived insideParquetDatasourceV2.After
Partitioninggains an opt-innull_fallbackfield. Withnull_fallback=HIVE_DEFAULT_PARTITION(new constant), that directory value parses as null and skips the partition type cast. DefaultNonekeeps today's behavior.to_pyarrow()passes it topds.HivePartitioning. The Delta writer uses the constant instead of its own literal.field_types, else string). A null-typed column would makeis_in/not_inraiseArrowTypeError.pc.equalof two nulls is null, so this check would reject it.field_types, else string), not Arrownull. A dataset whose first file was in the null folder reported the column asnull.PathPartitionFilter.oftakesnull_fallback, so the filter function seesNonefor the paths the data has nulls for._PartitionValueParser([Data] Fix mixed-root partition filtering in Parquet and ORC V2 #67067) leaves a null value asNoneinstead of casting it withfield_types, which raisedTypeErrorfromint(None).ParquetFileReaderusesNonefor "not sized yet", so a pickled reader reads normally.make_row_group_bin_packer()builds the bin packer for any source whose listing goes throughFooterFileIndexer;ParquetDatasourceV2calls it. No behavior change.Subsystems
IO (
datasource/partitioning.py,datasource/file_based_datasource.py,_internal/datasource_v2/formats/parquet/).Not a duplicate
Split out of #67676 at reviewers' request; no other open PR touches these. The Delta reader that uses them follows in #67888 → #67889 → #67890.
Testing
macOS / Python 3.12, env pinned to the CI lock (pyarrow 23.0.1, pandas 2.3.3, pytest 7.4.4, deltalake 1.5.0), after rebasing onto master with #67067 (its shared
resolve_partitioningalready keepsnull_fallback, so this PR no longer changes the ORC and Parquet V2 copies;test_read_hive_null_fallbackcovers it for both):pytest python/ray/data/tests/test_partitioning.py: 148 passed (test_read_hive_null_fallbackalso runs withfield_types={"grp": int}for Parquet and ORC and filters on the partition; those cases fail without the V2 parser fix), including newnull_fallbacktests: the parser,to_pyarrow(a custom"NULL"value),read_parquet/read_orc, pruning on a null partition (is_in,not_in,==,is_null; with and without a schema andfield_types), the in-file column check (all-null matches; mixed null and non-null raises), the type of an added null column (read_csvand V1read_parquet, string andint), andPathPartitionFilter.of(null_fallback=...). The read, pruning, in-file, column-type and filter tests each fail without their fix. The 12 S3-fixture tests need the moto server (not available locally).pytest python/ray/data/tests/unit/datasource_v2/: 862 passed, includingtest_parquet_file_reader_reads_after_pickling, which failed on master withTypeError: an integer is required.test_read_parquet_v2.py: 148 passed;datasource/test_parquet.py: 268 passed (29 S3-fixture errors, moto not available locally);test_csv.py: 14 passed;test_json.py: 62 passed (2httpserver-fixture errors, not available locally).test_orc.py: 216 passed; the 6test_read_orc_v2_partitioned_scan_optimizationscases fail locally on master too (they assert the source path, which differs in my env).AI assistance was used (Claude Code); every line has been reviewed by the submitter.
🤖 Generated with Claude Code