Repository navigation
[Data] Read Snowflake results in parallel and bulk-load Snowflake writes - #67799
Conversation
`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]>
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
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" |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 [] |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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:
_arrow_connection_parameters()mergesPYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "ARROW"intosession_parametersat 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 ownsession_parameterssurvive, and it copies rather than mutating what the caller passed._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 butArrowResultBatchcomes back we raise there with a message pointing at the Arrow-capable build or atshard_keys(which routes throughread_sql, the old path) — instead of a bareNotSupportedErrorsurfacing 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.
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]>
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 b0e1866. Configure here.
| # `ArrowDtype`. To learn more, read | ||
| # https://github.com/snowflakedb/snowflake-connector-python/issues/1687. | ||
| use_logical_type=True, | ||
| ) |
There was a problem hiding this comment.
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)
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(): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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:Noneand[]both go throughget_result_batches() or [], so one is enough.test_write_snowflake_uses_snowflake_datasink:write_snowflakeis one line that builds the datasink, and this test mockswrite_datasinkto check that line. Can we drop it?


Summary
Give
read_snowflakeandDataset.write_snowflaketheir own Snowflake datasource and datasink instead of routing throughread_sql/write_sql. Reads run the query once and download Snowflake's result batches in parallel, and writes bulk-load withwrite_pandasinstead of row-by-rowINSERTs. The implementation is based on the one Anyscale's runtime has used for both APIs.Before
read_snowflakecalledread_sql. Withoutshard_keys, it read the whole result in one task, by fetching rows as Python tuples and converting them to Arrow. Passingoverride_num_blocks > 1withoutshard_keysraisedValueError. Withshard_keys, it ran a sharding probe query and aCOUNT(*)on the driver, then one query per read task, each filtered withMOD(ABS(HASH(keys)), N) = i.write_snowflakecomputed the schema (executing the dataset), then calledwrite_sqlwithINSERT INTO <table> (...) VALUES (...), batched 128 rows perexecutemany. The table had to exist.After
shard_keys,SnowflakeDatasourceruns 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 withResultBatch.to_arrow(), which needs no connection, and retries failed downloads.override_num_blocksworks withoutshard_keys. Withshard_keys, theread_sqlpath is unchanged.SnowflakeDatasinkcombines each write task's blocks and loads them with onewrite_pandas(..., auto_create_table=True)call, which stages Parquet files and runsCOPY INTO. If the table doesn't exist, it is created.write_snowflake("my_table")still writes toMY_TABLE. Column names stay quoted (case-sensitive), as theINSERTdid.NUMBERcolumns with a nonzero scale (for exampleNUMBER(5, 2)) are now read asfloat64instead ofdecimal128, because that's what the connector's Arrow result batches return. This also resolves theTODO(mowen)intest_snowflake.pyabout Decimal values.read_sqldid.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 changedSubsystems
IO (the behavioral change: new Snowflake datasource and datasink). API:
read_snowflakeandwrite_snowflakenow 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'sconnection_parameters: strannotation toDict[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 inrequirements_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-endread_snowflakethrough Ray workers,shard_keysrouting toread_sql, table-name resolution and the datasink.pytest python/ray/data/tests/datasource/test_sql.py: 9 passed, 1 skippedpre-commit runon the changed files, including pyrefly for Ray Data: passedtest_snowflake.py, which needs Snowflake credentials and runs only in the postmerge authenticated step. I updated it to compare scaledNUMBERvalues as floats and addedtest_write_creates_table.Written with AI assistance (Claude Code).
🤖 Generated with Claude Code