From 50f48baa09895e4d743fdd63a1b0ea20684395ab Mon Sep 17 00:00:00 2001 From: Dave Borowitz Date: Fri, 20 Nov 2026 10:23:28 -0800 Subject: [PATCH] fix(session): support REST transport for Dataproc control plane --- .github/workflows/integration-tests.yaml | 25 +- README.md | 1 + google/cloud/managed_spark_connect/session.py | 232 ++++++++++--- pyproject.toml | 1 + tests/integration/conftest.py | 41 ++- tests/integration/test_session.py | 47 ++- tests/unit/test_dataproc.py | 112 ++++++ tests/unit/test_integration_conftest.py | 32 ++ tests/unit/test_session.py | 325 ++++++++++++++++++ 9 files changed, 742 insertions(+), 74 deletions(-) diff --git a/.github/workflows/integration-tests.yaml b/.github/workflows/integration-tests.yaml index 323ef5e0..c282acbc 100644 --- a/.github/workflows/integration-tests.yaml +++ b/.github/workflows/integration-tests.yaml @@ -127,7 +127,7 @@ jobs: exit 1 fi echo "pr_head_sha=${PR_HEAD_SHA}" >> "$GITHUB_OUTPUT" - for job in ubuntu-latest macos-latest windows-latest "ubuntu-latest, runtime 4.0"; do + for job in ubuntu-latest macos-latest windows-latest "ubuntu-latest, runtime 4.0" "ubuntu-latest, rest"; do gh api "repos/${GITHUB_REPOSITORY}/statuses/${PR_HEAD_SHA}" \ -f state="pending" \ -f target_url="${RUN_URL}" \ @@ -136,7 +136,7 @@ jobs: done integration-test: - name: Run integration tests (${{ matrix.os }}${{ matrix.runtime != 'default' && format(', runtime {0}', matrix.runtime) || '' }}) + name: Run integration tests (${{ matrix.os }}${{ matrix.runtime != 'default' && format(', runtime {0}', matrix.runtime) || '' }}${{ matrix.transport != 'grpc' && format(', {0}', matrix.transport) || '' }}) # `ControlCheck.dominates` (`ControlChecks.qll`) traverses `needs:`, so # `authorize-gcbrun`'s `BashCommentVsHeadDateCheck` dominates this job's checkout. needs: [authorize-gcbrun] @@ -156,11 +156,21 @@ jobs: # extra's pyspark-client. Other runtimes need their own pyspark, and # their own Python for Python UDFs; they run on one OS only. runtime: ["default"] + # Declare transport as a base axis so the REST include entry overwrites + # an existing key and adds a separate job rather than merging into + # ubuntu-latest. + transport: ["grpc"] include: - os: "ubuntu-latest" runtime: "4.0" + transport: "grpc" python-version: "3.13" pyspark: "pyspark-client~=4.2.0" + - os: "ubuntu-latest" + runtime: "default" + transport: "rest" + api-endpoint: "dataproc.googleapis.com" + pytest-marker: "control_plane" # Run on push to main, manual dispatch, non-Dependabot same-repo pull requests, # or authorized /gcbrun PR comments (`needs.authorize-gcbrun.result == 'success'`). @@ -256,8 +266,15 @@ jobs: MANAGED_SPARK_CONNECT_SUBNET: ${{ vars.GCP_SUBNET || secrets.GCP_SUBNET }} MANAGED_SPARK_CONNECT_AUTH_TYPE: "SERVICE_ACCOUNT" MANAGED_SPARK_CONNECT_TEST_RUNTIME_VERSION: ${{ matrix.runtime != 'default' && matrix.runtime || '' }} + MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT: ${{ matrix.transport != 'grpc' && matrix.transport || '' }} + GOOGLE_CLOUD_DATAPROC_API_ENDPOINT: ${{ matrix.api-endpoint || '' }} + PYTEST_MARKER: ${{ matrix.pytest-marker || '' }} run: | - python -m pytest tests/integration/ -v --tb=short -x + if [[ -n "$PYTEST_MARKER" ]]; then + python -m pytest tests/integration/ -v --tb=short -x -m "$PYTEST_MARKER" + else + python -m pytest tests/integration/ -v --tb=short -x + fi - name: Report /gcbrun commit status if: always() && github.event_name == 'issue_comment' && needs.authorize-gcbrun.outputs.pr_head_sha != '' @@ -266,7 +283,7 @@ jobs: JOB_STATUS: ${{ job.status }} PR_HEAD_SHA: ${{ needs.authorize-gcbrun.outputs.pr_head_sha }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - STATUS_CONTEXT: Integration Tests / Run integration tests (${{ matrix.os }}${{ matrix.runtime != 'default' && format(', runtime {0}', matrix.runtime) || '' }}) + STATUS_CONTEXT: Integration Tests / Run integration tests (${{ matrix.os }}${{ matrix.runtime != 'default' && format(', runtime {0}', matrix.runtime) || '' }}${{ matrix.transport != 'grpc' && format(', {0}', matrix.transport) || '' }}) run: | if [[ "$JOB_STATUS" == "success" ]]; then STATE="success" diff --git a/README.md b/README.md index 3af15e97..a3f32653 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,7 @@ These environment variables change how the client behaves. | `MANAGED_SPARK_CONNECT_SHOW_OPERATION_LINKS` | `true` | Default for `showOperationLinks()`. | | `MANAGED_SPARK_CONNECT_PROGRESS_BAR` | `true` | Default for `showProgressBar()`. | | `MANAGED_SPARK_CONNECT_PROGRESS_BAR_LEAVE` | `false` | Default for `progressBarLeave()`. | +| `MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT` | `grpc` | Transport for Dataproc control-plane calls (`grpc` or `rest`). Pair `rest` with `GOOGLE_CLOUD_DATAPROC_API_ENDPOINT=dataproc.googleapis.com` in environments whose egress allowlists permit `dataproc.googleapis.com` but not regional `*-dataproc.googleapis.com` hostnames. | ### Reusing Named Sessions Across Notebooks diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index b8db7376..ca58fc0f 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -50,7 +50,10 @@ from google.api_core.client_options import ClientOptions from google.api_core.exceptions import ( Aborted, + BadRequest, + Conflict, FailedPrecondition, + Forbidden, InvalidArgument, MethodNotImplemented, NotFound, @@ -348,6 +351,31 @@ def fetch(): PROGRESS_BAR_ENV = "MANAGED_SPARK_CONNECT_PROGRESS_BAR" PROGRESS_BAR_LEAVE_ENV = "MANAGED_SPARK_CONNECT_PROGRESS_BAR_LEAVE" SESSION_START_RETRIES_ENV = "MANAGED_SPARK_CONNECT_SESSION_START_RETRIES" +DATAPROC_TRANSPORT_ENV = "MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT" +_VALID_DATAPROC_TRANSPORTS = ("grpc", "rest") +_REST_ERROR_PREFIX_RE = re.compile( + r"^(?:GET|POST|PUT|PATCH|DELETE)\s+https?://\S+:\s*(.*)$", + re.DOTALL, +) + + +def _resolve_dataproc_transport() -> str: + raw = os.getenv(DATAPROC_TRANSPORT_ENV) + if not raw or not raw.strip(): + return "grpc" + normalized = raw.strip().lower() + if normalized not in _VALID_DATAPROC_TRANSPORTS: + raise ValueError( + f"Invalid {DATAPROC_TRANSPORT_ENV} value '{raw}'; " + "expected 'grpc' or 'rest'." + ) + return normalized + + +def _dataproc_api_endpoint(region: Optional[str]) -> str: + return ( + os.getenv("GOOGLE_CLOUD_DATAPROC_API_ENDPOINT") or "" + ).strip() or f"{region}-dataproc.googleapis.com" def _progress_bar_forced() -> bool: @@ -400,15 +428,22 @@ def _create_session_controller_client( ) -> SessionControllerClient: """Create or return a cached Dataproc SessionControllerClient instance.""" client_cls = dataproc_v1.SessionControllerClient + resolved_transport = _resolve_dataproc_transport() + transport_kwargs: Dict[str, Any] = ( + {"transport": resolved_transport} + if resolved_transport != "grpc" + else {} + ) if ( _get_client_option(client_options, "client_cert_source") is not None or _get_client_option(client_options, "client_encrypted_cert_source") is not None ): - return client_cls(client_options=client_options) + return client_cls(client_options=client_options, **transport_kwargs) scopes = _get_client_option(client_options, "scopes") cache_key = ( client_cls, + resolved_transport, _get_client_option(client_options, "api_endpoint"), _get_client_option(client_options, "quota_project_id"), _get_client_option(client_options, "universe_domain"), @@ -432,11 +467,15 @@ def _create_session_controller_client( client = _CLIENT_CACHE.get(cache_key) if client is None: if has_custom_creds: - client = client_cls(client_options=client_options) + client = client_cls( + client_options=client_options, **transport_kwargs + ) else: creds, _ = get_default_credentials() client = client_cls( - client_options=client_options, credentials=creds + client_options=client_options, + credentials=creds, + **transport_kwargs, ) _CLIENT_CACHE[cache_key] = client return client @@ -497,6 +536,88 @@ def _is_valid_session_id(session_id: str) -> bool: return bool(re.match(pattern, session_id)) +def _api_error_status(exc: BaseException) -> Optional[str]: + """Return the google.rpc.Code status name from a REST error response, if any.""" + resp = getattr(exc, "response", None) + if resp is None or not callable(getattr(resp, "json", None)): + return None + try: + payload = resp.json() + except Exception: + return None + if isinstance(payload, Mapping): + error = payload.get("error") + if isinstance(error, Mapping): + status = error.get("status") + if isinstance(status, str): + return status + return None + + +def _api_error_message(exc: BaseException) -> str: + raw = (getattr(exc, "message", None) or str(exc)).strip() + match = _REST_ERROR_PREFIX_RE.match(raw) + if match: + return match.group(1).strip() + return raw + + +def _looks_like_html(text: str) -> bool: + lower = text.lstrip().lower() + return " bool: + if isinstance(exc, InvalidArgument): + return True + if ( + isinstance(exc, BadRequest) + and getattr(type(exc), "grpc_status_code", None) is None + ): + status = _api_error_status(exc) + return status is None or status == "INVALID_ARGUMENT" + return False + + +def _is_endpoint_http_404(exc: BaseException, raw_msg: str) -> bool: + if isinstance(exc, MethodNotImplemented) and "status: 404" in raw_msg: + return True + if isinstance(exc, NotFound): + resp = getattr(exc, "response", None) + if resp is None: + return _looks_like_html(raw_msg) + headers = getattr(resp, "headers", None) + if not isinstance(headers, Mapping): + # On the gRPC path, from_grpc_error() attaches the grpc.Call as + # response, which has no HTTP headers mapping. + return False + content_type = "" + for key, value in headers.items(): + if isinstance(key, str) and key.lower() == "content-type": + content_type = value + break + return "json" not in str(content_type).lower() + return False + + +def _is_create_session_client_error(exc: BaseException) -> bool: + if isinstance( + exc, (InvalidArgument, PermissionDenied, MethodNotImplemented) + ): + return True + if getattr(type(exc), "grpc_status_code", None) is None: + if isinstance(exc, BadRequest): + status = _api_error_status(exc) + return status is None or status == "INVALID_ARGUMENT" + if isinstance(exc, Forbidden): + status = _api_error_status(exc) + return status is None or status == "PERMISSION_DENIED" + if isinstance(exc, NotFound): + raw_msg = (getattr(exc, "message", None) or str(exc)).strip() + return _is_endpoint_http_404(exc, raw_msg) + return False + + def _extract_api_error_details( exc: BaseException, ) -> Tuple[List[str], List[str]]: @@ -504,10 +625,20 @@ def _extract_api_error_details( reasons: List[str] = [] debug_details: List[str] = [] for item in getattr(exc, "details", None) or (): - reason = getattr(item, "reason", None) + if isinstance(item, Mapping): + reason = item.get("reason") + detail = item.get("detail") + violations = ( + item.get("fieldViolations") + or item.get("field_violations") + or () + ) + else: + reason = getattr(item, "reason", None) + detail = getattr(item, "detail", None) + violations = getattr(item, "field_violations", None) or () if isinstance(reason, str) and reason and reason not in reasons: reasons.append(reason) - detail = getattr(item, "detail", None) if ( isinstance(detail, str) and detail @@ -515,9 +646,13 @@ def _extract_api_error_details( and detail not in debug_details ): debug_details.append(detail) - for violation in getattr(item, "field_violations", None) or (): - field = getattr(violation, "field", "") - desc = getattr(violation, "description", "") + for violation in violations: + if isinstance(violation, Mapping): + field = violation.get("field", "") + desc = violation.get("description", "") + else: + field = getattr(violation, "field", "") + desc = getattr(violation, "description", "") if desc: entry = f"{field}: {desc}" if field else desc if entry not in debug_details: @@ -535,7 +670,7 @@ def _format_create_session_error( ) -> str: prefix = "Error while creating Managed Spark Session" raw_msg = (getattr(exc, "message", None) or str(exc)).strip() - if isinstance(exc, MethodNotImplemented) and "status: 404" in raw_msg: + if _is_endpoint_http_404(exc, raw_msg): default_endpoint = ( f"{region}-dataproc.googleapis.com" if region else None ) @@ -549,12 +684,18 @@ def _format_create_session_error( ) endpoint_desc = f" '{api_endpoint}'" if api_endpoint else "" region_desc = f" (location '{region}')" if region else "" + detail = _api_error_message(exc) + if not detail or _looks_like_html(detail): + return ( + f"{prefix}: Endpoint{endpoint_desc}{region_desc} " + "returned HTTP 404." + ) return ( f"{prefix}: Endpoint{endpoint_desc}{region_desc} " - f"returned HTTP 404: {raw_msg}" + f"returned HTTP 404: {detail}" ) - base_msg = raw_msg + base_msg = _api_error_message(exc) reasons, debug_details = _extract_api_error_details(exc) extra_parts: List[str] = [] @@ -576,8 +717,9 @@ def _format_create_session_error( if note not in base_msg: extra_parts.append(note) + is_invalid_arg = _is_invalid_argument_error(exc) if ( - isinstance(exc, InvalidArgument) + is_invalid_arg and session_template and not _session_templates.is_valid_session_template_ref( session_template @@ -593,7 +735,7 @@ def _format_create_session_error( ) base_msg_lower = base_msg.lower() - if isinstance(exc, InvalidArgument) and ( + if is_invalid_arg and ( "subnetwork must be specified" in base_msg_lower or "specify a subnetwork" in base_msg_lower ): @@ -603,7 +745,7 @@ def _format_create_session_error( " .runtimeProfile('')." ) elif ( - isinstance(exc, InvalidArgument) + is_invalid_arg and "stack type, which is not supported" in base_msg_lower ): extra_parts.append( @@ -611,7 +753,7 @@ def _format_create_session_error( " .subnetwork('') or MANAGED_SPARK_CONNECT_SUBNET." ) - if isinstance(exc, InvalidArgument) and runtime_override_note: + if is_invalid_arg and runtime_override_note: extra_parts.append(runtime_override_note) if base_msg and extra_parts and base_msg[-1] not in ".!?:;": @@ -705,10 +847,7 @@ def __init__(self): self._project_id = os.getenv("GOOGLE_CLOUD_PROJECT") self._region = os.getenv("GOOGLE_CLOUD_REGION") self._client_options = ClientOptions( - api_endpoint=os.getenv( - "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", - f"{self._region}-dataproc.googleapis.com", - ) + api_endpoint=_dataproc_api_endpoint(self._region) ) self._session_controller_client: Optional[ SessionControllerClient @@ -779,10 +918,14 @@ def session_template_controller_client(self): ) if self._session_template_controller_client is None: + resolved_transport = _resolve_dataproc_transport() + kwargs: Dict[str, Any] = { + "client_options": self._client_options + } + if resolved_transport != "grpc": + kwargs["transport"] = resolved_transport self._session_template_controller_client = ( - SessionTemplateControllerClient( - client_options=self._client_options - ) + SessionTemplateControllerClient(**kwargs) ) return self._session_template_controller_client @@ -792,9 +935,8 @@ def projectId(self, project_id): def location(self, location): self._region = location - self._client_options.api_endpoint = os.getenv( - "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", - f"{self._region}-dataproc.googleapis.com", + self._client_options.api_endpoint = _dataproc_api_endpoint( + self._region ) return self @@ -1157,23 +1299,28 @@ def create_session_pbar(): f"Exception while writing active session to file {file_path}, {e}" ) except ( - InvalidArgument, - PermissionDenied, + BadRequest, + Forbidden, MethodNotImplemented, + NotFound, ) as e: ManagedSparkSession._active_s8s_session_id = None ManagedSparkSession._active_session_uses_custom_id = False - raise ManagedSparkConnectException( - _format_create_session_error( - e, - self._project_id, - self._region, - _get_client_option( - self._client_options, "api_endpoint" - ), - session_config.session_template, - runtime_resolution.create_error_note(), - ) + if _is_create_session_client_error(e): + raise ManagedSparkConnectException( + _format_create_session_error( + e, + self._project_id, + self._region, + _get_client_option( + self._client_options, "api_endpoint" + ), + session_config.session_template, + runtime_resolution.create_error_note(), + ) + ) from e + raise RuntimeError( + "Error while creating Managed Spark Session" ) from e except DefaultCredentialsError as e: ManagedSparkSession._active_s8s_session_id = None @@ -2776,7 +2923,14 @@ def terminate_s8s_session( # Client will get 'Aborted' error if session creation is still in progress and # 'FailedPrecondition' if another termination is still in progress. # Both are retryable, but we catch it and let TTL take care of cleanups. - except (FailedPrecondition, Aborted): + # Over REST, google-api-core maps HTTP 400/409 to the parent BadRequest / + # Conflict classes, so inspect the JSON error status there as well. + except (BadRequest, Conflict) as e: + if not isinstance(e, (FailedPrecondition, Aborted)) and ( + getattr(type(e), "grpc_status_code", None) is not None + or _api_error_status(e) not in ("FAILED_PRECONDITION", "ABORTED") + ): + raise logger.debug( f"{active_s8s_session_id} Managed Spark Session already terminated manually or automatically due to TTL" ) diff --git a/pyproject.toml b/pyproject.toml index 521f88c5..be7aaf4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,4 +11,5 @@ markers = [ "integration: marks tests as integration tests", "ci_safe: marks tests that work in CI environment", "slow: marks unit tests that take a second or more, mostly waiting; the smoke tests skip them", + "control_plane: marks integration tests that exercise Dataproc control-plane operations without the shared cluster", ] diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index f0c0218d..9b2e1578 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -25,6 +25,10 @@ TerminateSessionRequest, ) from google.cloud.managed_spark_connect import ManagedSparkSession +from google.cloud.managed_spark_connect.session import ( + _dataproc_api_endpoint, + _resolve_dataproc_transport, +) import pytest logger = logging.getLogger(__name__) @@ -79,7 +83,10 @@ def _candidate_regions( raw = [r.strip() for r in (regions_spec or "").split(",") if r.strip()] if not raw: raw = list(DEFAULT_CANDIDATE_REGIONS) - if "/" in test_subnet or custom_endpoint: + is_global_endpoint = (custom_endpoint or "").strip().rstrip( + "/" + ) == "dataproc.googleapis.com" + if "/" in test_subnet or (custom_endpoint and not is_global_endpoint): return [raw[0]] candidates = [] @@ -122,6 +129,11 @@ def _is_service_unavailable(exc): return False +def _dataproc_transport_kwargs(): + transport = _resolve_dataproc_transport() + return {"transport": transport} if transport != "grpc" else {} + + def _terminate_active_session(): """Best-effort, idempotent termination of any active or in-flight ManagedSparkSession.""" session_id = ManagedSparkSession._active_s8s_session_id @@ -147,12 +159,11 @@ def _terminate_active_session(): region = ManagedSparkSession._region or os.getenv("GOOGLE_CLOUD_REGION") if project_id and region: try: - endpoint = os.getenv( - "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", - f"{region}-dataproc.googleapis.com", - ) + endpoint = _dataproc_api_endpoint(region) opts = client_options.ClientOptions(api_endpoint=endpoint) - client = SessionControllerClient(client_options=opts) + client = SessionControllerClient( + client_options=opts, **_dataproc_transport_kwargs() + ) name = ( f"projects/{project_id}/locations/{region}/sessions/" f"{session_id}" @@ -290,10 +301,7 @@ def test_subnetwork_uri(test_project, test_region, test_subnet): @pytest.fixture def api_endpoint(test_region): - return os.getenv( - "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", - f"{test_region}-dataproc.googleapis.com", - ) + return _dataproc_api_endpoint(test_region) @pytest.fixture @@ -304,12 +312,11 @@ def test_client_options(api_endpoint, os_environment): def _get_session_controller_client(_region_state, region): clients = _region_state["session_clients"] if region not in clients: - endpoint = os.getenv( - "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", - f"{region}-dataproc.googleapis.com", - ) + endpoint = _dataproc_api_endpoint(region) opts = client_options.ClientOptions(api_endpoint=endpoint) - clients[region] = SessionControllerClient(client_options=opts) + clients[region] = SessionControllerClient( + client_options=opts, **_dataproc_transport_kwargs() + ) return clients[region] @@ -324,7 +331,7 @@ def session_controller_client(_region_state, test_region, test_client_options): clients = _region_state["session_clients"] if test_region not in clients: clients[test_region] = SessionControllerClient( - client_options=test_client_options + client_options=test_client_options, **_dataproc_transport_kwargs() ) return clients[test_region] @@ -336,7 +343,7 @@ def session_template_controller_client( clients = _region_state["template_clients"] if test_region not in clients: clients[test_region] = SessionTemplateControllerClient( - client_options=test_client_options + client_options=test_client_options, **_dataproc_transport_kwargs() ) return clients[test_region] diff --git a/tests/integration/test_session.py b/tests/integration/test_session.py index ddfe404b..1c1b68a3 100644 --- a/tests/integration/test_session.py +++ b/tests/integration/test_session.py @@ -18,9 +18,10 @@ import warnings from google.api_core.exceptions import ( - InvalidArgument, + BadRequest, + Forbidden, MethodNotImplemented, - PermissionDenied, + NotFound, ) from google.cloud.dataproc_v1 import ( CreateSessionTemplateRequest, @@ -230,6 +231,7 @@ def session_template_name( ) +@pytest.mark.control_plane def test_create_spark_session_with_session_template_and_user_provided_session_config( test_project, test_region, @@ -447,6 +449,7 @@ def test_runtime_profile_pre_3_0_warns_and_overrides_to_default( connect_session.stop() +@pytest.mark.control_plane def test_runtime_profile_pre_3_0_with_staging_bucket_appends_override_note_on_error( test_project, test_region, @@ -481,6 +484,7 @@ def test_runtime_profile_pre_3_0_with_staging_bucket_appends_override_note_on_er assert "dataproc-spark-connect~=0.9.0" in err +@pytest.mark.control_plane def test_unreadable_pre_3_0_and_unversioned_runtime_profiles_fail_fast( test_project, test_region, @@ -787,6 +791,7 @@ def test_serverless_session_termination_and_deletion_lifecycle( pass +@pytest.mark.control_plane def test_create_spark_session_with_invalid_project_id( test_project, test_region, os_environment, isolated_session_state ): @@ -800,7 +805,7 @@ def test_create_spark_session_with_invalid_project_id( .getOrCreate() ) - assert isinstance(exc_info.value.__cause__, PermissionDenied) + assert isinstance(exc_info.value.__cause__, Forbidden) msg = str(exc_info.value) assert msg.startswith("Error while creating Managed Spark Session:") assert f"Permission denied on resource project {invalid_project}." in msg @@ -808,10 +813,11 @@ def test_create_spark_session_with_invalid_project_id( assert ManagedSparkSession._active_s8s_session_id is None +@pytest.mark.control_plane def test_create_spark_session_with_invalid_region( test_project, os_environment, isolated_session_state ): - """Test that an invalid region raises a clear ManagedSparkConnectException explaining the 404.""" + """Test that an invalid region raises a clear ManagedSparkConnectException.""" invalid_region = "us-east-4" with pytest.raises(ManagedSparkConnectException) as exc_info: @@ -821,17 +827,30 @@ def test_create_spark_session_with_invalid_region( .getOrCreate() ) - assert isinstance(exc_info.value.__cause__, MethodNotImplemented) msg = str(exc_info.value) - assert msg == ( - "Error while creating Managed Spark Session: Regional endpoint" - " 'us-east-4-dataproc.googleapis.com' (derived from location" - " 'us-east-4') returned HTTP 404; check that 'us-east-4' is a valid" - " Managed Spark region." - ) + custom_endpoint = ( + os.getenv("GOOGLE_CLOUD_DATAPROC_API_ENDPOINT") or "" + ).strip() + if custom_endpoint.rstrip("/") == "dataproc.googleapis.com": + # Global REST endpoint validates the location in Chemist rather than + # returning an HTTP 404 from a nonexistent regional hostname. + assert isinstance(exc_info.value.__cause__, Forbidden) + assert msg.startswith("Error while creating Managed Spark Session:") + assert invalid_region in msg + else: + assert isinstance( + exc_info.value.__cause__, (MethodNotImplemented, NotFound) + ) + assert msg == ( + "Error while creating Managed Spark Session: Regional endpoint" + " 'us-east-4-dataproc.googleapis.com' (derived from location" + " 'us-east-4') returned HTTP 404; check that 'us-east-4' is a valid" + " Managed Spark region." + ) assert ManagedSparkSession._active_s8s_session_id is None +@pytest.mark.control_plane def test_create_spark_session_with_invalid_session_template( test_project, test_region, os_environment, isolated_session_state ): @@ -852,7 +871,7 @@ def test_create_spark_session_with_invalid_session_template( .getOrCreate() ) - assert isinstance(exc_info.value.__cause__, InvalidArgument) + assert isinstance(exc_info.value.__cause__, BadRequest) msg = str(exc_info.value) assert msg.startswith("Error while creating Managed Spark Session:") assert f"'{template_id}' does not exist" in msg @@ -869,7 +888,7 @@ def test_create_spark_session_with_invalid_session_template( .getOrCreate() ) - assert isinstance(bare_exc_info.value.__cause__, InvalidArgument) + assert isinstance(bare_exc_info.value.__cause__, BadRequest) bare_msg = str(bare_exc_info.value) assert bare_msg.startswith("Error while creating Managed Spark Session:") assert f"'{template_id}' does not exist" in bare_msg @@ -889,7 +908,7 @@ def test_create_spark_session_with_invalid_session_template( .getOrCreate() ) - assert isinstance(mismatch_exc_info.value.__cause__, InvalidArgument) + assert isinstance(mismatch_exc_info.value.__cause__, BadRequest) mismatch_msg = str(mismatch_exc_info.value) assert mismatch_msg.startswith( "Error while creating Managed Spark Session:" diff --git a/tests/unit/test_dataproc.py b/tests/unit/test_dataproc.py index edf6958b..e89e274f 100644 --- a/tests/unit/test_dataproc.py +++ b/tests/unit/test_dataproc.py @@ -393,3 +393,115 @@ def worker(idx: int): assert client_count == 1 assert len({id(c) for c in results_client}) == 1 assert all(c is creds for c in results_creds) + + +def test_resolve_dataproc_transport_env_and_validation(monkeypatch): + monkeypatch.delenv(session_mod.DATAPROC_TRANSPORT_ENV, raising=False) + assert session_mod._resolve_dataproc_transport() == "grpc" + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "") + assert session_mod._resolve_dataproc_transport() == "grpc" + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, " REST ") + assert session_mod._resolve_dataproc_transport() == "rest" + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "http2") + with pytest.raises( + ValueError, match="Invalid MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT" + ): + session_mod._resolve_dataproc_transport() + + +def test_create_session_controller_client_respects_transport_and_caches_separately( + monkeypatch, +): + fake_creds = _FakeRealCredentials(valid=True, token="tok") + monkeypatch.setattr( + proxy_mod.googleauth, "default", lambda scopes=None: (fake_creds, "p") + ) + + calls = [] + + class TransportAwareClient: + + def __init__(self, **kwargs): + calls.append(kwargs) + self.kwargs = kwargs + + _set_client_cls(monkeypatch, TransportAwareClient) + opts = ClientOptions(api_endpoint="dataproc.googleapis.com") + + monkeypatch.delenv(session_mod.DATAPROC_TRANSPORT_ENV, raising=False) + c_grpc = session_mod._create_session_controller_client(client_options=opts) + assert "transport" not in c_grpc.kwargs + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "rest") + c_rest = session_mod._create_session_controller_client(client_options=opts) + assert c_rest.kwargs["transport"] == "rest" + assert c_rest is not c_grpc + assert ( + session_mod._create_session_controller_client(client_options=opts) + is c_rest + ) + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "grpc") + assert ( + session_mod._create_session_controller_client(client_options=opts) + is c_grpc + ) + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "rest") + opts_cert = ClientOptions( + api_endpoint="dataproc.googleapis.com", + client_cert_source=lambda: (b"cert", b"key"), + ) + c_cert = session_mod._create_session_controller_client( + client_options=opts_cert + ) + assert c_cert.kwargs["transport"] == "rest" + + +def test_builder_dataproc_transport_env_and_empty_endpoint_env(monkeypatch): + fake_creds = _FakeRealCredentials(valid=True, token="tok") + monkeypatch.setattr( + proxy_mod.googleauth, "default", lambda scopes=None: (fake_creds, "p") + ) + monkeypatch.setenv("GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", " ") + monkeypatch.delenv(session_mod.DATAPROC_TRANSPORT_ENV, raising=False) + + session_calls = [] + template_calls = [] + + class FakeSessionClient: + + def __init__(self, **kwargs): + session_calls.append(kwargs) + + class FakeTemplateClient: + + def __init__(self, **kwargs): + template_calls.append(kwargs) + + _set_client_cls(monkeypatch, FakeSessionClient) + monkeypatch.setattr( + session_mod.dataproc_v1, + "SessionTemplateControllerClient", + FakeTemplateClient, + ) + + builder = session_mod.ManagedSparkSession.builder.location("us-east4") + assert ( + builder._client_options.api_endpoint + == "us-east4-dataproc.googleapis.com" + ) + _ = builder.session_controller_client + _ = builder.session_template_controller_client + assert "transport" not in session_calls[-1] + assert "transport" not in template_calls[-1] + + monkeypatch.setenv(session_mod.DATAPROC_TRANSPORT_ENV, "rest") + rest_builder = session_mod.ManagedSparkSession.builder.location("us-east4") + _ = rest_builder.session_controller_client + _ = rest_builder.session_template_controller_client + assert session_calls[-1]["transport"] == "rest" + assert template_calls[-1]["transport"] == "rest" diff --git a/tests/unit/test_integration_conftest.py b/tests/unit/test_integration_conftest.py index 056b6c46..9cb2dd87 100644 --- a/tests/unit/test_integration_conftest.py +++ b/tests/unit/test_integration_conftest.py @@ -99,6 +99,14 @@ def test_candidate_regions_disables_fallback_for_custom_endpoint(self): ) self.assertEqual(candidates, ["us-east1"]) + def test_candidate_regions_keeps_fallback_for_global_endpoint(self): + candidates = integration_conftest._candidate_regions( + "us-east1,us-central1", + test_subnet="default", + custom_endpoint="dataproc.googleapis.com", + ) + self.assertEqual(candidates, ["us-east1", "us-central1"]) + @mock.patch.object(ManagedSparkSession.Builder, "getOrCreate") def test_create_session_with_region_fallback_switches_on_wrapped_503( self, mock_get_or_create @@ -193,6 +201,30 @@ def test_terminate_active_session_in_flight_via_controller_is_idempotent( ) self.assertIsNone(ManagedSparkSession._active_s8s_session_id) + @mock.patch.object(integration_conftest, "SessionControllerClient") + def test_terminate_active_session_forwards_rest_transport( + self, mock_client_cls + ): + ManagedSparkSession._active_s8s_session_id = "sc-rest-123" + ManagedSparkSession._project_id = "test-proj" + ManagedSparkSession._region = "us-east4" + + with mock.patch.dict( + os.environ, + { + "MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest", + "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT": "dataproc.googleapis.com", + }, + ): + integration_conftest._terminate_active_session() + + mock_client_cls.assert_called_once() + _, kwargs = mock_client_cls.call_args + self.assertEqual(kwargs["transport"], "rest") + self.assertEqual( + kwargs["client_options"].api_endpoint, "dataproc.googleapis.com" + ) + def test_remaining_items_need_shared_session(self): shared_item = mock.Mock(fixturenames=["connect_session"]) isolated_1 = mock.Mock(fixturenames=["isolated_session_state"]) diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index f8d7476a..73ba97c7 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -21,7 +21,10 @@ from google.api_core.exceptions import ( Aborted, + BadRequest, + Conflict, FailedPrecondition, + Forbidden, InvalidArgument, MethodNotImplemented, NotFound, @@ -4483,5 +4486,327 @@ def test_runtime_profile_and_session_template_alias(self): self.assertEqual(builder.session_config.session_template, "profile-b") +class TestRestTransportErrors(unittest.TestCase): + """Tests that REST-shaped google.api_core exceptions are handled like gRPC ones.""" + + def setUp(self): + super().setUp() + from google.cloud.managed_spark_connect import session as session_mod + + session_mod.clear_dataproc_caches() + ManagedSparkSession._active_s8s_session_id = None + ManagedSparkSession._active_s8s_session_uuid = None + ManagedSparkSession._default_session = None + + def tearDown(self): + from google.cloud.managed_spark_connect import session as session_mod + + session_mod.clear_dataproc_caches() + ManagedSparkSession._active_s8s_session_id = None + ManagedSparkSession._active_s8s_session_uuid = None + ManagedSparkSession._default_session = None + super().tearDown() + + @staticmethod + def _fake_http_response( + payload=None, + content_type="application/json; charset=UTF-8", + header_name="content-type", + ): + resp = mock.Mock() + resp.headers = {header_name: content_type} + if payload is not None: + resp.json.return_value = payload + else: + resp.json.side_effect = ValueError("not json") + return resp + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_rest_forbidden_with_dict_details( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + mock_session_controller_client.return_value.create_session.side_effect = Forbidden( + "POST https://dataproc.googleapis.com/v1/projects/bad-proj/locations/us-central1/sessions: " + "Permission denied on resource project bad-proj.", + details=[ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONSUMER_INVALID", + }, + { + "@type": "type.googleapis.com/google.rpc.DebugInfo", + "detail": "Project 'projects/bad-proj' not found or deleted.", + }, + ], + response=self._fake_http_response( + {"error": {"status": "PERMISSION_DENIED"}} + ), + ) + + with mock.patch.dict( + os.environ, {"MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest"} + ): + with self.assertRaises(ManagedSparkConnectException) as ctx: + ( + ManagedSparkSession.builder.projectId("bad-proj") + .location("us-central1") + .getOrCreate() + ) + + self.assertIsInstance(ctx.exception.__cause__, Forbidden) + self.assertEqual( + str(ctx.exception), + "Error while creating Managed Spark Session: " + "Permission denied on resource project bad-proj. " + "Project 'projects/bad-proj' not found or deleted.", + ) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_rest_bad_request_with_field_violations_and_hints( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + mock_session_controller_client.return_value.create_session.side_effect = BadRequest( + "POST https://dataproc.googleapis.com/v1/projects/p/locations/us-east4/sessions: " + "A subnetwork must be specified for this runtime", + details=[ + { + "@type": "type.googleapis.com/google.rpc.BadRequest", + "fieldViolations": [ + { + "field": "session.environment_config.execution_config.subnetwork_uri", + "description": "must not be empty", + } + ], + } + ], + response=self._fake_http_response( + {"error": {"status": "INVALID_ARGUMENT"}} + ), + ) + + with mock.patch.dict( + os.environ, {"MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest"} + ): + with self.assertRaises(ManagedSparkConnectException) as ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-east4") + .getOrCreate() + ) + + self.assertIsInstance(ctx.exception.__cause__, BadRequest) + msg = str(ctx.exception) + self.assertIn("A subnetwork must be specified for this runtime.", msg) + self.assertIn("subnetwork_uri: must not be empty", msg) + self.assertIn("MANAGED_SPARK_CONNECT_SUBNET", msg) + self.assertNotIn("https://dataproc.googleapis.com", msg) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_rest_html_404_regional_endpoint( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + mock_session_controller_client.return_value.create_session.side_effect = NotFound( + "POST https://us-east-4-dataproc.googleapis.com/v1/...: " + "Error 404", + response=self._fake_http_response( + payload=None, content_type="text/html; charset=UTF-8" + ), + ) + + with mock.patch.dict( + os.environ, + {"MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest"}, + clear=False, + ): + os.environ.pop("GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", None) + with self.assertRaises(ManagedSparkConnectException) as ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-east-4") + .getOrCreate() + ) + + self.assertIsInstance(ctx.exception.__cause__, NotFound) + self.assertEqual( + str(ctx.exception), + "Error while creating Managed Spark Session: Regional endpoint " + "'us-east-4-dataproc.googleapis.com' (derived from location " + "'us-east-4') returned HTTP 404; check that 'us-east-4' is a " + "valid Managed Spark region.", + ) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_rest_custom_endpoint_html_404_omits_html_body( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + mock_session_controller_client.return_value.create_session.side_effect = NotFound( + "POST https://custom-dataproc.googleapis.com/v1/...: " + "Error 404", + response=self._fake_http_response( + payload=None, content_type="text/html; charset=UTF-8" + ), + ) + + with mock.patch.dict( + os.environ, + { + "MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest", + "GOOGLE_CLOUD_DATAPROC_API_ENDPOINT": ( + "custom-dataproc.googleapis.com" + ), + }, + ): + with self.assertRaises(ManagedSparkConnectException) as ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-central1") + .getOrCreate() + ) + + self.assertIsInstance(ctx.exception.__cause__, NotFound) + self.assertEqual( + str(ctx.exception), + "Error while creating Managed Spark Session: Endpoint " + "'custom-dataproc.googleapis.com' (location 'us-central1') " + "returned HTTP 404.", + ) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_rest_json_404_not_misclassified_as_bad_region( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + mock_session_controller_client.return_value.create_session.side_effect = NotFound( + "POST https://us-east4-dataproc.googleapis.com/v1/...: " + "Requested entity was not found.", + response=self._fake_http_response( + {"error": {"status": "NOT_FOUND"}}, + header_name="Content-Type", + ), + ) + + with mock.patch.dict( + os.environ, + {"MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest"}, + clear=False, + ): + os.environ.pop("GOOGLE_CLOUD_DATAPROC_API_ENDPOINT", None) + with self.assertRaises(RuntimeError) as ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-east4") + .getOrCreate() + ) + + self.assertNotIsInstance(ctx.exception, ManagedSparkConnectException) + self.assertIsInstance(ctx.exception.__cause__, NotFound) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_create_session_grpc_not_found_and_failed_precondition_unchanged( + self, mock_session_controller_client, mock_credentials + ): + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + + # from_grpc_error() attaches the grpc.Call as response (no .headers). + fake_grpc_call = object() + mock_session_controller_client.return_value.create_session.side_effect = NotFound( + "Subnetwork not found", + response=fake_grpc_call, + ) + with self.assertRaises(RuntimeError) as not_found_ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-east4") + .getOrCreate() + ) + self.assertNotIsInstance( + not_found_ctx.exception, ManagedSparkConnectException + ) + self.assertIsInstance(not_found_ctx.exception.__cause__, NotFound) + + mock_session_controller_client.return_value.create_session.side_effect = FailedPrecondition( + "Precondition check failed", + response=fake_grpc_call, + ) + with self.assertRaises(RuntimeError) as precond_ctx: + ( + ManagedSparkSession.builder.projectId("p") + .location("us-east4") + .getOrCreate() + ) + self.assertNotIsInstance( + precond_ctx.exception, ManagedSparkConnectException + ) + self.assertIsInstance( + precond_ctx.exception.__cause__, FailedPrecondition + ) + + @mock.patch("google.auth.default") + @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") + def test_terminate_s8s_session_rest_failed_precondition_and_aborted( + self, mock_session_controller_client, mock_credentials + ): + from google.cloud.managed_spark_connect.session import ( + terminate_s8s_session, + ) + + cred = mock.MagicMock() + cred.token = "token" + mock_credentials.return_value = (cred, "") + + with mock.patch.dict( + os.environ, {"MANAGED_SPARK_CONNECT_DATAPROC_TRANSPORT": "rest"} + ): + # REST FailedPrecondition -> HTTP 400 BadRequest with FAILED_PRECONDITION status + mock_session_controller_client.return_value.terminate_session.side_effect = BadRequest( + "POST https://dataproc.googleapis.com/...: already terminating", + response=self._fake_http_response( + {"error": {"status": "FAILED_PRECONDITION"}} + ), + ) + terminate_s8s_session("p", "us-east4", "sc-1234") + + # REST Aborted -> HTTP 409 Conflict with ABORTED status + mock_session_controller_client.return_value.terminate_session.side_effect = Conflict( + "POST https://dataproc.googleapis.com/...: creation in progress", + response=self._fake_http_response( + {"error": {"status": "ABORTED"}} + ), + ) + terminate_s8s_session("p", "us-east4", "sc-1234") + + # Unrelated REST BadRequest (INVALID_ARGUMENT) is NOT swallowed + mock_session_controller_client.return_value.terminate_session.side_effect = BadRequest( + "POST https://dataproc.googleapis.com/...: invalid name", + response=self._fake_http_response( + {"error": {"status": "INVALID_ARGUMENT"}} + ), + ) + with self.assertRaises(BadRequest): + terminate_s8s_session("p", "us-east4", "sc-1234") + + if __name__ == "__main__": unittest.main()