Skip to content

[Data] Read Snowflake results in parallel and bulk-load Snowflake writes - #67799

Merged
richardliaw merged 5 commits into
ray-project:masterfrom
goutamvenkat-anyscale:data/snowflake-result-batch-reader-and-bulk-writer
Nov 21, 2026
Merged

richardliaw merged 5 commits into
ray-project:masterfrom
goutamvenkat-anyscale:data/snowflake-result-batch-reader-and-bulk-writer

Conversation

@goutamvenkat-anyscale

@goutamvenkat-anyscale goutamvenkat-anyscale commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Give read_snowflake and Dataset.write_snowflake their own Snowflake datasource and datasink instead of routing through read_sql / write_sql. Reads run the query once and download Snowflake's result batches in parallel, and writes bulk-load with write_pandas instead of row-by-row INSERTs. The implementation is based on the one Anyscale's runtime has used for both APIs.

Before

  • Read: read_snowflake called read_sql. Without shard_keys, it read the whole result in one task, by fetching rows as Python tuples and converting them to Arrow. Passing override_num_blocks > 1 without shard_keys raised ValueError. With shard_keys, it ran a sharding probe query and a COUNT(*) on the driver, then one query per read task, each filtered with MOD(ABS(HASH(keys)), N) = i.
  • Write: write_snowflake computed the schema (executing the dataset), then called write_sql with INSERT INTO <table> (...) VALUES (...), batched 128 rows per executemany. The table had to exist.

After

  • Read: without shard_keys, SnowflakeDatasource runs the query once on the driver and splits the non-empty result batches into contiguous groups, at most one read task per batch. Each task downloads its batches with ResultBatch.to_arrow(), which needs no connection, and retries failed downloads. override_num_blocks works without shard_keys. With shard_keys, the read_sql path is unchanged.
  • Write: SnowflakeDatasink combines each write task's blocks and loads them with one write_pandas(..., auto_create_table=True) call, which stages Parquet files and runs COPY INTO. If the table doesn't exist, it is created.
  • Unchanged: the table name keeps Snowflake's resolution rules, so write_snowflake("my_table") still writes to MY_TABLE. Column names stay quoted (case-sensitive), as the INSERT did.
  • Type change: NUMBER columns with a nonzero scale (for example NUMBER(5, 2)) are now read as float64 instead of decimal128, because that's what the connector's Arrow result batches return. This also resolves the TODO(mowen) in test_snowflake.py about Decimal values.
  • Empty results still produce one empty block with the query's column names, as read_sql did.
flowchart TD
    subgraph Before
        subgraph BA[API]
            B1[read_snowflake] --> B2[read_sql]
            B5[write_snowflake] --> B6[write_sql]
        end
        subgraph BI[IO]
            B2 --> B3[SQLDatasource: 1 task, fetchall to Arrow<br/>or N queries with shard_keys]
            B6 --> B7[SQLDatasink: INSERT, 128 rows per executemany]
        end
    end
    subgraph After
        subgraph AA[API]
            A1[read_snowflake]
            A5[write_snowflake]
        end
        subgraph AI[IO]
            A1 -->|no shard_keys| A3[SnowflakeDatasource: query once,<br/>split result batches across read tasks]
            A1 -->|shard_keys| A2[read_sql, unchanged]
            A5 --> A7[SnowflakeDatasink: write_pandas,<br/>Parquet stage + COPY INTO, auto-create]
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B3,B7 removed
    class A3,A7 added
    class A1,A5 changed
Loading

Subsystems

IO (the behavioral change: new Snowflake datasource and datasink). API: read_snowflake and write_snowflake now route to them.

Not a duplicate

Searched open PRs and issues for "snowflake". None replace the Snowflake read or write path. #62077 (typing cleanup) changes write_snowflake's connection_parameters: str annotation to Dict[str, Any]. This PR makes the identical change to that line, which pyrefly needs, so the two shouldn't conflict there.

Testing

Run on this branch from the test file's directory, with snowflake-connector-python==4.3.0, the version in requirements_compiled:

  • pytest python/ray/data/tests/datasource/test_snowflake_unit.py: 29 passed. These tests mock the connector and cover read-task splitting, running the query once, empty results, download retries, rejecting pickled-object columns, an end-to-end read_snowflake through Ray workers, shard_keys routing to read_sql, table-name resolution and the datasink.
  • pytest python/ray/data/tests/datasource/test_sql.py: 9 passed, 1 skipped
  • pre-commit run on the changed files, including pyrefly for Ray Data: passed
  • Not run: test_snowflake.py, which needs Snowflake credentials and runs only in the postmerge authenticated step. I updated it to compare scaled NUMBER values as floats and added test_write_creates_table.

Written with AI assistance (Claude Code).

🤖 Generated with Claude Code

`read_snowflake` and `Dataset.write_snowflake` went through `read_sql`
and `write_sql`. Without `shard_keys`, reads ran in a single task that
fetched rows as Python tuples, and `override_num_blocks > 1` raised.
With `shard_keys`, every read task re-ran the query. Writes issued
`INSERT ... VALUES` statements 128 rows at a time, and the table had to
exist.

