Skip to content

[Data] write_delta + generic Table write abstraction + Catalog-based credential vending (9-PR stack) - #63337

Closed
abhishekverma-ray wants to merge 10 commits into
ray-project:masterfrom
abhishekverma-ray:data-write-table-staged
Closed

abhishekverma-ray wants to merge 10 commits into
ray-project:masterfrom
abhishekverma-ray:data-write-table-staged

Conversation

@abhishekverma-ray

@abhishekverma-ray abhishekverma-ray commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This stack introduces Dataset.write_delta, refactors the existing Dataset.write_iceberg onto a new generic TableDatasink + TableAdapter abstraction so both formats share the distributed write plumbing, and adds a generic Catalog parameter (with Unity Catalog credential vending) to the Delta read/write APIs. The abstraction is format-agnostic — a future write_hudi (or any table-format datasink) only needs a new TableAdapter, and a future catalog (Iceberg REST, Glue, …) only needs a new Catalog.

The change is split across 9 sequential phases, each self-contained and independently reviewable, so each phase lands as its own PR and is validated before the next starts. UPSERT mode is intentionally out of scope for write_delta (the abstraction supports it — Iceberg uses it via a distributed scan-merge — but DeltaAdapter does not opt in).

Motivation

IcebergDatasink and DeltaDatasink would otherwise each be independent Datasink[T] subclasses re-implementing nearly identical orchestration:

  • Two-phase commit (workers write files, driver commits one transaction).
  • Type-promoted schema unification across worker schemas.
  • Per-mode commit dispatch (APPEND / OVERWRITE / UPSERT).
  • Per-task → driver metadata transport.
  • Orphan-file cleanup on failure.

The reviewer asked us to factor that distributed plumbing out once and let each format ship a small per-format adapter on top. This stack does that, layers write_delta on the resulting framework, and then adds catalog-based credential vending so the read/write APIs can resolve a catalog table identifier to a physical location + short-lived cloud credentials.

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│  Generic framework: ray.data._internal.datasource.table.*            │
│    TableDatasink[FileAction, DeletePredicate]                        │
│        — Ray Data lifecycle, mode validation, schema unification,    │
│          per-mode commit dispatch, orphan routing                    │
│    TableAdapter[FileAction, DeletePredicate]  (ABC)                  │
│        — per-format contract: preflight → write_block →              │
│          reconcile_schema → commit_append / commit_overwrite,        │
│          build_overwrite_predicate, path_for_action, on_failure      │
│    SupportsUpserts  (opt-in Protocol)                                │
│        — upsert_semantics, build_upsert_predicate, commit_upsert;    │
│          framework gates mode="upsert" on isinstance(adapter, …)     │
│    TableWriteTaskResult       — generic per-task result shape        │
│    ParquetFileWriter          — pluggable, NaN-safe partitioned      │
│                                 Parquet writer                       │
│    (sequence diagram embedded in adapter.py + SEQUENCE.md)           │
└──────────────────┬─────────────────────────────────┬────────────────┘
                   ▼                                 ▼
        ┌─────────────────────┐           ┌─────────────────────┐
        │  IcebergAdapter     │           │  DeltaAdapter       │
        │  (PR 2, +Upserts)   │           │  (PRs 3–7)          │
        └─────────────────────┘           └─────────────────────┘

      ray.data.Catalog (ABC)  →  UnityCatalog        (PR 9)
        resolve(identifier) → (physical url, format, vended storage_options)
        consumed by read_delta(catalog=…) / write_delta(catalog=…)

Each adapter owns table loading, per-block file writing, transactional commit, and format-specific delete-predicate construction. The TableAdapter contract is split: the base class covers APPEND + OVERWRITE; UPSERT is an opt-in SupportsUpserts Protocol, so formats that don't support it (Delta) don't carry fictional upsert state. DeletePredicate is a second type parameter so predicate types flow precisely from build_*_predicate to commit_*.

Phased delivery

# Title Scope Risk
PR 1 Introduce TableDatasink + TableAdapter abstraction New _internal/datasource/table/ module: modes.py, result.py, adapter.py (TableAdapter ABC + SupportsUpserts Protocol + ASCII/Mermaid sequence diagram), file_writer.py (sort-based, NaN-safe ParquetFileWriter), table_datasink.py. Framework unit tests (test_table_datasink.py, FakeAdapter) + real-I/O integration tests (test_table_datasink_integration.py, ToyParquetAdapter writing real Parquet). No production callers wired up. Low — purely additive
PR 2 Refactor write_iceberg onto TableDatasink New iceberg_adapter.py (implements TableAdapter + SupportsUpserts; overrides path_for_action → DataFile.file_path; integrates the distributed scan-merge UPSERT). iceberg_datasink.py becomes a thin facade. Existing test_iceberg.py must pass unchanged — the abstraction-correctness proof. Medium
PR 3 write_delta APPEND MVP New _internal/datasource/delta/ module (adapter, datasink, writer, committer, fs, utils, __init__). DeltaAdapter.supported_modes = {APPEND}. Dataset.write_delta public API. Tests for APPEND happy path, schema mismatch, empty datasets, unsupported-mode rejection. Medium
PR 4 OVERWRITE / ERROR / IGNORE modes Extends supported_modes, adds static-partition OVERWRITE to the committer, race-condition handling for concurrent table creation/deletion. Tests per mode + edge cases. Medium
PR 5 Partitioning + dynamic partition overwrite + buffered writes Hive-style partitioning in DeltaFileWriter (NULL __HIVE_DEFAULT_PARTITION__, float-NaN handling). partition_overwrite_mode="dynamic" SQL predicate. target_file_size_bytes buffered writes. Tests for single/multi-column partitions, dynamic vs static overwrite, partition-mismatch rejection. Medium
PR 6 Schema evolution New delta/schema.py with SchemaPolicy("error" | "merge"), validate_and_plan_evolution, reconcile_worker_schemas, evolve_schema. schema_mode="merge" adds columns via DeltaTable.alter.add_columns. Tests for merge evolution, error-mode rejection, type-mismatch rejection. Medium
PR 7 Cloud auto-detection, idempotency, orphan cleanup get_storage_options auto-detects AWS / Azure / GCS credentials. create_app_transaction_id provides commit idempotency on retries via Delta app_transactions. Worker/driver orphan-file cleanup. Pickling robustness. Unified per-format + shared retry config (commit_retry_* kwargs, DataContext.table_write_config). Medium
PR 8 Extract shared Parquet I/O primitives New _internal/datasource/_parquet_io.py (build_uuid_filename, retry-wrapped write_parquet_with_retry); DeltaFileWriter migrates onto them. ParquetDatasink is unchanged (it uses pyarrow.dataset.write_dataset); converging it is a follow-up. Establishes the shared module. Low
PR 9 Catalog abstraction + credential vending for read/write Delta New public ray.data.catalog (Catalog ABC, ResolvedTable, UnityCatalog). read_delta(catalog=…) and write_delta(catalog=…) resolve a catalog table identifier → physical URL + vended cloud credentials (no os.environ mutation / forced ray.init); credentials flow through the existing storage_options → per-worker filesystem path. read_unity_catalog is deprecated (kept working). Includes a worker-filesystem fix so vended credentials reach distributed writes. Strictly additive to the read/write APIs (new optional catalog= only). Medium

UPSERT mode for write_delta is intentionally not part of this delivery. The framework supports UPSERT in the abstract (IcebergAdapter conforms to SupportsUpserts), but DeltaAdapter does not, and ds.write_delta(..., mode="upsert") raises a clean ValueError. A regression test pins that behaviour.

Public API

Iceberg: unchanged (plus an additive catalog= follow-up in PR 10).

New for Delta:

ds.write_delta(
    path,                       # or a catalog table identifier when catalog= is set
    *,
    catalog=None,               # ray.data.Catalog (e.g. UnityCatalog); PR 9
    mode="append" | "overwrite" | "error" | "ignore",
    partition_cols=...,
    filesystem=...,
    schema=...,
    schema_mode="error" | "merge",
    ray_remote_args=...,
    concurrency=...,
    # write_kwargs: storage_options, compression, write_statistics,
    # target_file_size_bytes, partition_overwrite_mode, name, description,
    # configuration, max_commit_retries, commit_retry_* overrides
)

ray.data.read_delta(
    path,                       # or a catalog table identifier when catalog= is set
    *,
    catalog=None,               # PR 9
    storage_options=..., filesystem=..., columns=..., version=..., ...
)

# PR 9 — generic catalog credential vending (replaces read_unity_catalog):
from ray.data import UnityCatalog
ray.data.read_delta("main.sales.orders",
                    catalog=UnityCatalog(url=..., token=..., region="us-west-2"))
ds.write_delta("main.sales.orders", catalog=UnityCatalog(url=..., token=...))

read_unity_catalog continues to work and now emits a DeprecationWarning pointing at the catalog= parameter.

Test plan

  • pytest python/ray/data/tests/datasource/test_table_datasink.py — framework contract (PR 1+).
  • pytest python/ray/data/tests/datasource/test_table_datasink_integration.py — real-I/O ParquetFileWriter + lifecycle (PR 1+).
  • pytest python/ray/data/tests/datasource/test_iceberg.py — full existing Iceberg suite, green from PR 2 (abstraction-correctness proof).
  • pytest python/ray/data/tests/datasource/test_write_delta.py — Delta write suite, growing across PRs 3–7 (grouped by # PR N -- headers).
  • pytest python/ray/data/tests/datasource/test_catalog.py — Catalog resolution + credential translation + read/write wiring (PR 9).
  • pytest python/ray/data/tests/datasource/test_uc_datasource.py — existing Unity Catalog suite stays green (deprecation only).
  • Local round-trip smoke: from_items([...]).write_delta("/tmp/t", mode=...) then read_delta("/tmp/t").take_all() per mode.
  • Cloud round-trip (gated on creds): same on s3://, gs://, abfss://, including catalog=UnityCatalog(...).
  • Type check: mypy python/ray/data/_internal/datasource/table/ python/ray/data/_internal/datasource/delta/ python/ray/data/catalog.py.

Notes for reviewers

  • PR 1 is purely additive. No public API changes, no existing call sites touched. Lowest-risk first merge.
  • PR 2 is the abstraction-correctness proof. Iceberg's existing suite is the regression net; passing it unchanged proves the abstraction is behaviour-preserving.
  • PRs 3–7 grow the same Delta files incrementally. Each phase's contribution is well-scoped to one feature.
  • The TableAdapter contract is split (base + SupportsUpserts Protocol) and parameterized on DeletePredicate; the call sequence is documented in an embedded ASCII diagram (+ SEQUENCE.md Mermaid).
  • PR 9 is strictly additive and non-breaking. read_delta/write_delta gain only an optional catalog=; read_unity_catalog is deprecated but unchanged in behaviour; the worker-filesystem change is a bugfix (vended credentials now reach worker writes) that preserves the existing path for ambient credentials.
  • No feature flag. write_delta is gated behind @PublicAPI(stability="alpha"); Catalog/UnityCatalog are @PublicAPI(stability="alpha") / @DeveloperAPI.

Acknowledgement

This branch was authored with assistance from Anthropic's Claude Opus 4.7 and 4.8 (1M context) — co-credited on each commit's Co-Authored-By: trailer (PRs 1–8 on 4.7, PR 9 on 4.8). The abstraction design, the per-PR scope split, the Lakehouse → Table rename, the contract split into SupportsUpserts, the Catalog design, and the test suites were drafted in collaboration with the model; review, validation, and final acceptance are mine.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a Delta Lake write datasink for Ray Data, implementing an MVP for append-only writes. It establishes a generic TableDatasink framework to unify distributed write logic across different table formats, refactoring the existing Iceberg implementation to utilize this shared infrastructure. Key components include a DeltaAdapter for format-specific operations, a partition-aware ParquetFileWriter, and various utilities for schema reconciliation and filesystem management. Review feedback suggests improving error handling by allowing directory creation exceptions to propagate, optimizing transaction ID lookups with sets for better performance, and ensuring consistent logging during worker-side file cleanup.

Comment on lines +289 to +292
try:
self.filesystem.create_dir(parent, recursive=True)
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Silently catching a broad Exception when creating the parent directory can obscure the root cause of a write failure. If create_dir fails, the subsequent write will also fail, but with a potentially misleading error message. It would be better to let this exception propagate, as the retry mechanism in write_parquet_with_retry should handle transient filesystem errors. PyArrow's create_dir(parent, recursive=True) is idempotent and safe to call multiple times.

                    self.filesystem.create_dir(parent, recursive=True)

Comment on lines +360 to +363
try:
self._filesystem.create_dir(parent, recursive=True)
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Silently catching a broad Exception when creating the parent directory can obscure the root cause of a write failure. If create_dir fails, the subsequent pq.write_table will also fail, but with a potentially misleading error message. It would be better to let this exception propagate. The retry mechanism, if configured, should handle transient filesystem errors, and PyArrow's create_dir(recursive=True) is idempotent.

            self._filesystem.create_dir(parent, recursive=True)

Comment on lines +390 to +394
txns = list(existing.app_transactions or [])
if app_txn:
key = (app_txn.app_id, app_txn.version)
if all((t.app_id, t.version) != key for t in txns):
txns.append(app_txn)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logic to check for an existing transaction before appending can be made more efficient and readable by using a set for the existence check. This is O(1) on average, whereas using all() with a generator is an O(n) scan.

Suggested change
txns = list(existing.app_transactions or [])
if app_txn:
key = (app_txn.app_id, app_txn.version)
if all((t.app_id, t.version) != key for t in txns):
txns.append(app_txn)
txns = list(existing.app_transactions or [])
if app_txn:
existing_keys = {(t.app_id, t.version) for t in txns}
if (app_txn.app_id, app_txn.version) not in existing_keys:
txns.append(app_txn)

Comment on lines +427 to +428
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

For consistency with _cleanup_files_driver, it's better to log a warning here if deleting a file fails instead of silently passing. This will aid in debugging potential filesystem issues on workers.

Suggested change
except Exception:
pass
except Exception as e:
logger.warning("Failed to cleanup file %s on worker: %s", p, e)

@abhishekverma-ray
abhishekverma-ray force-pushed the data-write-table-staged branch 7 times, most recently from 9db159a to 6356c4f Compare May 18, 2026 05:37
@abhishekverma-ray
abhishekverma-ray force-pushed the data-write-table-staged branch 5 times, most recently from 161000a to 2ebea83 Compare June 2, 2026 05:08
@abhishekverma-ray abhishekverma-ray changed the title [Data] Add write_delta and extract TableDatasink abstraction shared with write_iceberg [Data] write_delta + generic Table write abstraction + Catalog-based credential vending (9-PR stack) Jun 15, 2026
@abhishekverma-ray
abhishekverma-ray force-pushed the data-write-table-staged branch 9 times, most recently from 2f85bd6 to 191c7ee Compare June 26, 2026 15:48
abhishekverma-ray and others added 3 commits June 26, 2026 21:29
Adds python/ray/data/_internal/datasource/table/ -- a generic framework
that unifies the distributed write plumbing shared by table-format
datasinks (Iceberg, Delta, future Hudi). Supporting a new format reduces
to writing a new TableAdapter.

Modules:
- modes.py: re-exports SaveMode; adds UpsertSemantics enum.
- result.py: TableWriteTaskResult[FileAction] -- generic per-task result.
- adapter.py: TableAdapter[FileAction] -- the per-format Strategy. The
  11-method contract maps 1-to-1 to the approved design sequence diagram.
- file_writer.py: DataFileWriter protocol + ParquetFileWriter implementation
  (partition encoding / file-action shape pluggable via callbacks).
- table_datasink.py: TableDatasink -- the Template Method. Owns the
  Ray Data lifecycle, mode validation, schema unification, upsert-key
  concatenation, orphan-path collection, and routes every lifecycle step
  to the adapter.

Adds tests/datasource/test_table_datasink.py exercising the framework
in isolation via a FakeAdapter that records every lifecycle call.

No production callers wired up in this PR; existing IcebergDatasink stays
unchanged. Subsequent PRs migrate Iceberg onto the abstraction and add
write_delta on top of it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
…pter

Migrates the existing Iceberg write path onto the table abstraction
introduced in PR 1. No user-facing API changes; Dataset.write_iceberg and
the IcebergDatasink class import path are preserved.

* New: python/ray/data/_internal/datasource/iceberg_adapter.py exposes
  IcebergAdapter, a TableAdapter[DataFile] that owns the Iceberg-
  specific responsibilities -- catalog load, schema evolution via
  union_by_name, per-block Parquet writes via PyIceberg's
  _dataframe_to_data_files, copy-on-write UPSERT via create_match_filter,
  and transactional commit through PyIceberg's Table.transaction.

* Rewritten: iceberg_datasink.py. IcebergDatasink keeps its public
  constructor signature but is now a thin subclass of TableDatasink
  that builds an IcebergAdapter and forwards the lifecycle to the
  framework. Backwards-compat properties (table_identifier, _table,
  _table_metadata) are surfaced so existing tests that introspect the
  instance keep working.

* Removed: IcebergWriteResult dataclass (replaced by
  TableWriteTaskResult).

Iceberg keeps using `pyiceberg._dataframe_to_data_files` for the actual
file writes -- migrating it to ParquetFileWriter is a future PR. The
existing test_iceberg.py suite must pass unchanged; that's the proof
that the abstraction is behaviour-preserving against a mature format.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Adds the minimum-viable Dataset.write_delta supporting only mode="append".
Built directly on top of the TableDatasink abstraction (PR 1).

New files under python/ray/data/_internal/datasource/delta/:
- __init__.py     exports DeltaAdapter, DeltaDatasink.
- adapter.py      DeltaAdapter implementing TableAdapter[AddAction].
                  supported_modes = {APPEND}.
- datasink.py     DeltaDatasink thin facade over TableDatasink.
- writer.py       DeltaFileWriter -- immediate writes only, no
                  partitioning, no target_file_size_bytes buffering.
- committer.py    create_table_with_files and APPEND-only branch of
                  commit_to_existing_table.
- fs.py           Minimal driver/worker filesystem reconstruction.
- utils.py        Core helpers (storage_options pass-through, schema
                  conversion, type-compatibility checks, parquet stats,
                  try_get_deltatable).

New: python/ray/data/dataset.py write_delta(...) public API, mode="append" only.

New: python/ray/data/tests/datasource/test_write_delta.py with APPEND
tests (new path, existing table, explicit schema, empty dataset with
schema, unsupported-mode rejection).

Master's existing test_delta.py (which exercises ray.data.read_delta) is
left untouched.

OVERWRITE / ERROR / IGNORE land in PR 4. Partitioning in PR 5. Schema
evolution in PR 6. Cloud storage in PR 7. UPSERT is intentionally out of
scope for this delivery train.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
abhishekverma-ray and others added 7 commits June 26, 2026 21:29
Extends DeltaAdapter.supported_modes to {APPEND, OVERWRITE, ERROR, IGNORE}.

Adapter changes (delta/adapter.py):
- preflight: rejects ERROR mode against an existing table; sets
  _skip_write when IGNORE + table already exists.
- start_task / write_block / commit: honour _skip_write (IGNORE path).
- commit: dispatches OVERWRITE through commit_to_existing_table; handles
  empty-dataset OVERWRITE (truncate, preserve schema) and the
  concurrent-creation-during-OVERWRITE race.

Committer changes (delta/committer.py):
- commit_to_existing_table now calls table.delete() before the append
  transaction when inputs.mode == "overwrite" (static partition overwrite;
  dynamic variant comes in PR 5).

API changes (dataset.py write_delta):
- Docstring documents the four supported modes.

Tests added (tests/datasource/test_write_delta.py):
- ERROR against existing table -> raises.
- ERROR against new path -> succeeds.
- IGNORE against existing table -> no-op.
- IGNORE against new path -> creates table.
- OVERWRITE replaces data.
- OVERWRITE creates table when missing.
- OVERWRITE with empty Dataset truncates and preserves schema.
- UPSERT is rejected (still out of scope).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
…o write_delta

Extends write_delta to support Hive-style partitioning, the
partition_overwrite_mode knob, and large-file buffered writes via
target_file_size_bytes.

Utils (delta/utils.py):
- build_partition_path with NULL (__HIVE_DEFAULT_PARTITION__) and float
  NaN (literal "NaN") encoding.
- validate_partition_value, validate_partition_column_names,
  validate_partition_columns_in_table, infer_partition_type.
- MAX_PARTITION_PATH_LENGTH, MAX_PARTITION_COLUMNS.

Writer (delta/writer.py):
- partition_cols and target_file_size_bytes constructor args.
- partition_table using pc.unique for 1-col and pc.dictionary_encode
  for multi-col (with manual-iteration fallback for builds without
  struct dict_encode).
- write_partition drops partition columns from the on-disk payload.
- Buffered path: per-partition buffer flushed when its byte total hits
  the target.
- flush(task_idx) drains remaining partition buffers.

Committer (delta/committer.py):
- partition_overwrite_mode="dynamic" branch with a SQL predicate
  (_build_partition_delete_predicate).
- validate_partition_columns_match_existing.
- infer_schema_from_files now appends partition columns.

Adapter (delta/adapter.py):
- Accepts partition_cols and target_file_size_bytes.
- preflight adopts existing partition columns or validates against them.
- write_block validates partition columns in the incoming table.
- finalize_task drains the writer.

API (datasink.py, dataset.py):
- DeltaDatasink accepts partition_cols.
- write_delta documents partition_cols and new write_kwargs
  (target_file_size_bytes, partition_overwrite_mode).

Tests added: single/multi-column partitioning, invalid partition column
names rejected, partition-column mismatch rejected, dynamic vs static
partition overwrite, target_file_size_bytes validation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Adds support for schema_mode="merge", which permits new columns in
incoming data to be added to an existing Delta table via
DeltaTable.alter.add_columns. Default behaviour ("error") is preserved.

New: delta/schema.py
- SchemaPolicy("error" | "merge").
- reconcile_worker_schemas: type-promoted union of worker schemas + the
  existing table.
- validate_and_plan_evolution: detects type mismatches and new columns;
  raises clearly when policy disallows.
- evolve_schema: adds new columns to an existing DeltaTable.
- existing_table_pyarrow_schema: convenience accessor.

Adapter (delta/adapter.py):
- Accepts schema_mode constructor arg (default "error").
- preflight plans schema evolution and applies it on merge mode.
- reconcile_schema folds the existing table's schema into the union.

Facade + API (datasink.py, dataset.py):
- DeltaDatasink accepts schema_mode.
- write_delta documents schema_mode.

Tests added: error-mode rejection of new columns, merge-mode adds new
columns, invalid schema_mode rejected, existing-column type mismatch
rejected.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
…nd orphan cleanup to write_delta

Final polish PR. No new modes; production-readiness only.

Utils (delta/utils.py):
- get_storage_options auto-detects AWS / Azure / GCS credentials
  (boto3, azure-identity, google-auth) for s3:// abfs[s]:// gs:// gcs://
  paths. Caller-supplied options always win.
- create_filesystem_from_storage_options: builds a PyArrow filesystem
  from storage_options for cloud paths.
- normalize_commit_properties: validates and converts commit_properties
  dicts to deltalake's CommitProperties.
- create_app_transaction_id: deterministic Transaction record for
  idempotent commits across retries.

Adapter (delta/adapter.py):
- task_metadata() ships the per-task write_uuid to the driver.
- gather_task_metadata() captures the shared write_uuid for commit.
- _build_commit_kwargs() constructs CommitProperties with deduped
  app_transactions and propagates max_commit_retries.
- on_failure() routes orphan-path cleanup to the driver.
- write_block() / finalize_task() catch exceptions, attach orphan
  paths to the exception, run worker-side cleanup, and re-raise.
- _driver_fs() prefers credential-based filesystem construction via
  create_filesystem_from_storage_options when applicable.

Tests added: storage_options passthrough, app_transactions UUID
construction, normalize_commit_properties validation, adapter pickle
round-trip.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Addresses the review feedback to reuse the Parquet writer between
write_parquet and write_delta.

New: python/ray/data/_internal/datasource/_parquet_io.py
- WRITE_FILE_MAX_ATTEMPTS / WRITE_FILE_RETRY_MAX_BACKOFF_SECONDS
  re-exported from parquet_datasink.
- build_uuid_filename: stable
  ``part-<uuid8>-<task:05d>-<block:05d>-<rand16>.parquet`` builder.
- write_parquet_with_retry: retry-wrapped ``pq.write_table`` with
  size verification.

Updated: delta/writer.py
- _filename delegates to build_uuid_filename.
- _write_parquet delegates to write_parquet_with_retry.
- Drops now-unused imports.

ParquetDatasink is unchanged (it uses the higher-level
pyarrow.dataset.write_dataset API; migrating it onto these primitives is
a separate follow-up). This PR establishes the shared module so future
work has a clean home.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Introduce a generic `Catalog` abstraction so format readers/writers can
resolve a catalog table identifier to a physical location and vend
short-lived cloud credentials, replacing the dedicated `read_unity_catalog`
entry point.

- python/ray/data/catalog.py (new): `Catalog` ABC, `ResolvedTable`, and the
  first concrete `UnityCatalog(url, token, *, credential_provider, region)`.
  `UnityCatalog.resolve` performs the Databricks UC table lookup +
  temporary-table-credentials vending and translates the result into a
  `storage_options` dict (AWS/Azure/GCP) WITHOUT mutating os.environ or
  forcing ray.init (unlike the legacy UnityCatalogConnector).
- read_delta gains an optional keyword-only `catalog=` param. When provided,
  the first positional arg is a catalog table identifier; the catalog
  resolves it to the physical URL + vended storage_options (user-supplied
  storage_options / filesystem take precedence). Strictly additive: calls
  without `catalog=` are unchanged.
- read_unity_catalog now emits a DeprecationWarning. Its internals are
  otherwise untouched (no behavior change); re-pointing it at the catalog
  path is deferred to the parquet/iceberg follow-up.
- Export Catalog, ResolvedTable, UnityCatalog from ray.data.

Tests: python/ray/data/tests/datasource/test_catalog.py — UnityCatalog.resolve
credential translation (AWS/Azure/format-inference/error paths) and
read_delta(catalog=) wiring, all against mocked UC REST responses.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Wire the Catalog abstraction into write_delta and fix the worker-side
filesystem so vended credentials actually reach distributed writes.

- delta/fs.py: worker_filesystem now honours config.storage_options via
  create_filesystem_from_storage_options (mirroring the driver's _driver_fs),
  falling back to from_uri when no usable cloud creds are present. Previously
  the worker dropped storage_options and built a bare from_uri filesystem, so
  vended session-token credentials (e.g. Unity Catalog) never reached worker
  data-file writes — only the driver commit. Non-breaking: the fallback
  preserves the existing path-only behavior for local / ambient-credential
  writes (the helper returns None unless usable cloud keys are present).

- Dataset.write_delta gains an optional keyword-only catalog= param. When
  provided, path is a catalog table identifier; the catalog resolves it with
  operation="READ_WRITE", and the vended storage_options are injected into
  write_kwargs so the existing _FsConfig -> worker_filesystem path carries
  them to workers. User-supplied storage_options take precedence. Strictly
  additive: calls without catalog= are unchanged.

Tests (test_catalog.py): worker_filesystem builds a credentialed S3FileSystem
from storage_options and falls back to LocalFileSystem for local paths;
write_delta(catalog=) resolves with READ_WRITE + injects storage_options;
format-mismatch raises.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the data-write-table-staged branch from 191c7ee to 8923b0d Compare June 26, 2026 16:00
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jul 11, 2026
@richardliaw richardliaw added the data Ray Data-related issues label Jul 23, 2026
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Jul 24, 2026
NightWing1998 added a commit to NightWing1998/ray that referenced this pull request Sep 7, 2026
Azure coverage for `DatabricksUnityCatalog` stops at `resolve()` today: in
`test_catalog.py` the Databricks SDK is mocked, the assertions check that
`AZURE_STORAGE_SAS_TOKEN` lands in `os.environ`, and no byte is ever read. That
leaves the part that matters untested -- whether a vended SAS actually gets a
*reader* to the data, on the driver and in the read tasks.

`test_catalog_azure.py` drives the whole path: the real catalog resolves a
table, its real `_creds_to_env` / `_apply_env` deliver the credential, and
`ray.data.read_delta` fetches real bytes from real Azure blob storage. The
aggregations (`count` / `min` / `max`) are the point -- authenticating is
necessary but not sufficient, the rows have to come back correct.

Delta only. Parquet-on-Azure has a separate problem (pyarrow's Azure filesystem
and its SAS support) that is easier to reason about on its own, so it is left to
a later commit rather than mixed in here.

The table is deliberately not trivial
-------------------------------------

Written as three separate appends with a small `target_file_size`, so it holds
several `_delta_log/*.json` versions and several Parquet data files instead of
one of each. That is what makes the read exercise anything: the driver replays
the whole log to learn which files are current, and the read tasks each
authenticate separately for their own files. A one-file one-version table would
pass with a single credential reaching a single process -- precisely the bug
these tests exist to catch. `test_table_shape_is_non_trivial` asserts the shape
rather than trusting it, so the suite cannot silently decay into the trivial
case.

Two backends behind one factory fixture
---------------------------------------

Both satisfy the same interface -- `catalog()`, `table_identifier()`,
`reader_storage_options()`, `object_names()`, `is_emulator` -- so every test
reads identically against either.

`azurite` (default, no cloud account needed)

  Storage is a local Azurite emulator, the way the rest of the Ray Data suite
  uses `moto` for S3. Only the Databricks *control plane* is faked:
  `_workspace_client` is patched to return a
  `GenerateTemporaryTableCredentialResponse` carrying a genuine,
  signature-checked Azurite container SAS and a genuine `abfss://` URL.
  `_resolve_storage`, `_creds_to_env`, `_apply_env` and `_infer_format` all run
  as shipped. Seeding uses the account key (an admin path a UC client would
  never have); the reads then use nothing but the vended SAS, and Azurite
  validates it -- a no-credential read fails, so the SAS is load-bearing rather
  than decorative.

  Needs `azurite` on PATH (`npm install -g azurite`) and `azure-storage-blob`
  importable; skips cleanly otherwise. Azurite is a Node package, so it stays a
  local prerequisite rather than a Python requirement.

`real` (when the environment is configured)

  A real Azure Databricks workspace over real Azure storage, nothing mocked:

      RAY_TEST_AZURE_DATABRICKS_HOST=https://adb-XXXX.NN.azuredatabricks.net
      RAY_TEST_AZURE_DATABRICKS_TOKEN=dapi...
      RAY_TEST_AZURE_UC_DELTA_TABLE=main.ray_test.ray_azure_delta

  A *managed* table is enough. Credential vending works on Databricks-managed
  storage, which on Azure is ADLS Gen2, so the vended URL is still `abfss://`
  and the credential still an Azure user-delegation SAS -- no storage account,
  access connector, role assignment, storage credential or external location
  needs provisioning.

  `load_azure_uc_test_table.py` provisions the table to match, over the SQL
  Statement Execution API so `databricks-sdk` is the only dependency (no SQL
  driver, no cluster). It writes the rows as several INSERTs to get several log
  versions, then verifies count/min/max/distinct, the `v` formula on every row,
  the log version count and the data-file count. `--verify` alone checks an
  existing table; `--list-warehouses` finds a warehouse id.

  Two gates are easy to miss, and the script's docstring spells them out: the
  principal needs `EXTERNAL USE SCHEMA` on the schema on top of `SELECT`, and
  the metastore needs `external_access_enabled` -- an *account*-level setting
  that the workspace API cannot reach. Without both,
  `generate_temporary_table_credentials` refuses rather than vending a SAS.

Test-isolation note
-------------------

`clean_azure_env` is autouse and restores `os.environ` explicitly rather than
via `monkeypatch`. This is not tidiness: `monkeypatch.delenv` only restores
variables that existed at setup, and `_apply_env` *creates*
`AZURE_STORAGE_SAS_TOKEN` mid-test by writing straight to `os.environ`. Left
behind, it is inherited by the module-scoped Ray cluster when it starts, which
hands every read task a credential for free -- and
`test_vended_credentials_reach_read_tasks` then passes without the code doing
anything. An earlier draft had exactly that false pass. That test now also
asserts up front that a worker sees no SAS *before* `resolve()` runs, so the
harness cannot lie about it again.

Also declares the two test dependencies
---------------------------------------

Both in `data-test-requirements.txt`, alongside `deltalake`, which the same
tests use.

`databricks-sdk==0.103.0` reached the data CI images only transitively, via
`mlflow>=3.0.0` -> `mlflow-skinny` -> `databricks-sdk`, and appears in no
`data-*.lock`. Every Unity Catalog test is behind
`pytest.importorskip("databricks.sdk")`, so if mlflow ever dropped that
dependency all of `test_catalog.py` would silently skip with a green build --
and there are open mlflow bumps in flight. Pinned to the version the transitive
resolve already lands on, so declaring it changes nothing installed today.

`azure-storage-blob` mints the Azurite SAS the emulator backend vends. Left
unpinned, like most of this file; the compiled lock pins it. The Azure *read*
paths do not use it -- pyarrow and deltalake carry their own Azure clients -- so
it is genuinely test-only.

The deplocks are deliberately NOT regenerated here, so this does not yet change
what CI installs; that belongs in its own commit with the lockfile churn. When
they are, expect `azure-core` to move: the base image carries `azure-cli-core`,
which pins `azure-core~=1.35.0` for the autoscaler tests, while
`azure-storage-blob` wants a newer one. No resolve conflict -- the data depset
compiles from `data-requirements.txt` / `data-test-requirements.txt` /
`dl-cpu-requirements.txt` and never sees `test-requirements.txt` -- but the data
image installs the lock over the base with `--no-deps --reinstall`, so
`azure-cli-core`'s pin ends up unsatisfied there. Harmless for the data suite,
which does not import it.

Testing
-------

Two of the four tests fail against current code, by design -- they are written
against the behaviour a correct implementation must have, so that fixing the
code is what turns them green:

- `test_delta_count_min_max_via_catalog` and
  `test_vended_credentials_reach_read_tasks` fail because `_apply_env` folds
  the credential into the cluster `runtime_env` only while Ray is still
  uninitialized. On a running cluster -- every case where a Dataset already
  exists -- the credential stops at the driver. AWS tolerates this because its
  vended `S3FileSystem` pickles into the read tasks; Azure is handed no
  filesystem, so the environment is its only channel. The Delta read gets
  through the driver-side log read and then dies in a worker:

      ray::_fetch_parquet_file_info() ... deltalake/fs/fs_handler.py:38
      OSError: Generic MicrosoftAzure error
        -> Error performing GET http://169.254.169.254/metadata/identity/oauth2/token...

  That address is the Azure instance-metadata endpoint: the worker found no
  credential and fell back to "maybe I am on an Azure VM with an attached
  identity".

- `test_resolve_vends_sas_for_azure_delta` and
  `test_table_shape_is_non_trivial` pass; they guard the harness.

Not run: the real-Azure backend. Credential vending needs the metastore's
account-level `external_access_enabled` flag, which is still off on the
workspace available here.

    pre-commit run --files python/ray/data/tests/datasource/test_catalog_azure.py \
      python/ray/data/tests/datasource/load_azure_uc_test_table.py

No bazel target is added yet; these tests are intentionally not wired into CI
while they are red.

Not a duplicate: `gh pr list --repo ray-project/ray --state open --search
"unity catalog azure"` and `"azurite OR test_catalog_azure OR databricks-sdk"`
turn up no PR adding Azure Unity Catalog coverage. ray-project#63337 (draft, 9-PR stack)
built the catalog credential-vending feature itself; this adds the Azure test
coverage that stack lacks, and does not touch its code.

AI assistance was used to write these tests and to diagnose the failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VyMDS42NTSrLcack13B3im
Signed-off-by: Dhruvil Shah <[email protected]>
NightWing1998 added a commit to NightWing1998/ray that referenced this pull request Sep 7, 2026
Azure coverage for `DatabricksUnityCatalog` stops at `resolve()` today: in
`test_catalog.py` the Databricks SDK is mocked, the assertions check that
`AZURE_STORAGE_SAS_TOKEN` lands in `os.environ`, and no byte is ever read. That
leaves the part that matters untested -- whether a vended SAS actually gets a
*reader* to the data, on the driver and in the read tasks.

`test_catalog_azure.py` drives the whole path: the real catalog resolves a
table, its real `_creds_to_env` / `_apply_env` deliver the credential, and
`ray.data.read_delta` fetches real bytes from real Azure blob storage. The
aggregations (`count` / `min` / `max`) are the point -- authenticating is
necessary but not sufficient, the rows have to come back correct.

Delta only. Parquet-on-Azure has a separate problem (pyarrow's Azure filesystem
and its SAS support) that is easier to reason about on its own, so it is left to
a later commit rather than mixed in here.

The table is deliberately not trivial
-------------------------------------

Written as three separate appends with a small `target_file_size`, so it holds
several `_delta_log/*.json` versions and several Parquet data files instead of
one of each. That is what makes the read exercise anything: the driver replays
the whole log to learn which files are current, and the read tasks each
authenticate separately for their own files. A one-file one-version table would
pass with a single credential reaching a single process -- precisely the bug
these tests exist to catch. `test_table_shape_is_non_trivial` asserts the shape
rather than trusting it, so the suite cannot silently decay into the trivial
case.

Two backends behind one factory fixture
---------------------------------------

Both satisfy the same interface -- `catalog()`, `table_identifier()`,
`reader_storage_options()`, `object_names()`, `is_emulator` -- so every test
reads identically against either.

`azurite` (default, no cloud account needed)

  Storage is a local Azurite emulator, the way the rest of the Ray Data suite
  uses `moto` for S3. Only the Databricks *control plane* is faked:
  `_workspace_client` is patched to return a
  `GenerateTemporaryTableCredentialResponse` carrying a genuine,
  signature-checked Azurite container SAS and a genuine `abfss://` URL.
  `_resolve_storage`, `_creds_to_env`, `_apply_env` and `_infer_format` all run
  as shipped. Seeding uses the account key (an admin path a UC client would
  never have); the reads then use nothing but the vended SAS, and Azurite
  validates it -- a no-credential read fails, so the SAS is load-bearing rather
  than decorative.

  Needs `azurite` on PATH (`npm install -g azurite`) and `azure-storage-blob`
  importable; skips cleanly otherwise. Azurite is a Node package, so it stays a
  local prerequisite rather than a Python requirement.

`real` (when the environment is configured)

  A real Azure Databricks workspace over real Azure storage, nothing mocked:

      RAY_TEST_AZURE_DATABRICKS_HOST=https://adb-XXXX.NN.azuredatabricks.net
      RAY_TEST_AZURE_DATABRICKS_TOKEN=dapi...
      RAY_TEST_AZURE_UC_DELTA_TABLE=main.ray_test.ray_azure_delta

  A *managed* table is enough. Credential vending works on Databricks-managed
  storage, which on Azure is ADLS Gen2, so the vended URL is still `abfss://`
  and the credential still an Azure user-delegation SAS -- no storage account,
  access connector, role assignment, storage credential or external location
  needs provisioning.

  The module docstring carries the DDL, including
  `TBLPROPERTIES ('delta.enableDeletionVectors' = false)`, which is not
  optional: deletion vectors are on by default for Databricks managed tables,
  and deltalake cannot read a table that merely *declares* that reader feature
  through pyarrow datasets -- the path `read_delta` takes -- so the read fails
  before it authenticates.

  Two gates are easy to miss, and the docstring spells them out: the principal
  needs `EXTERNAL USE SCHEMA` on the schema on top of `SELECT`, and the
  metastore needs `external_access_enabled` -- an *account*-level setting that
  the workspace API cannot reach. Without both,
  `generate_temporary_table_credentials` refuses rather than vending a SAS.

Test-isolation note
-------------------

`clean_azure_env` is autouse and restores `os.environ` explicitly rather than
via `monkeypatch`. This is not tidiness: `monkeypatch.delenv` only restores
variables that existed at setup, and `_apply_env` *creates*
`AZURE_STORAGE_SAS_TOKEN` mid-test by writing straight to `os.environ`. Left
behind, it is inherited by the module-scoped Ray cluster when it starts, which
hands every read task a credential for free -- and
`test_vended_credentials_reach_read_tasks` then passes without the code doing
anything. An earlier draft had exactly that false pass. That test now also
asserts up front that a worker sees no SAS *before* `resolve()` runs, so the
harness cannot lie about it again.

Also declares the two test dependencies
---------------------------------------

Both in `data-test-requirements.txt`, alongside `deltalake`, which the same
tests use.

`databricks-sdk==0.103.0` reached the data CI images only transitively, via
`mlflow>=3.0.0` -> `mlflow-skinny` -> `databricks-sdk`, and appears in no
`data-*.lock`. Every Unity Catalog test is behind
`pytest.importorskip("databricks.sdk")`, so if mlflow ever dropped that
dependency all of `test_catalog.py` would silently skip with a green build --
and there are open mlflow bumps in flight. Pinned to the version the transitive
resolve already lands on, so declaring it changes nothing installed today.

`azure-storage-blob` mints the Azurite SAS the emulator backend vends. Left
unpinned, like most of this file; the compiled lock pins it. The Azure *read*
paths do not use it -- pyarrow and deltalake carry their own Azure clients -- so
it is genuinely test-only.

The deplocks are deliberately NOT regenerated here, so this does not yet change
what CI installs; that belongs in its own commit with the lockfile churn. When
they are, expect `azure-core` to move: the base image carries `azure-cli-core`,
which pins `azure-core~=1.35.0` for the autoscaler tests, while
`azure-storage-blob` wants a newer one. No resolve conflict -- the data depset
compiles from `data-requirements.txt` / `data-test-requirements.txt` /
`dl-cpu-requirements.txt` and never sees `test-requirements.txt` -- but the data
image installs the lock over the base with `--no-deps --reinstall`, so
`azure-cli-core`'s pin ends up unsatisfied there. Harmless for the data suite,
which does not import it.

Testing
-------

Two of the four tests fail against current code, by design -- they are written
against the behaviour a correct implementation must have, so that fixing the
code is what turns them green:

- `test_delta_count_min_max_via_catalog` and
  `test_vended_credentials_reach_read_tasks` fail because `_apply_env` folds
  the credential into the cluster `runtime_env` only while Ray is still
  uninitialized. On a running cluster -- every case where a Dataset already
  exists -- the credential stops at the driver. AWS tolerates this because its
  vended `S3FileSystem` pickles into the read tasks; Azure is handed no
  filesystem, so the environment is its only channel. The Delta read gets
  through the driver-side log read and then dies in a worker:

      ray::_fetch_parquet_file_info() ... deltalake/fs/fs_handler.py:38
      OSError: Generic MicrosoftAzure error
        -> Error performing GET http://169.254.169.254/metadata/identity/oauth2/token...

  That address is the Azure instance-metadata endpoint: the worker found no
  credential and fell back to "maybe I am on an Azure VM with an attached
  identity".

- `test_resolve_vends_sas_for_azure_delta` and
  `test_table_shape_is_non_trivial` pass; they guard the harness.

Not run: the real-Azure backend. Credential vending needs the metastore's
account-level `external_access_enabled` flag, which is still off on the
workspace available here.

    pre-commit run --files python/ray/data/tests/datasource/test_catalog_azure.py \
      python/ray/data/tests/datasource/load_azure_uc_test_table.py

No bazel target is added yet; these tests are intentionally not wired into CI
while they are red.

Not a duplicate: `gh pr list --repo ray-project/ray --state open --search
"unity catalog azure"` and `"azurite OR test_catalog_azure OR databricks-sdk"`
turn up no PR adding Azure Unity Catalog coverage. ray-project#63337 (draft, 9-PR stack)
built the catalog credential-vending feature itself; this adds the Azure test
coverage that stack lacks, and does not touch its code.

AI assistance was used to write these tests and to diagnose the failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VyMDS42NTSrLcack13B3im
Signed-off-by: Dhruvil Shah <[email protected]>
NightWing1998 added a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
Azure coverage for `DatabricksUnityCatalog` stops at `resolve()` today: in
`test_catalog.py` the Databricks SDK is mocked, the assertions check that
`AZURE_STORAGE_SAS_TOKEN` lands in `os.environ`, and no byte is ever read. That
leaves the part that matters untested -- whether a vended SAS actually gets a
*reader* to the data, on the driver and in the read tasks.

`test_catalog_azure.py` drives the whole path: the real catalog resolves a
table, its real `_creds_to_env` / `_apply_env` deliver the credential, and
`ray.data.read_delta` fetches real bytes from real Azure blob storage. The
aggregations (`count` / `min` / `max`) are the point -- authenticating is
necessary but not sufficient, the rows have to come back correct.

Delta only. Parquet-on-Azure has a separate problem (pyarrow's Azure filesystem
and its SAS support) that is easier to reason about on its own, so it is left to
a later commit rather than mixed in here.

The table is deliberately not trivial
-------------------------------------

Written as three separate appends with a small `target_file_size`, so it holds
several `_delta_log/*.json` versions and several Parquet data files instead of
one of each. That is what makes the read exercise anything: the driver replays
the whole log to learn which files are current, and the read tasks each
authenticate separately for their own files. A one-file one-version table would
pass with a single credential reaching a single process -- precisely the bug
these tests exist to catch. `test_table_shape_is_non_trivial` asserts the shape
rather than trusting it, so the suite cannot silently decay into the trivial
case.

Two backends behind one factory fixture
---------------------------------------

Both satisfy the same interface -- `catalog()`, `table_identifier()`,
`reader_storage_options()`, `object_names()`, `is_emulator` -- so every test
reads identically against either.

`azurite` (default, no cloud account needed)

  Storage is a local Azurite emulator, the way the rest of the Ray Data suite
  uses `moto` for S3. Only the Databricks *control plane* is faked:
  `_workspace_client` is patched to return a
  `GenerateTemporaryTableCredentialResponse` carrying a genuine,
  signature-checked Azurite container SAS and a genuine `abfss://` URL.
  `_resolve_storage`, `_creds_to_env`, `_apply_env` and `_infer_format` all run
  as shipped. Seeding uses the account key (an admin path a UC client would
  never have); the reads then use nothing but the vended SAS, and Azurite
  validates it -- a no-credential read fails, so the SAS is load-bearing rather
  than decorative.

  Needs `azurite` on PATH (`npm install -g azurite`) and `azure-storage-blob`
  importable; skips cleanly otherwise. Azurite is a Node package, so it stays a
  local prerequisite rather than a Python requirement.

`real` (when the environment is configured)

  A real Azure Databricks workspace over real Azure storage, nothing mocked:

      RAY_TEST_AZURE_DATABRICKS_HOST=https://adb-XXXX.NN.azuredatabricks.net
      RAY_TEST_AZURE_DATABRICKS_TOKEN=dapi...
      RAY_TEST_AZURE_UC_DELTA_TABLE=main.ray_test.ray_azure_delta

  A *managed* table is enough. Credential vending works on Databricks-managed
  storage, which on Azure is ADLS Gen2, so the vended URL is still `abfss://`
  and the credential still an Azure user-delegation SAS -- no storage account,
  access connector, role assignment, storage credential or external location
  needs provisioning.

  `load_azure_uc_test_table.py` provisions the table to match, over the SQL
  Statement Execution API so `databricks-sdk` is the only dependency (no SQL
  driver, no cluster). It writes the rows as several INSERTs to get several log
  versions, then verifies count/min/max/distinct, the `v` formula on every row,
  the log version count and the data-file count. `--verify` alone checks an
  existing table; `--list-warehouses` finds a warehouse id.

  Two gates are easy to miss, and the script's docstring spells them out: the
  principal needs `EXTERNAL USE SCHEMA` on the schema on top of `SELECT`, and
  the metastore needs `external_access_enabled` -- an *account*-level setting
  that the workspace API cannot reach. Without both,
  `generate_temporary_table_credentials` refuses rather than vending a SAS.

Test-isolation note
-------------------

`clean_azure_env` is autouse and restores `os.environ` explicitly rather than
via `monkeypatch`. This is not tidiness: `monkeypatch.delenv` only restores
variables that existed at setup, and `_apply_env` *creates*
`AZURE_STORAGE_SAS_TOKEN` mid-test by writing straight to `os.environ`. Left
behind, it is inherited by the module-scoped Ray cluster when it starts, which
hands every read task a credential for free -- and
`test_vended_credentials_reach_read_tasks` then passes without the code doing
anything. An earlier draft had exactly that false pass. That test now also
asserts up front that a worker sees no SAS *before* `resolve()` runs, so the
harness cannot lie about it again.

Also declares the two test dependencies
---------------------------------------

Both in `data-test-requirements.txt`, alongside `deltalake`, which the same
tests use.

`databricks-sdk==0.103.0` reached the data CI images only transitively, via
`mlflow>=3.0.0` -> `mlflow-skinny` -> `databricks-sdk`, and appears in no
`data-*.lock`. Every Unity Catalog test is behind
`pytest.importorskip("databricks.sdk")`, so if mlflow ever dropped that
dependency all of `test_catalog.py` would silently skip with a green build --
and there are open mlflow bumps in flight. Pinned to the version the transitive
resolve already lands on, so declaring it changes nothing installed today.

`azure-storage-blob` mints the Azurite SAS the emulator backend vends. Left
unpinned, like most of this file; the compiled lock pins it. The Azure *read*
paths do not use it -- pyarrow and deltalake carry their own Azure clients -- so
it is genuinely test-only.

The deplocks are deliberately NOT regenerated here, so this does not yet change
what CI installs; that belongs in its own commit with the lockfile churn. When
they are, expect `azure-core` to move: the base image carries `azure-cli-core`,
which pins `azure-core~=1.35.0` for the autoscaler tests, while
`azure-storage-blob` wants a newer one. No resolve conflict -- the data depset
compiles from `data-requirements.txt` / `data-test-requirements.txt` /
`dl-cpu-requirements.txt` and never sees `test-requirements.txt` -- but the data
image installs the lock over the base with `--no-deps --reinstall`, so
`azure-cli-core`'s pin ends up unsatisfied there. Harmless for the data suite,
which does not import it.

Testing
-------

Two of the four tests fail against current code, by design -- they are written
against the behaviour a correct implementation must have, so that fixing the
code is what turns them green:

- `test_delta_count_min_max_via_catalog` and
  `test_vended_credentials_reach_read_tasks` fail because `_apply_env` folds
  the credential into the cluster `runtime_env` only while Ray is still
  uninitialized. On a running cluster -- every case where a Dataset already
  exists -- the credential stops at the driver. AWS tolerates this because its
  vended `S3FileSystem` pickles into the read tasks; Azure is handed no
  filesystem, so the environment is its only channel. The Delta read gets
  through the driver-side log read and then dies in a worker:

      ray::_fetch_parquet_file_info() ... deltalake/fs/fs_handler.py:38
      OSError: Generic MicrosoftAzure error
        -> Error performing GET http://169.254.169.254/metadata/identity/oauth2/token...

  That address is the Azure instance-metadata endpoint: the worker found no
  credential and fell back to "maybe I am on an Azure VM with an attached
  identity".

- `test_resolve_vends_sas_for_azure_delta` and
  `test_table_shape_is_non_trivial` pass; they guard the harness.

Not run: the real-Azure backend. Credential vending needs the metastore's
account-level `external_access_enabled` flag, which is still off on the
workspace available here.

    pre-commit run --files python/ray/data/tests/datasource/test_catalog_azure.py \
      python/ray/data/tests/datasource/load_azure_uc_test_table.py

No bazel target is added yet; these tests are intentionally not wired into CI
while they are red.

Not a duplicate: `gh pr list --repo ray-project/ray --state open --search
"unity catalog azure"` and `"azurite OR test_catalog_azure OR databricks-sdk"`
turn up no PR adding Azure Unity Catalog coverage. ray-project#63337 (draft, 9-PR stack)
built the catalog credential-vending feature itself; this adds the Azure test
coverage that stack lacks, and does not touch its code.

AI assistance was used to write these tests and to diagnose the failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VyMDS42NTSrLcack13B3im
Signed-off-by: Dhruvil Shah <[email protected]>
richardliaw pushed a commit that referenced this pull request Oct 14, 2026
…sks) (#66146)

## Description

`Dataset.write_iceberg(mode=SaveMode.UPSERT, ...)` aggregated the join
keys of every upserted row on
the driver: each write task returned the key columns of every row it
wrote, `on_write_complete`
concatenated all of them into one table, and the driver then filtered
NULL keys and ran a distinct
over the result. Driver memory therefore grew with the size of the
upsert -- ~185 MiB per million rows
for a two-column key, 1.4 GiB at 8M rows -- and it was paid even when
the coarse filter matched no
file and no rewrite was needed at all.

What the driver actually needs is only the per-column min/max used to
build the coarse range filter.
So:

1. The write tasks fold their block's keys into running per-column
`(min, max)` bounds and return only
those bounds. Rows with a NULL in any join column are left out of the
bounds, because `NULL != NULL`
means they can never match an existing row -- that is where the driver
used to filter them.
2. The driver merges the bounds (min of mins, max of maxes) and builds
the same coarse filter as
before. When the bounds are empty -- every row had a NULL join key --
the commit short-circuits to
a plain append, and when `plan_files()` then finds no candidate file the
keys are never needed.
3. When there *are* candidate files, one task reads the join key columns
back out of the data files
this write just produced and deduplicates them; every rewrite task
shares that single result. The
   driver passes the reference along without ever resolving it.

On step 3: the keys are columns of the dataset that was just written, so
they are already in the new
data files and a projected read gets them back without the driver
touching them. This is a task return
value rather than a `ray.put`, deliberately: `ray.put` objects are owned
by the worker that created
them and are not lineage-reconstructable, so losing that worker after
the write phase would fail the
commit with `ObjectLostError`, whereas a task return value is owned by
the submitter and Ray can
rebuild it by re-running the task. Doing the read inside each rewrite
task instead would turn one
broadcast into (candidate files x new files) reads, hence the single
collect task.

The coarse filter that comes out is identical to before: `pc.min_max`
skips nulls, and the distinct
that used to run on the driver cannot move either bound.

## Related issues

Related to #66145.

This covers steps 1 and 2 of that issue plus the key-broadcast half of
step 3. It deliberately does
not change where the rewrite tasks build their anti-join, which is the
remaining scaling limit
discussed in [my design comment on the
issue](#66145 (comment))
and is why the issue stays open -- see "What this does not fix" below.

Not a duplicate: no issue or PR mentioned the UPSERT key aggregation
before #66145, and no open PR
touches `iceberg_datasink.py`'s upsert path (#62749 adds CREATE mode,
#61753 adds checkpointing,
#63337 is a Delta/write-abstraction stack). #66144 is mine and changes
the OVERWRITE commit path in
the same file; this PR is independent of it -- the two touch different
functions, the branches merge
cleanly and the merged tree passes the Iceberg tests, so they can land
in either order and whichever
is second just needs a rebase.

## Additional information

### Driver memory

Measured with the script from #66145: the Iceberg table stays at 1000
rows and only the upsert dataset
grows. The dataset is generated with `ray.data.range().map_batches()` so
its blocks live in the object
store; what the driver holds is the key aggregation under measurement.
Peak driver RSS delta over the
`write_iceberg` call, sampled every 20ms. Both arms run back to back on
the same machine, `num_cpus=8`.

`overlap` means the existing rows' ids fall inside the upsert range, so
the coarse filter makes the
existing file a rewrite candidate and the keys really are needed; `no
overlap` is the pure-insert case
where they are not.

| upserted rows | before (no overlap) | after | before (overlap) | after
|
|---|---|---|---|---|
| 1,000,000 | 191 MiB | 10 MiB | 207 MiB | 11 MiB |
| 2,000,000 | 368 MiB | 10 MiB | 377 MiB | 11 MiB |
| 4,000,000 | 786 MiB | 11 MiB | 793 MiB | 11 MiB |
| 8,000,000 | 1,457 MiB | 12 MiB | 1,534 MiB | 12 MiB |

Linear before, flat after. Row counts after the write are identical in
every pair (1,001,000 /
2,001,000 / 4,001,000 / 8,001,000 for the insert case, 1M / 2M / 4M / 8M
for the overlap case, where
the upsert replaces the 1000 existing rows). Wall time is not what this
change is about and is within
noise of before (for example 8M: 5.9s -> 5.5s no overlap, 5.5s -> 6.6s
overlap); the failure mode
being removed is a driver OOM, not a slowdown.

### What this does not fix

Memory per rewrite task is unchanged: each rewrite task still builds an
anti-join table over the whole
key set, ~19 MiB per million rows, so a 100M-row upsert would still ask
about 1.9 GiB of each rewrite
task. Fixing that needs the broadcast anti-join replaced by a
distributed join, which is a design
change with its own trade-offs (for a small upsert against a large table
the broadcast is cheaper than
a shuffle, so it likely wants a broadcast-or-shuffle choice rather than
a replacement). That is step 3
of #66145 and I have asked there whether maintainers want it in the same
effort.

### Tests

Two cases added to `TestUpsertScanMerge` in
`python/ray/data/tests/datasource/test_iceberg.py`:

- `test_upsert_write_tasks_do_not_ship_keys_to_the_driver` -- wraps
`on_write_complete` to inspect what
the write tasks actually returned, and asserts none of them carried a
key table, that the bounds
cover the written keys, and that the resulting rows are correct. This is
the regression test for the
  behaviour being changed.
- `test_upsert_row_with_null_join_key_is_inserted` -- a row whose join
key is NULL must be inserted
rather than matched against anything. NULL filtering moved from the
driver into the write tasks, so
this guards that the move did not change the semantics; it passes before
and after by design.

Commands and results:

```
# with master's iceberg_datasink.py, new tests only
pytest python/ray/data/tests/datasource/test_iceberg.py \
  -k "upsert_write_tasks_do_not_ship_keys or upsert_row_with_null_join_key"
  -> 1 failed, 1 passed
     AssertionError: write tasks returned upsert key tables to the driver ([2] rows);
     the driver only needs the per-column bounds

# with this change
pytest python/ray/data/tests/datasource/test_iceberg.py \
  -k "upsert_write_tasks_do_not_ship_keys or upsert_row_with_null_join_key"
  -> 2 passed
pytest python/ray/data/tests/datasource/test_iceberg.py
  -> 85 passed
pre-commit run --files python/ray/data/_internal/datasource/iceberg_datasink.py \
  python/ray/data/tests/datasource/test_iceberg.py
  -> all hooks pass
```

Run on Python 3.12.11, macOS arm64, with the pinned `pyiceberg==0.11.0`
/ `pyarrow==23.0.1`.

### AI assistance

AI assistance was used for this change: the investigation, the
implementation, this description and the
measurements above were produced with Claude Code, and every number
quoted here comes from the runs
listed. I have reviewed every changed line and run the tests locally.

---------

Signed-off-by: Noritaka Sekiyama <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
Co-authored-by: Isaac <[email protected]>
@richardliaw richardliaw closed this Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants