diff --git a/.github/workflows/kernel-e2e.yml b/.github/workflows/kernel-e2e.yml index 8a240a5d8..8488c025e 100644 --- a/.github/workflows/kernel-e2e.yml +++ b/.github/workflows/kernel-e2e.yml @@ -241,6 +241,7 @@ jobs: DATABRICKS_SERVER_HOSTNAME: ${{ secrets.DATABRICKS_HOST }} DATABRICKS_HTTP_PATH: ${{ secrets.TEST_PECO_WAREHOUSE_HTTP_PATH }} DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }} + DATABRICKS_CATALOG: peco steps: - name: Check out connector uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index c31d6927f..4080b06bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ # Unreleased - Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#505. - Speed up `fetchone()`, `fetchmany()` and `fetchall()` by building each result `Row` with fewer Python calls. The rows are unchanged. Large results and many concurrent cursors in one process benefit most. +- Support Volume `PUT`, `GET` and `REMOVE` on the kernel backend (`use_kernel=True`), including `input_stream` uploads. Local paths, with symlinks resolved, must be within `staging_allowed_local_path`. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#520 and #521. # 4.10.0 (2026-11-24) - Upgrade Databricks SQL Kernel to 1.5.0, with lower overhead for buffered fetches and closing drained cursors, and Arrow and Quinn security updates. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 4e91c6597..e2376d86b 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -114,7 +114,7 @@ to change without notice. | Option | Type | Thrift | Kernel | Default Value | Note | | ------------------------------------ | ----------- | :----: | :----: | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `_socket_timeout` | `float` (s) | ✅ | ✅ | `900` (Thrift); `120` (kernel) | Thrift: socket send/recv/connect timeout. Kernel: total HTTP request deadline from connect through response-body completion. A positive value is forwarded; unset or `0` selects the kernel's 120s default. On the kernel path, `0` is neither unlimited nor an immediate timeout. | +| `_socket_timeout` | `float` (s) | ✅ | ✅ | `900` (Thrift); `120` (kernel) | Thrift: socket send/recv/connect timeout. Kernel: total HTTP request deadline from connect through response-body completion. A positive value is forwarded; unset or `0` selects the kernel's 120s default. On the kernel path, `0` is neither unlimited nor an immediate timeout. For a Volume file transfer, the kernel uses it as an idle limit instead. | | `_pool_connections` | `int` | ⚠️ | ❌ | `10` | Number of pools in the shared Python HTTP client. On Thrift this affects auxiliary auth/feature-flag/telemetry traffic, not the separate Thrift query transport. Kernel-owned network traffic does not use this client. | | `_pool_maxsize` | `int` | ⚠️ | ⚠️ | `20` (Python); `100` (kernel when unset) | Max idle connections retained per host. It configures the shared Python client but not the Thrift query transport. With kernel ≥ 1.1.0, a positive value also configures the kernel's Rust HTTP pool. Unset or `0` keeps each client's default. | | `_proxy_auth_method` | `str` | ✅ | ❌ | `None` | `basic` or `negotiate` (Kerberos). Applied to both Thrift query traffic and the shared Python client. It is not forwarded to the kernel's Rust transport. See [`docs/proxy.md`](docs/proxy.md). | @@ -191,7 +191,7 @@ environment. The backends differ for SOCKS proxies: | `use_inline_params` | `bool` \| `"silent"` | ✅ | ✅ | `False` | Render parameters inline (legacy) vs. native bound params (DBR 14.1+). Shared cursor code performs the rendering before dispatch, so both backends honor it identically. | | `ignore_transactions` | `bool` | ✅ | ✅ | `True` | When `True`: `commit()` is a no-op, `rollback()` raises `NotSupportedError`, and setting `autocommit` is a no-op. | | `fetch_autocommit_from_server`| `bool` | ✅ | ✅ | `False` | Query the server (`SET AUTOCOMMIT`) for autocommit state instead of returning the cached value. | -| `staging_allowed_local_path` | `str` \| `List[str]` | ✅ | ❌ | `None` | Local path(s) permitted for Unity Catalog Volume `PUT`/`GET`. **Thrift-only** — the kernel has no Volume API yet. | +| `staging_allowed_local_path` | `str` \| `List[str]` | ✅ | ✅ | `None` | Local path(s) permitted for Unity Catalog Volume `PUT`/`GET`. The kernel also checks resolved symlink targets; see [Volume file paths](#volume-file-paths). | ## Telemetry @@ -228,12 +228,11 @@ are forwarded when supported by the installed kernel binding. `enable_query_result_lz4_compression`. 5. Arrow-native rendering for `_use_arrow_native_decimals` / `_use_arrow_native_timestamps` (complex types **are** forwarded). -6. `staging_allowed_local_path` (Volume `PUT`/`GET`). -7. Retry fine-tuning beyond the four forwarded knobs: `_retry_delay_default`, +6. Retry fine-tuning beyond the four forwarded knobs: `_retry_delay_default`, `_retry_dangerous_codes`, `_respect_server_retry_after_header`, `_retry_max_redirects`, `_enable_v3_retries`. -8. `force_enable_telemetry`. -9. `_pool_connections` and `_proxy_auth_method` do not configure the +7. `force_enable_telemetry`. +8. `_pool_connections` and `_proxy_auth_method` do not configure the kernel-owned network stack. ### Supported on Kernel, missing / ignored on Thrift @@ -263,6 +262,15 @@ are forwarded when supported by the installed kernel binding. `force_enable_telemetry`, and an omitted `enable_telemetry` or circuit-breaker setting uses the kernel's default. +### Volume file paths + +With `use_kernel=True`, SQL `PUT`, `GET` and `REMOVE` run their file transfer +inside `execute()` or `get_async_execution_result()`. `PUT` and `GET` need local +paths, with symlinks resolved, within `staging_allowed_local_path`; `REMOVE` +needs none. `execute(input_stream=stream)` reads the stream before the statement +runs. A `PUT` reads a regular file; pass other data, such as a pipe's content, +as `input_stream`. Cancelling or closing the cursor stops a running transfer. + > All kernel-path behavior reflects the current **early-access** surface and is > subject to change. Generated against connector version `4.5.0`; the source of > truth is `Connection.__init__` (`src/databricks/sql/client.py`) and the diff --git a/KERNEL_REV b/KERNEL_REV index 418c81d3b..c3e3ca999 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f diff --git a/src/databricks/sql/backend/databricks_client.py b/src/databricks/sql/backend/databricks_client.py index 0c22b9e07..406319801 100644 --- a/src/databricks/sql/backend/databricks_client.py +++ b/src/databricks/sql/backend/databricks_client.py @@ -1,7 +1,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import Dict, List, Optional, Any, Union, TYPE_CHECKING +from typing import BinaryIO, Dict, List, Optional, Any, Union, TYPE_CHECKING if TYPE_CHECKING: from databricks.sql.client import Cursor @@ -90,6 +90,7 @@ def execute_command( enforce_embedded_schema_correctness: bool, row_limit: Optional[int] = None, query_tags: Optional[Dict[str, Optional[str]]] = None, + input_stream: Optional[BinaryIO] = None, ) -> Union[ResultSet, None]: """ Executes a SQL command or query within the specified session. @@ -110,6 +111,8 @@ def execute_command( enforce_embedded_schema_correctness: Whether to enforce schema correctness row_limit: Maximum number of rows in the response. query_tags: Optional dictionary of query tags to apply for this query only. + input_stream: The content a `PUT '__input_stream__'` uploads, for a + backend that runs Volume transfers inside execute. Returns: If async_op is False, returns a ResultSet object containing the diff --git a/src/databricks/sql/backend/kernel/_errors.py b/src/databricks/sql/backend/kernel/_errors.py index bcf3f56b1..0fb032c13 100644 --- a/src/databricks/sql/backend/kernel/_errors.py +++ b/src/databricks/sql/backend/kernel/_errors.py @@ -141,7 +141,14 @@ def reraise_kernel_error(exc: "_kernel.KernelError") -> "Error": "operation-id": getattr(exc, "query_id", None), "diagnostic-info": getattr(exc, "diagnostic_info", None), } - new = cls(getattr(exc, "message", str(exc)), context) + message = getattr(exc, "message", str(exc)) + if getattr(exc, "error_code", None) == "VOLUME_STORAGE_HTTP_ERROR": + cls = OperationalError + message = ( + "Staging operation over HTTP was unsuccessful: " + f"{getattr(exc, 'http_status', None)}-{message}" + ) + new = cls(message, context) for attr in ( "code", diff --git a/src/databricks/sql/backend/kernel/client.py b/src/databricks/sql/backend/kernel/client.py index a0e77bbc7..e263e4c72 100644 --- a/src/databricks/sql/backend/kernel/client.py +++ b/src/databricks/sql/backend/kernel/client.py @@ -16,18 +16,18 @@ - ``query_tags`` on execute is not supported (kernel exposes ``statement_conf`` but PyO3 doesn't surface it). -- Volume PUT/GET (staging operations): kernel has no Volume API - yet. Users on Thrift-only paths. """ from __future__ import annotations import inspect import logging +import os import threading import uuid from typing import ( Any, + BinaryIO, Dict, FrozenSet, List, @@ -84,40 +84,49 @@ # per-request skip-and-warn. _KERNEL_MANAGED_HEADERS = frozenset({"authorization", "x-databricks-org-id"}) -# Leading verbs of SQL volume/staging statements. Detected by the -# leading token (case-insensitive) so the kernel backend can fail loud -# on staging ops it can't service — see ``execute_command``. -_STAGING_VERBS = ("PUT", "GET", "REMOVE") +def _staging_paths(paths: object) -> List[str]: + """``staging_allowed_local_path`` as a list. A value that is not a path or + a list of paths allows none, so a PUT or GET fails while a REMOVE still + runs, as on Thrift.""" + if isinstance(paths, (str, os.PathLike)): + paths = [paths] + if isinstance(paths, (list, tuple)) and all( + isinstance(path, (str, os.PathLike)) for path in paths + ): + return [os.fspath(path) for path in paths] + return [] -def _strip_leading_sql_comments(sql: str) -> str: - """Strip leading whitespace and SQL comments (``-- …`` line and - ``/* … */`` block, possibly several) from ``sql``, returning the - remainder. - Needed so staging detection sees the real leading verb: a - comment-prefixed staging op (``-- upload\\nPUT …`` or - ``/* c */ PUT …``, common in ETL scripts) must still be classified - as staging, or it would slip past the guard into the silent-no-op - bug. Block comments do not nest in Databricks SQL, so a simple - scan-to-``*/`` is correct. - """ - i = 0 - n = len(sql) - while i < n: - if sql[i].isspace(): - i += 1 - elif sql.startswith("--", i): - # Line comment: skip to end of line (or string). - nl = sql.find("\n", i) - i = n if nl == -1 else nl + 1 - elif sql.startswith("/*", i): - # Block comment: skip to closing */ (or end if unterminated). - close = sql.find("*/", i + 2) - i = n if close == -1 else close + 2 - else: - break - return sql[i:] +def _read_stream(stream: Optional[BinaryIO]) -> Optional[bytes]: + if stream is None: + return None + data = stream.read() + return data.encode("utf-8") if isinstance(data, str) else data + + +def _volume_error( + exc: BaseException, staging_allowed_local_path: object +) -> Optional[Exception]: + """The exception the Thrift backend raises for the local side of a failed + Volume transfer, or None.""" + if getattr(exc, "error_code", None) == "VOLUME_PATH_NOT_ALLOWED": + if _staging_paths(staging_allowed_local_path): + return ProgrammingError( + "Local file operations are restricted to paths within the configured staging_allowed_local_path" + ) + return ProgrammingError( + "You must provide at least one staging_allowed_local_path when initialising a connection to perform ingestion commands" + ) + os_code = getattr(exc, "local_os_error", None) + if os_code is None: + return None + local_path = getattr(exc, "local_path", None) + if os.name == "nt": + # On Windows the kernel reports a Windows error code, which OSError + # maps to errno itself. + return OSError(0, "Local file operation failed", local_path, os_code) + return OSError(os_code, os.strerror(os_code), local_path) def _is_not_found(exc: BaseException) -> bool: @@ -155,21 +164,6 @@ def _catalog_or_none(value: Optional[str]) -> Optional[str]: return value -def _is_staging_statement(operation: str) -> bool: - """True iff ``operation`` is a volume/staging statement (PUT / GET / - REMOVE). - - Strips leading whitespace + SQL comments first (so a comment- - prefixed staging op is still caught), then matches the leading token - only — so a normal query that merely *contains* the word (e.g. - ``SELECT 'GET' AS x``) isn't misflagged. - """ - stripped = _strip_leading_sql_comments(operation) - # First whitespace-delimited token, uppercased. - verb = stripped.split(None, 1)[0].upper() if stripped.strip() else "" - return verb in _STAGING_VERBS - - class _KernelSessionParameterSupport(NamedTuple): session_type: Any parameters: FrozenSet[str] @@ -643,6 +637,7 @@ def execute_command( enforce_embedded_schema_correctness: bool, row_limit: Optional[int] = None, query_tags: Optional[Dict[str, Optional[str]]] = None, + input_stream: Optional[BinaryIO] = None, ) -> Union["ResultSet", None]: if self._kernel_session is None: raise InterfaceError("Cannot execute_command without an open session.") @@ -655,24 +650,6 @@ def execute_command( # ``_async_statements`` and closed by ``close_command``); the sync # path drops it in finally. ``close_stmt`` is the post-success # decision flag — it stays True on sync, flips to False on async. - # Volume/staging (PUT/GET/REMOVE) is not supported on the kernel - # path: the kernel returns the staging control row as a normal - # result set (``KernelResultSet.is_staging_operation`` is always - # False), so the connector's ``_handle_staging_operation`` never - # fires and NO file is transferred. Rather than silently no-op - # (the Thrift path performs the presigned-URL upload/download), - # fail loud at the call site so ETL scripts don't ingest - # stale/missing data. Detected by the leading SQL verb — the - # only signal available pre-execute, since the kernel exposes no - # staging marker today. - if _is_staging_statement(operation): - raise NotSupportedError( - "Volume / staging operations (PUT / GET / REMOVE) are not " - "supported on the kernel backend (use_kernel=True); the file " - "transfer would silently not happen. Use the Thrift backend " - "for staging operations." - ) - close_stmt = True try: try: @@ -687,6 +664,12 @@ def execute_command( stmt.set_query_tags(query_tags) if parameters: bind_tspark_params(stmt, parameters) + # The kernel then runs the file transfer of a Volume PUT, GET or + # REMOVE inside execute. + stmt.set_volume_options( + _staging_paths(cursor.connection.staging_allowed_local_path), + input_bytes=_read_stream(input_stream), + ) if async_op: async_exec = stmt.submit() command_id = CommandId.from_sea_statement_id( @@ -749,7 +732,10 @@ def execute_command( ) except Exception: pass - raise _wrap_kernel_exception("execute_command", exc) from exc + raise ( + _volume_error(exc, cursor.connection.staging_allowed_local_path) + or _wrap_kernel_exception("execute_command", exc) + ) from exc finally: with self._sync_cancellers_lock: self._sync_cancellers.pop(id(cursor), None) @@ -1031,7 +1017,10 @@ def get_execution_result( if uses_owning_handle: with self._async_handles_lock: self._async_result_stream_started.discard(command_id.guid) - raise _wrap_kernel_exception("get_execution_result", exc) from exc + raise ( + _volume_error(exc, cursor.connection.staging_allowed_local_path) + or _wrap_kernel_exception("get_execution_result", exc) + ) from exc # ``KernelResultSet.__init__`` calls ``arrow_schema()`` which # can raise — map that to PEP 249 too. # diff --git a/src/databricks/sql/backend/kernel/result_set.py b/src/databricks/sql/backend/kernel/result_set.py index 15f78bf5f..629e99625 100644 --- a/src/databricks/sql/backend/kernel/result_set.py +++ b/src/databricks/sql/backend/kernel/result_set.py @@ -100,6 +100,11 @@ def __init__( # stays O(1) instead of walking the deque. self._buffered_count: int = 0 self._exhausted: bool = False + if kernel_handle.is_volume_operation: + # The transfer ran inside execute. Like the Thrift backend, which + # reads the instruction row to run it, return no rows. + self._exhausted = True + self.has_more_rows = False # ----- internal helpers ----- diff --git a/src/databricks/sql/backend/sea/backend.py b/src/databricks/sql/backend/sea/backend.py index fff7daab4..411ccf549 100644 --- a/src/databricks/sql/backend/sea/backend.py +++ b/src/databricks/sql/backend/sea/backend.py @@ -3,7 +3,7 @@ import logging import time import re -from typing import Any, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set +from typing import Any, BinaryIO, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set from databricks.sql.backend.sea.models.base import ( ExternalLink, @@ -482,6 +482,7 @@ def execute_command( enforce_embedded_schema_correctness: bool, row_limit: Optional[int] = None, query_tags: Optional[Dict[str, Optional[str]]] = None, + input_stream: Optional[BinaryIO] = None, ) -> Union[SeaResultSet, None]: """ Execute a SQL command using the SEA backend. diff --git a/src/databricks/sql/backend/thrift_backend.py b/src/databricks/sql/backend/thrift_backend.py index e6ca68d6d..2ba4ac6f4 100644 --- a/src/databricks/sql/backend/thrift_backend.py +++ b/src/databricks/sql/backend/thrift_backend.py @@ -7,7 +7,7 @@ import time import threading import weakref -from typing import Dict, List, Optional, Union, Any, TYPE_CHECKING +from typing import BinaryIO, Dict, List, Optional, Union, Any, TYPE_CHECKING from uuid import UUID from databricks.sql.common.unified_http_client import UnifiedHttpClient @@ -1107,6 +1107,7 @@ def execute_command( enforce_embedded_schema_correctness=False, row_limit: Optional[int] = None, query_tags: Optional[Dict[str, Optional[str]]] = None, + input_stream: Optional[BinaryIO] = None, ) -> Union["ResultSet", None]: thrift_handle = session_id.to_thrift_handle() if not thrift_handle: diff --git a/src/databricks/sql/client.py b/src/databricks/sql/client.py index 15db8f8f9..70f95f274 100755 --- a/src/databricks/sql/client.py +++ b/src/databricks/sql/client.py @@ -378,7 +378,8 @@ def read(self) -> Optional[OAuthToken]: # On Thrift, the timeout in seconds for socket send, recv and connect # operations. On the kernel path, a positive value is the total HTTP # request deadline. Kernel values of None or 0 select its 120-second - # default; 0 is neither unlimited nor an immediate timeout. + # default; 0 is neither unlimited nor an immediate timeout. For a + # Volume file transfer the kernel uses it as an idle limit instead. # _disable_pandas # In case the deserialisation through pandas causes any issues, it can be disabled with # this flag. @@ -1613,6 +1614,7 @@ def execute( enforce_embedded_schema_correctness=enforce_embedded_schema_correctness, row_limit=self.row_limit, query_tags=query_tags, + input_stream=input_stream, ) # Surface the affected-row count for DML (INSERT/UPDATE/DELETE/MERGE) as diff --git a/tests/e2e/test_kernel_backend.py b/tests/e2e/test_kernel_backend.py index 260c49689..d02939a86 100644 --- a/tests/e2e/test_kernel_backend.py +++ b/tests/e2e/test_kernel_backend.py @@ -21,6 +21,7 @@ from __future__ import annotations +from contextlib import contextmanager import hashlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import select @@ -35,11 +36,13 @@ from databricks.sql.backend.types import CommandState from databricks.sql.exc import ( DatabaseError, - NotSupportedError, OperationalError, ServerOperationError, ) +from tests.e2e.common.streaming_put_tests import PySQLStreamingPutTestSuiteMixin +from tests.e2e.common.uc_volume_tests import PySQLUCVolumeTestSuiteMixin + # These tests must run against the REAL databricks-sql-kernel wheel and # must NOT silently pass when it's absent or shadowed. We distinguish # three states explicitly so a misconfigured CI job can't look green: @@ -863,30 +866,6 @@ def test_scientific_notation_decimal_parameter_binds(conn): assert int(cur.fetchall()[0][0]) == 100 -# ── Staging / volume — fail loud, not silent no-op ──────────────── - - -def test_staging_put_raises_not_supported(conn): - """A PUT (volume/staging) statement fails loud on the kernel path - rather than silently no-opping (which would make ETL ingest - stale/missing data). (CUJ-gap audit)""" - with conn.cursor() as cur: - with pytest.raises(NotSupportedError, match="staging"): - cur.execute("PUT '/tmp/x.csv' INTO '/Volumes/main/default/v/x.csv'") - - -def test_comment_prefixed_staging_put_raises_not_supported(conn): - """A comment-prefixed staging op (common in ETL scripts) must also - fail loud — the leading-verb detection strips SQL comments first, so - it can't slip past into the silent-no-op bug (PR #825 review #1).""" - with conn.cursor() as cur: - with pytest.raises(NotSupportedError, match="staging"): - cur.execute( - "-- upload the daily extract\n" - "PUT '/tmp/x.csv' INTO '/Volumes/main/default/v/x.csv'" - ) - - # ── Error fidelity — diagnostic-info reaches .context ───────────── @@ -991,3 +970,14 @@ def cancel_after_delay(): finally: t.join() cur.close() + + +class TestKernelUCVolume(PySQLUCVolumeTestSuiteMixin, PySQLStreamingPutTestSuiteMixin): + @pytest.fixture(autouse=True) + def setup_kernel_connection(self, kernel_conn_params): + self.params = kernel_conn_params + + @contextmanager + def connection(self, extra_params=()): + with sql.connect(**dict(self.params, **dict(extra_params))) as connection: + yield connection diff --git a/tests/unit/test_kernel_client.py b/tests/unit/test_kernel_client.py index ded4a3362..a5f1eee35 100644 --- a/tests/unit/test_kernel_client.py +++ b/tests/unit/test_kernel_client.py @@ -13,10 +13,14 @@ from __future__ import annotations +import errno +import io +import re import sys import threading import types from concurrent.futures import ThreadPoolExecutor +from pathlib import PurePosixPath from typing import Optional from unittest.mock import MagicMock @@ -1074,32 +1078,21 @@ def test_execute_command_forwards_row_limit(row_limit): # --------------------------------------------------------------------------- -# Staging / volume operations — fail loud (not silently no-op) +# Volume operations # --------------------------------------------------------------------------- -@pytest.mark.parametrize( - "operation", - [ - "PUT '/local/f.csv' INTO '/Volumes/c/s/v/f.csv'", - " put '/local/f' into '/Volumes/...'", # leading ws + lowercase - "GET '/Volumes/c/s/v/f' TO '/local/f'", - "REMOVE '/Volumes/c/s/v/f'", - ], -) -def test_staging_operation_raises_not_supported(operation): - """Volume/staging PUT/GET/REMOVE must FAIL LOUD on the kernel path - (the kernel can't perform the presigned-URL transfer; silently - no-opping would make ETL ingest stale/missing data).""" +def _execute_failing(staging_allowed_local_path, error, input_stream=None): + """Run ``execute_command`` whose kernel execute raises ``error``.""" c = _make_client() c._kernel_session = MagicMock() + stmt = c._kernel_session.statement.return_value + stmt.execute.side_effect = error cursor = MagicMock() - cursor.arraysize = 100 - cursor.buffer_size_bytes = 1024 - - with pytest.raises(NotSupportedError, match="staging"): + cursor.connection.staging_allowed_local_path = staging_allowed_local_path + with pytest.raises(Exception) as raised: c.execute_command( - operation=operation, + operation="PUT 'f' INTO '/Volumes/c/s/v/f'", session_id=MagicMock(), max_rows=1, max_bytes=1, @@ -1109,34 +1102,84 @@ def test_staging_operation_raises_not_supported(operation): parameters=[], async_op=False, enforce_embedded_schema_correctness=False, + input_stream=input_stream, ) + return stmt, raised.value @pytest.mark.parametrize( - "operation, is_staging", + "staging_allowed_local_path, input_stream, paths, input_bytes", [ - ("PUT '/f' INTO '/v'", True), - ("get '/v' to '/f'", True), - ("REMOVE '/v'", True), - # Comment-prefixed staging ops MUST still be caught — otherwise - # they slip into the silent-no-op bug this guard exists to close - # (regression: review #1 on PR #825). ETL scripts commonly - # prefix statements with comments. - ("-- upload the file\nPUT '/f' INTO '/v'", True), - ("/* staging */ PUT '/f' INTO '/v'", True), - ("/* c1 */\n -- c2\n get '/v' to '/f'", True), # mixed, multiple - (" \n\t PUT '/f' INTO '/v'", True), # leading whitespace only - ("SELECT 'GET' AS x", False), # word appears but not leading verb - ("SELECT * FROM puts", False), - ("-- PUT in a comment\nSELECT 1", False), # verb only in comment - ("/* PUT */ SELECT 1", False), - ("INSERT INTO t VALUES (1)", False), - ("", False), - ("-- just a comment", False), # comment only, no statement + # With no staging path, a REMOVE still runs, as on Thrift. + (None, None, [], None), + ("/data", io.BytesIO(b"\x00bytes"), ["/data"], b"\x00bytes"), + (["/a", "/b"], io.StringIO("text"), ["/a", "/b"], b"text"), + (PurePosixPath("/data"), None, ["/data"], None), + ((PurePosixPath("/a"), "/b"), None, ["/a", "/b"], None), + # A value that is not a path or a list of paths allows none. + (42, None, [], None), + (["/a", 42], None, [], None), ], ) -def test_is_staging_statement(operation, is_staging): - assert kernel_client._is_staging_statement(operation) is is_staging +def test_execute_sets_the_volume_options( + staging_allowed_local_path, input_stream, paths, input_bytes +): + stmt, _ = _execute_failing( + staging_allowed_local_path, RuntimeError("stop"), input_stream + ) + stmt.set_volume_options.assert_called_once_with(paths, input_bytes=input_bytes) + + +@pytest.mark.parametrize( + "staging_allowed_local_path, attributes, raised_type, message", + [ + ( + None, + {"error_code": "VOLUME_PATH_NOT_ALLOWED"}, + ProgrammingError, + "^You must provide at least one staging_allowed_local_path", + ), + ( + 42, + {"error_code": "VOLUME_PATH_NOT_ALLOWED"}, + ProgrammingError, + "^You must provide at least one staging_allowed_local_path", + ), + ( + "/data", + {"error_code": "VOLUME_PATH_NOT_ALLOWED"}, + ProgrammingError, + "^Local file operations are restricted to paths within", + ), + ( + "/data", + {"local_os_error": errno.ENOENT, "local_path": "/data/missing"}, + FileNotFoundError, + "/data/missing", + ), + ( + "/data", + { + "error_code": "VOLUME_STORAGE_HTTP_ERROR", + "http_status": 404, + "message": "Volume storage request failed: HTTP 404", + }, + OperationalError, + "^Staging operation over HTTP was unsuccessful: 404-Volume storage request failed: HTTP 404$", + ), + ], +) +def test_volume_errors_match_the_thrift_backend( + staging_allowed_local_path, attributes, raised_type, message +): + error = kernel_client._kernel.KernelError("boom") + error.message = "boom" + error.local_os_error = None + for name, value in attributes.items(): + setattr(error, name, value) + _, raised = _execute_failing(staging_allowed_local_path, error) + assert isinstance(raised, raised_type) + assert re.search(message, str(raised)) # --------------------------------------------------------------------------- @@ -1571,6 +1614,25 @@ def test_get_execution_result_owning_handle_failure_can_retry_owning_handle(): c._kernel_session.attach_async_statement.assert_not_called() +def test_get_execution_result_maps_volume_errors_like_execute(): + """An async Volume PUT or GET reports local errors as a sync one does.""" + c = _make_client() + c._kernel_session = MagicMock() + handle = MagicMock() + error = _FakeKernelError() + error.error_code = "VOLUME_PATH_NOT_ALLOWED" + handle.await_result.side_effect = error + cid = CommandId.from_sea_statement_id("async-volume") + c._async_handles[cid.guid] = handle + cursor = MagicMock() + cursor.connection.staging_allowed_local_path = "/data" + + with pytest.raises( + ProgrammingError, match="^Local file operations are restricted to paths within" + ): + c.get_execution_result(cid, cursor=cursor) + + def test_get_execution_result_construction_failure_retains_marker_and_uses_reader(): """If the owning handle's ``await_result()`` succeeds but result-set construction then raises, the ``_async_result_stream_started`` marker @@ -1961,7 +2023,7 @@ def _make_tables_stream() -> MagicMock: schema=schema, ) batches = table.to_batches() - stream = MagicMock() + stream = MagicMock(is_volume_operation=False) stream.arrow_schema.return_value = schema # First call returns the batch; second returns None (exhausted). stream.fetch_next_batch.side_effect = batches + [None] diff --git a/tests/unit/test_kernel_result_set.py b/tests/unit/test_kernel_result_set.py index cfa2d3f2e..16d985e01 100644 --- a/tests/unit/test_kernel_result_set.py +++ b/tests/unit/test_kernel_result_set.py @@ -24,10 +24,11 @@ class _FakeKernelHandle: ``ResultStream``. Emits a configured list of ``RecordBatch``es via ``fetch_next_batch`` and then returns ``None``.""" - def __init__(self, schema: pa.Schema, batches): + def __init__(self, schema: pa.Schema, batches, is_volume_operation=False): self._schema = schema self._batches: Deque[pa.RecordBatch] = deque(batches) self.closed = False + self.is_volume_operation = is_volume_operation def arrow_schema(self) -> pa.Schema: return self._schema @@ -243,3 +244,9 @@ def test_close_skips_kernel_call_when_connection_already_closed(int_schema): # …but local state is still terminal so __del__ is idempotent: assert rs.status == CommandState.CLOSED assert rs.has_been_closed_server_side is True + + +def test_a_volume_result_returns_no_rows(int_schema): + batch = pa.record_batch([pa.array([1])], schema=int_schema) + rs = _make_rs(_FakeKernelHandle(int_schema, [batch], is_volume_operation=True)) + assert rs.fetchall() == []