Add `SnowflakeDatasource`, which runs the query once and splits
Snowflake's result batches across read tasks. Each task downloads its
batches as Arrow tables without a connection, and failed downloads are
retried. `shard_keys` keeps the `read_sql` path.

Add `SnowflakeDatasink`, which loads each write task's rows with
`write_pandas` (Parquet staging plus `COPY INTO`) and creates the table
if it doesn't exist. Table names are resolved as Snowflake resolves
them, so unquoted names still map to uppercase tables.

`NUMBER` columns with a nonzero scale are now read as `float64`, which
is what the connector's Arrow batches return, instead of `decimal128`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: goutam <[email protected]>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@goutamvenkat-anyscale
goutamvenkat-anyscale marked this pull request as ready for review November 4, 2026 00:43
@goutamvenkat-anyscale
goutamvenkat-anyscale requested review from a team as code owners November 4, 2026 00:43
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@goutamvenkat-anyscale goutamvenkat-anyscale added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 4, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Snowflake result batches are Arrow tables downloaded from outside the
process. A column with the `ray.data.arrow_pickled_object` extension
type unpickles on access, which can run arbitrary code. Call
`raise_on_pickle_object_columns` on each downloaded batch, both the
driver's sample batch and the batches read tasks download, before
anything uses it. The check runs after the retried download, so a
rejected batch isn't downloaded again.

Add a test that plants an `os.system` payload in the first batch and in
a later batch, and checks that the read raises and the payload never
runs.

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

def _download(result_batch: "ResultBatch") -> pa.Table:
table = call_with_retry(
result_batch.to_arrow, description="download a Snowflake result batch"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Edge case: one TIMESTAMP column can come back as timestamp[ns] from one result batch and timestamp[us] from another (the connector downscales a batch to us when a value is past 2262, e.g. a 9999-12-31 end date).

@goutamvenkat-anyscale goutamvenkat-anyscale Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added test_read_pins_timestamps_to_microseconds (one ns batch, one us batch; asserts both blocks and the reported ReadTask.schema agree), parametrized over both connector paths. Confirmed it fails on both without the fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correction to the above — I went with a hard floor instead of the feature check.

data-test-requirements.txt now asks for snowflake-connector-python>=4.3.0 (was >=3.15.0), and _download calls to_arrow(force_microsecond_precision=True) unconditionally. No lock regeneration needed: every deplocks/ci/*.lock and requirements_compiled_py3.*.txt already resolves to 4.3.0 (4.8.0 on py3.14), so the new floor doesn't move a pin. That drops the feature check and the fallback cast entirely.

One wrinkle the bump alone doesn't cover: that requirements file is test-only, and Ray declares no runtime dependency on the connector, so a user on 4.2.0 would still have hit TypeError: to_arrow() got an unexpected keyword argument 'force_microsecond_precision' from inside a read task. So SnowflakeDatasource.__init__ now checks the installed version and raises a clear ImportError up front, using the same packaging.version.parse + importlib.metadata pattern as catalog.py and read_api.py. test_read_rejects_old_connector covers it.

Net effect is smaller than what I described above, and the failure mode for an old connector is a readable message at construction time rather than a cryptic TypeError mid-read.



def _download(result_batch: "ResultBatch") -> pa.Table:
table = call_with_retry(

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.

There's a built-in retry in ResultBatch.to_arrow() already (the connector retries the download 10 times on any error), right? Does this do something the inner one doesn't?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right. _download() already wraps the GET in for retry in range(MAX_DOWNLOAD_RETRY) with a catch-all except (RetryRequest, Exception), so stacking ours on top meant up to 100 attempts and ~20 min of backoff per batch before the read task failed.

The only thing the outer layer covered that the inner one doesn't is the decompress/parse step after the download (_ensure_decompressed and _load sit outside the connector's loop) — too narrow to justify the multiplier. Removed it, and dropped the test that only existed to exercise it. The comment on _download now records why there's no retry there.

**self._connection_parameters
) as connection, connection.cursor() as cursor:
cursor.execute(self._sql)
result_batches = cursor.get_result_batches() or []

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.

I think this drops support for queries whose results come back as JSON (e.g. with PYTHON_CONNECTOR_QUERY_RESULT_FORMAT=JSON), because to_arrow() doesn't work on a JSONResultBatch: it raises NotSupportedError. fetchall() on master handled both formats.
This seems to be a behavioural difference

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed, and it's a bit broader than the session parameter. JSONResultBatch.to_arrow() is _arrow_fetching_error(), so it raises unconditionally — and cursor.py forces JSON at the statement level whenever CAN_USE_ARROW_RESULT_FORMAT is false, so an install without the Arrow extension lands on the same broken path without anyone setting anything.

Fixed in two parts, since one doesn't cover the other:

  1. _arrow_connection_parameters() merges PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "ARROW" into session_parameters at connect time, so an account-, user- or session-level JSON default no longer decides the format. It merges rather than replaces, so a caller's own session_parameters survive, and it copies rather than mutating what the caller passed.
  2. _check_arrow_result_batches() runs on the driver right after the query. The statement-level override above can't be fixed by asking nicely, so if anything but ArrowResultBatch comes back we raise there with a message pointing at the Arrow-capable build or at shard_keys (which routes through read_sql, the old path) — instead of a bare NotSupportedError surfacing deep inside a read task.

Tests: test_read_asks_for_arrow_result_format (pins the merge and the no-mutation property) and test_read_rejects_json_result_batches. Both fail without the change.

Comment thread python/ray/data/read_api.py Resolved
Datasource:

- Pin the query's result format to Arrow and reject JSON batches. The account,
  user or session can default the format to JSON, and `JSONResultBatch.to_arrow`
  raises `NotSupportedError`, so reads that worked through `read_sql` on master
  broke. `session_parameters` now asks for Arrow, and a driver-side check turns
  the case the connector overrides per statement, when its Arrow extension is
  missing, into an error that says what to do.
- Pin every result batch to microsecond timestamps. The connector picks a unit
  per batch from that batch's data, so one `TIMESTAMP` column could come back as
  `timestamp[ns]` from one batch and `timestamp[us]` from another, leaving read
  tasks emitting blocks that don't share a schema.
- Raise the connector floor to 4.3.0, which added
  `force_microsecond_precision`, and check the installed version up front rather
  than letting a read task fail with a `TypeError`.
- Drop the retry around `ResultBatch.to_arrow`. The connector already retries a
  download 10 times on any error, so this only multiplied attempts and backoff.
- Fix the comment on the zero-row batch filter: `to_arrow` returns an empty
  table, never `None`. The filter stays because `get_read_tasks` divides by the
  first batch's row count.

Datasink:

- Pass `use_logical_type=True` to `write_pandas`. Without it, timezone-aware
  timestamps are written incorrectly, and the connector's own warning doesn't
  fire because it tests `is_datetime64tz_dtype`, which is False for the
  `pd.ArrowDtype` columns an Arrow-backed block produces.
- Hold unquoted identifiers to Snowflake's rule. `write_pandas` quotes every
  part it's given, so a name Snowflake would reject unquoted, like `my-table`,
  became the valid but different `"MY-TABLE"` that `auto_create_table` created.
- Return a `NamedTuple` from `_parse_object_name` instead of a bare tuple.

Both: construct the datasource and datasink with named arguments.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Goutam <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit b0e1866. Configure here.

# `ArrowDtype`. To learn more, read
# https://github.com/snowflakedb/snowflake-connector-python/issues/1687.
use_logical_type=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quoted names break on write

Medium Severity

_resolve_identifier unescapes "" inside quoted names, then write_pandas wraps each part in quotes without re-escaping. Connector 4.3.0, the version this change requires, concatenates '"' + name + '"', so a name like "My ""quoted"" table" becomes invalid SQL ("My "quoted" table") instead of the previous INSERT path, which used the original identifier text. The same gap also lets a quote inside a parsed name terminate the identifier and run extra SQL.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b0e1866. Configure here.

The pre-commit pyrefly hook runs in its own virtualenv, which has neither
snowflake-connector-python nor Ray's other data dependencies. `pyrefly.toml`
lists `snowflake.*` under `ignore-missing-imports`, so locally every Snowflake
type resolved to `Any` and none of these errors appeared. CI runs pyrefly in the
data image, where the connector is installed and the real types apply.

- Annotate the result batches as `ArrowResultBatch`. Only that subclass's
  `to_arrow` takes `force_microsecond_precision`; the base class declares
  `to_arrow(self)`.
- Have `_require_arrow_result_batches` return the narrowed list instead of just
  raising, so the batches keep their type past the check.
- Match `FakeResultBatch` to the class it stands in for: `rowcount` is a plain
  attribute, and `to_arrow`'s first parameter is `connection`.
- Split the `mock_connect` fixture out of `mock_cursor` so a test can assert on
  how `connect` was called without reaching through the patched module.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Goutam <[email protected]>
}


def test_write_uses_logical_type_for_timezone_aware_timestamps():

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.

test_write already asserts use_logical_type=True, and the rest of this test checks how Ray converts blocks to pandas. Can we drop it?

datasource.get_read_tasks(1)


def test_read_runs_query_once(mock_cursor):

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.

test_read_snowflake already asserts the query runs once, and read_snowflake calls get_read_tasks more than once on its way there. Can we drop this one?

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.

Nit: a few test cases repeat another case:

  • test_parse_object_name_rejects_invalid_names: one case per rule is enough: "a.b.c.d", "a..b", '"unterminated', '""', "my-table", "1table". The other seven fail on the same rule as one of these.
  • test_parse_object_name: '"My Table"' is covered by '"my-table"'.
  • test_read_empty_result: None and [] both go through get_result_batches() or [], so one is enough.
  • test_write_snowflake_uses_snowflake_datasink: write_snowflake is one line that builds the datasink, and this test mocks write_datasink to check that line. Can we drop it?

@richardliaw
richardliaw merged commit 71b4006 into ray-project:master Nov 21, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants