← Back to Pull requests

chore(spark): convert Spark examples to Jupyter notebooks #796

Merged
Neha-Nimsatkar merged 32 files (5044 lines) on Oct 07, 2026 19:41 UTC
View on GitHub
Neha-Nimsatkar Neha-Nimsatkar commented on Sep 12, 2026 14:49 UTC
Author

Description

TL;DR: Migrates Spark examples from standalone scripts to Jupyter notebooks, removes the legacy test harness, and fixes a CI timeout caused by out-of-cluster DNS resolution (#801).

Fixes #635
Fixes #801

This PR completes the migration of the Spark SDK examples from standalone Python scripts to interactive Jupyter notebooks (.ipynb), aligning with the conventions established in kubeflow/trainer. It removes the legacy in-cluster test harness and introduces a host-level Papermill-based E2E CI workflow that headlessly validates the notebooks against a live KinD cluster.

What changed

Notebooks added & converted (examples/spark/)

Batch job lifecycle:

  • batch_job_lifecycle.ipynb

  • batch_func_job_lifecycle.ipynb

  • batch_job_options.ipynb

  • batch_failed_job.ipynb
  • Spark Connect lifecycle & sessions:

  • connect_existing_session.ipynb

  • demo_existing_sparkconnect.ipynb

  • spark_advanced_options.ipynb

  • spark_connect_simple.ipynb
  • Out-of-cluster connection handling & bug fixes (#801)

  • Resolved CellTimeoutError during host execution: Migrating from in-cluster jobs to host-level Papermill runner execution caused build_service_url(info) to construct internal DNS (.svc.cluster.local:15002), which cannot be resolved from the host runner. Updated connect_existing_session.ipynb to check for KUBERNETES_SERVICE_HOST:

  • - Uses direct internal service DNS when running in-cluster.
    - Falls back to setup_client.backend.get_connect_url(info) to leverage built-in localhost port-forwarding when executed on external hosts/CI.
  • SDK attribute fix: Used the public setup_client.backend property to resolve the previous AttributeError: 'SparkClient' object has no attribute '_backend'.
  • KEP-107 & SDK spec alignment

  • Session naming options: Aligned session initialization to pass custom identifiers via options=[Name(...)] rather than direct kwargs.

  • Compute specifications: Restructured Driver and Executor arguments to pass standard resource dictionaries (resources={"cpu": "1", "memory": "512m"}) and resources_per_executor.

  • Dataclass field correction: Replaced deprecated info.service_url with info.service_name.

  • KinD-friendly resource constraints: Scaled down advanced options (swapped unavailable GPU limits for CPU/memory, updated node selectors to kubernetes.io/os: linux, and removed non-provisioned custom service_account) so all sessions schedule and pass reliably on single-node KinD CI environments.
  • Security, teardown & review feedback

  • Subprocess sanitization: Sanitized subprocess.run calls in demo_existing_sparkconnect.ipynb by passing arguments as an explicit list without shell=True.

  • Deterministic session targeting: Replaced non-deterministic list indexing (sessions[-1]) with unique UUID-based session names (f"...-{uuid.uuid4().hex[:8]}").

  • Resource cleanup: Added explicit client.delete_session(...) teardown calls across all demo blocks in spark_advanced_options.ipynb.
  • Legacy test harness removal & workflow modernization

  • Removed legacy test harness: Completely deleted test/e2e/spark/test_spark_examples.py, run_in_cluster.py, cluster_watcher.py, test/e2e/spark/README.md, and hack/Dockerfile.spark-e2e-runner.

  • Removed deprecated standalone scripts: Deleted old script equivalents (batch_.py, connect_*.py, spark_connect_simple.py, spark_advanced_options.py).

  • Retained necessary standalone scripts: Kept examples/spark/spark_job.py (for driver pod execution) and examples/spark/test_connect_url.py (URL connection test).

  • Updated documentation: Updated docs/source/examples.rst and examples/spark/README.md to reference .ipynb notebook paths and cleaned up lingering references to deleted .py test files.

  • CI harness: Added python3 kernelspec metadata across all notebooks, introduced hack/e2e-run-notebook.sh, and updated .github/workflows/test-spark-examples.yaml to spin up KinD, execute all 8 notebooks sequentially via Papermill, and export execution artifacts.
  • Verification

    Formatting and repo checks:

    uv run pre-commit run --all-files
    uv run ruff check .
    

    SDK and unit tests:

    uv run pytest kubeflow/spark/ -v
    

    CI runs:

  • Spark Examples E2E Test / example-validation (1.32.0) passes completely green across all 8 notebooks.

  • All documentation, linting, and matrix E2E tests pass.
  • Checklist

  • Follows Conventional Commits

  • Commits signed off (git commit -s) per DCO

  • Pre-commit hooks and ruff checks pass locally

  • Zero references to deleted .py test files remain

  • Fixed host-level DNS resolution/timeout (#801)

  • E2E notebook harness validated green in CI
  • Diff: 5044 lines (+2011 / -3033) across 32 files Reviewer: RobuRishabh Review duration: 36292m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.72) × (1 − Review Confidence (0.77)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 5044 lines diff across 32 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    77%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    56 items
    review-notebook-app[bot] review-notebook-app[bot] commented on Sep 12, 2026 14:49 UTC
    Bot

    Check out this pull request on&nbsp; <a href="https://app.reviewnb.com/kubeflow/sdk/pull/796"><img align="absmiddle" alt="ReviewNB" height="30" class="BotMessageButtonImage" src="https://raw.githubusercontent.com/ReviewNB/support/master/images/button_reviewnb.png" style="height: 30px !important;"/></a>

    See visual diffs & provide feedback on Jupyter Notebooks.

    ---

    <i>Powered by <a href='https://www.reviewnb.com/?utm_source=gh'>ReviewNB</a></i>

    github-actions[bot] github-actions[bot] commented on Sep 12, 2026 14:49 UTC
    Bot

    🎉 Welcome to the Kubeflow SDK! 🎉

    Thanks for opening your first PR! We're happy to have you as part of our community 🚀

    Here's what happens next:

  • If you haven't already, please check out our Contributing Guide for repo-specific guidelines and the Kubeflow Contributor Guide for general community standards

  • Our team will review your PR soon! cc @kubeflow/kubeflow-sdk-team
  • Join the community:

  • Slack: Join our #kubeflow-ml-experience and #kubeflow-trainer Slack channels

  • Meetings: Attend the Kubeflow SDK and ML Experience bi-weekly meetings
  • Feel free to ask questions in the comments if you need any help or clarification!
    Thanks again for contributing to Kubeflow! 🙏

    tariq-hasan tariq-hasan commented on Sep 13, 2026 16:30 UTC
    Contributor

    /ok-to-test
    /retest

    RobuRishabh RobuRishabh commented on code on Sep 14, 2026 14:36 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,212 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    f\"kubectl get namespace {namespace}\", shell=True, capture_output=True, text=True\n",
    +    ")\n",
    +    "if res.returncode == 0:\n",
    +    "    print(f\"✓ Namespace '{namespace}' reachable on cluster.\")\n",
    +    "else:\n",
    +    "    print(f\"Warning: Cluster connectivity check returned: {res.stderr.strip()}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Example 1: Create SparkConnect Session with Defaults\n",
    +    "\n",
    +    "Launch an interactive session using default sizing. Once ready, inspect the assigned service URL and driver pod."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "print(\"Launching SparkConnect session with default configuration...\")\n",
    +    "spark = client.connect(timeout=120)\n",
    +    "\n",
    +    "# Discover the auto-generated session\n",
    +    "sessions = client.list_sessions()\n",
    +    "default_session_name = sessions[-1].name if sessions else None\n",

    sessions[-1] can select and delete another user’s session because Kubernetes does not guarantee list order. Preserve the exact created session name

    RobuRishabh RobuRishabh commented on code on Sep 14, 2026 14:37 UTC
    Code Review
    examples/spark/spark_advanced_options.ipynb:1
    @@ -0,0 +1,311 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Advanced Spark Connect Options (KEP-107 Pattern)\n",
    +    "\n",
    +    "This notebook demonstrates how to apply advanced Kubernetes configurations to interactive Spark Connect sessions using the KEP-107 options pattern.\n",
    +    "\n",
    +    "### What you will learn:\n",
    +    "1. Adding `Labels` and `Annotations` for cost attribution, monitoring, and metadata tracking.\n",
    +    "2. Applying `NodeSelector` to route driver/executors to dedicated hardware pools (e.g., GPU nodes).\n",
    +    "3. Specifying `Toleration` configurations for tainted nodes and spot instance execution.\n",
    +    "4. Explicitly naming sessions with the `Name` option.\n",
    +    "5. Combining `Driver`, `Executor`, and scheduling options into production deployment patterns."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Environment and Client Setup\n",
    +    "\n",
    +    "Import classes from `kubeflow.spark` and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import (\n",
    +    "    Annotations,\n",
    +    "    Driver,\n",
    +    "    Executor,\n",
    +    "    Labels,\n",
    +    "    Name,\n",
    +    "    NodeSelector,\n",
    +    "    SparkClient,\n",
    +    "    Toleration,\n",
    +    ")\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"default\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Resource Organization with Labels and Annotations\n",
    +    "\n",
    +    "Attach Kubernetes labels for filtering and cost accounting alongside annotations for runbooks, alerting, and operational metadata."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "spark = client.connect(\n",
    +    "    num_executors=3,\n",
    +    "    resources_per_executor={\"cpu\": \"2\", \"memory\": \"4Gi\"},\n",
    +    "    spark_conf={\"spark.serializer\": \"org.apache.spark.serializer.KryoSerializer\"},\n",
    +    "    options=[\n",
    +    "        Labels(\n",
    +    "            {\n",
    +    "                \"app\": \"spark\",\n",
    +    "                \"team\": \"data-engineering\",\n",
    +    "                \"environment\": \"production\",\n",
    +    "                \"cost-center\": \"analytics\",\n",
    +    "            }\n",
    +    "        ),\n",
    +    "        Annotations(\n",
    +    "            {\n",
    +    "                \"description\": \"Daily ETL pipeline for customer data\",\n",
    +    "                \"owner\": \"data-team@company.com\",\n",
    +    "                \"runbook\": \"https://wiki.company.com/runbooks/etl\",\n",
    +    "                \"pagerduty\": \"spark-oncall\",\n",
    +    "            }\n",
    +    "        ),\n",
    +    "    ],\n",
    +    ")\n",
    +    "\n",
    +    "print(\"Spark session created with labels and annotations.\")\n",
    +    "df = spark.range(100)\n",
    +    "print(f\"Processed {df.count()} rows\")\n",
    +    "\n",
    +    "spark.stop()\n",

    All five examples stop the local client but leave SparkConnect clusters running. Explicitly delete each session after use.

    RobuRishabh RobuRishabh commented on code on Sep 14, 2026 14:38 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,212 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    f\"kubectl get namespace {namespace}\", shell=True, capture_output=True, text=True\n",

    SPARK_TEST_NAMESPACE is interpolated into a shell=True command, allowing command injection. Pass arguments as a list without a shell.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 18, 2026 17:54 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,212 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    f\"kubectl get namespace {namespace}\", shell=True, capture_output=True, text=True\n",

    Addressed. Removed shell=True and passed command arguments as a list (["kubectl", "get", "namespace", namespace]) to avoid command injection risks.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 18, 2026 17:55 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,212 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    f\"kubectl get namespace {namespace}\", shell=True, capture_output=True, text=True\n",
    +    ")\n",
    +    "if res.returncode == 0:\n",
    +    "    print(f\"✓ Namespace '{namespace}' reachable on cluster.\")\n",
    +    "else:\n",
    +    "    print(f\"Warning: Cluster connectivity check returned: {res.stderr.strip()}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Example 1: Create SparkConnect Session with Defaults\n",
    +    "\n",
    +    "Launch an interactive session using default sizing. Once ready, inspect the assigned service URL and driver pod."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "print(\"Launching SparkConnect session with default configuration...\")\n",
    +    "spark = client.connect(timeout=120)\n",
    +    "\n",
    +    "# Discover the auto-generated session\n",
    +    "sessions = client.list_sessions()\n",
    +    "default_session_name = sessions[-1].name if sessions else None\n",

    Addressed. Assigned a unique UUID-based session name upfront and directly queried/deleted that specific session instead of relying on list index ordering.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 18, 2026 17:55 UTC
    Code Review
    examples/spark/spark_advanced_options.ipynb:1
    @@ -0,0 +1,311 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Advanced Spark Connect Options (KEP-107 Pattern)\n",
    +    "\n",
    +    "This notebook demonstrates how to apply advanced Kubernetes configurations to interactive Spark Connect sessions using the KEP-107 options pattern.\n",
    +    "\n",
    +    "### What you will learn:\n",
    +    "1. Adding `Labels` and `Annotations` for cost attribution, monitoring, and metadata tracking.\n",
    +    "2. Applying `NodeSelector` to route driver/executors to dedicated hardware pools (e.g., GPU nodes).\n",
    +    "3. Specifying `Toleration` configurations for tainted nodes and spot instance execution.\n",
    +    "4. Explicitly naming sessions with the `Name` option.\n",
    +    "5. Combining `Driver`, `Executor`, and scheduling options into production deployment patterns."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Environment and Client Setup\n",
    +    "\n",
    +    "Import classes from `kubeflow.spark` and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import (\n",
    +    "    Annotations,\n",
    +    "    Driver,\n",
    +    "    Executor,\n",
    +    "    Labels,\n",
    +    "    Name,\n",
    +    "    NodeSelector,\n",
    +    "    SparkClient,\n",
    +    "    Toleration,\n",
    +    ")\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"default\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Resource Organization with Labels and Annotations\n",
    +    "\n",
    +    "Attach Kubernetes labels for filtering and cost accounting alongside annotations for runbooks, alerting, and operational metadata."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "spark = client.connect(\n",
    +    "    num_executors=3,\n",
    +    "    resources_per_executor={\"cpu\": \"2\", \"memory\": \"4Gi\"},\n",
    +    "    spark_conf={\"spark.serializer\": \"org.apache.spark.serializer.KryoSerializer\"},\n",
    +    "    options=[\n",
    +    "        Labels(\n",
    +    "            {\n",
    +    "                \"app\": \"spark\",\n",
    +    "                \"team\": \"data-engineering\",\n",
    +    "                \"environment\": \"production\",\n",
    +    "                \"cost-center\": \"analytics\",\n",
    +    "            }\n",
    +    "        ),\n",
    +    "        Annotations(\n",
    +    "            {\n",
    +    "                \"description\": \"Daily ETL pipeline for customer data\",\n",
    +    "                \"owner\": \"data-team@company.com\",\n",
    +    "                \"runbook\": \"https://wiki.company.com/runbooks/etl\",\n",
    +    "                \"pagerduty\": \"spark-oncall\",\n",
    +    "            }\n",
    +    "        ),\n",
    +    "    ],\n",
    +    ")\n",
    +    "\n",
    +    "print(\"Spark session created with labels and annotations.\")\n",
    +    "df = spark.range(100)\n",
    +    "print(f\"Processed {df.count()} rows\")\n",
    +    "\n",
    +    "spark.stop()\n",

    Addressed. Added explicit unique session names and appended client.delete_session(...) across all 5 example blocks to prevent resource leaks on remote clusters.

    RobuRishabh RobuRishabh commented on code on Sep 21, 2026 13:50 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,220 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    [\"kubectl\", \"get\", \"namespace\", namespace],\n",
    +    "    capture_output=True,\n",
    +    "    text=True,\n",
    +    ")\n",
    +    "\n",
    +    "if res.returncode == 0:\n",
    +    "    print(f\"✓ Namespace '{namespace}' reachable on cluster.\")\n",
    +    "else:\n",
    +    "    print(f\"Warning: Cluster connectivity check returned: {res.stderr.strip()}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Example 1: Create SparkConnect Session with Defaults\n",
    +    "\n",
    +    "Launch an interactive session using default sizing. Once ready, inspect the assigned service URL and driver pod."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"demo-sparkconnect-{uuid.uuid4().hex[:6]}\"\n",
    +    "print(f\"Launching SparkConnect session: {session_name}...\")\n",
    +    "spark = client.connect(options=[Name(session_name)], timeout=120)\n",
    +    "\n",
    +    "# Discover the auto-generated session\n",
    +    "session = client.get_session(name=session_name)\n",
    +    "default_session_name = session.name if session else None\n",
    +    "\n",
    +    "if default_session_name:\n",
    +    "    info = client.get_session(default_session_name)\n",
    +    "    print(f\"Session Name: {info.name}\")\n",
    +    "    print(f\"State:        {info.state.value}\")\n",
    +    "    print(f\"Driver Pod:   {info.driver_pod_name}\")\n",
    +    "    print(f\"Service Name: {info.service_name}\")\n",
    +    "\n",
    +    "spark.stop()\n",
    +    "print(\"Local SparkSession disconnected.\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 3. Example 2: Create Named Session with Custom Compute Specs\n",
    +    "\n",
    +    "Define a custom driver and executor topology using `Driver` and `Executor` objects."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "custom_name = \"my-spark-session\"\n",

    still uses hardcoded custom_name = "my-spark-session" collision risk vs UUID names elsewhere

    RobuRishabh RobuRishabh commented on code on Sep 21, 2026 13:52 UTC
    Code Review
    examples/spark/connect_existing_session.ipynb:1
    @@ -0,0 +1,155 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Connecting to an Existing Spark Connect Session\n",
    +    "\n",
    +    "This notebook demonstrates the two-client (\"bring your own server\") pattern:\n",
    +    "1. **Setup Client**: Provisions the Spark Connect server on Kubernetes and resolves its service URL.\n",
    +    "2. **Consumer Client**: Attaches to the running remote server using `client.connect(base_url=...)` without provisioning new cluster resources.\n",
    +    "3. **Execution & Cleanup**: Executes distributed transformations and deletes the server resource."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Backend Setup\n",
    +    "\n",
    +    "Configure backend client settings and import connection helpers."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Name, SparkClient\n",
    +    "from kubeflow.spark.backends.kubernetes.utils import build_service_url\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "print(f\"Backend configured for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Phase 1: Provision Spark Connect Server (Setup Client)\n",
    +    "\n",
    +    "Create the Spark Connect server instance and extract its connection URL (`sc://...`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"connect-existing-{uuid.uuid4().hex[:8]}\"\n",
    +    "setup_client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"Deploying Spark Connect server: {session_name}...\")\n",
    +    "setup_spark = setup_client.connect(options=[Name(session_name)], timeout=180)\n",
    +    "\n",
    +    "info = setup_client.get_session(session_name)\n",
    +    "if os.environ.get(\"KUBERNETES_SERVICE_HOST\"):\n",
    +    "    service_url = build_service_url(info)\n",
    +    "else:\n",
    +    "    service_url, _ = setup_client.backend.get_connect_url(info)\n",

    Fine for short papermill runs (process dies with the kernel), but keeping/terminate() on cleanup would be cleaner

    RobuRishabh RobuRishabh commented on code on Sep 21, 2026 13:57 UTC
    Code Review
    docs/source/examples.rst:1

    The Spark Examples table only rewrites the existing connect-session rows from .py → .ipynb, but this PR also adds batch notebooks (and keeps demo_existing_sparkconnect.ipynb) that are already listed in examples/spark/README.md.

    Please add rows here for:

  • demo_existing_sparkconnect.ipynb

  • batch_job_lifecycle.ipynb

  • batch_func_job_lifecycle.ipynb

  • batch_failed_job.ipynb

  • batch_job_options.ipynb
  • Otherwise the published docs examples page stays out of sync with the README / shipped notebooks.

    RobuRishabh RobuRishabh commented on code on Sep 21, 2026 14:14 UTC
    Code Review
    examples/spark/spark_connect_simple.ipynb:1
    @@ -0,0 +1,189 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Interactive Spark Connect (KEP-107 Three-Level API Pattern)\n",
    +    "\n",
    +    "This notebook demonstrates the three levels of the `SparkClient` interactive session API as specified in KEP-107:\n",
    +    "\n",
    +    "1. **Level 1 (Minimal)**: Use defaults for zero-configuration interactive sessions.\n",
    +    "2. **Level 2 (Simple)**: Configure basic executor counts and resource requests directly.\n",
    +    "3. **Level 3 (Advanced)**: Use granular `Driver` and `Executor` objects for custom pod controls.\n",
    +    "4. **Connecting to Existing Sessions**: Attach to an external or running Spark Connect server via base URL."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Environment and Imports\n",
    +    "\n",
    +    "Import necessary types and configure backend settings."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"default\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Level 1: Minimal Usage\n",
    +    "\n",
    +    "Spin up a Spark Connect session using defaults for executor counts and resource limits."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"spark-connect-minimal-{uuid.uuid4().hex[:8]}\"\n",
    +    "\n",
    +    "spark = client.connect(\n",
    +    "    spark_conf={\"spark.serializer\": \"org.apache.spark.serializer.KryoSerializer\"},\n",
    +    "    options=[Name(session_name)],\n",
    +    ")\n",
    +    "\n",
    +    "df = spark.range(10)\n",
    +    "print(f\"Generated range with {df.count()} rows on session: {session_name}\")\n",
    +    "df.show()\n",
    +    "\n",
    +    "spark.stop()\n",
    +    "client.delete_session(session_name)\n",
    +    "print(\"Level 1 session stopped and cleaned up.\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 3. Level 2: Simple Parameters\n",
    +    "\n",
    +    "Customize compute sizing by passing `num_executors`, `resources_per_executor`, and custom Spark settings."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"my-simple-session-{uuid.uuid4().hex[:8]}\"\n",
    +    "\n",
    +    "spark = client.connect(\n",
    +    "    num_executors=5,\n",
    +    "    resources_per_executor={\"cpu\": \"2\", \"memory\": \"4Gi\"},\n",

    Level 2 still asks for 5×(2 CPU, 4Gi) while advanced options were scaled for KinD, this works today, but higher flake risk than the other notebooks.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 21, 2026 16:24 UTC
    Code Review
    examples/spark/demo_existing_sparkconnect.ipynb:1
    @@ -0,0 +1,220 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Live Cluster SparkConnect Demonstration\n",
    +    "\n",
    +    "This notebook demonstrates how to provision, inspect, query, and manage interactive `SparkConnect` instances on Kubernetes using `SparkClient`.\n",
    +    "\n",
    +    "### Prerequisites:\n",
    +    "- A Kubernetes cluster (such as KinD) with the Kubeflow Spark Operator and SparkConnect CRD installed.\n",
    +    "- `kubectl` configured to reach the target cluster.\n",
    +    "- `pyspark` installed in the local environment (`uv pip install pyspark`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Cluster Health Check\n",
    +    "\n",
    +    "Verify cluster connectivity, select the target namespace, and initialize `SparkClient`."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import subprocess\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")\n",
    +    "\n",
    +    "# Check cluster access via kubectl\n",
    +    "res = subprocess.run(\n",
    +    "    [\"kubectl\", \"get\", \"namespace\", namespace],\n",
    +    "    capture_output=True,\n",
    +    "    text=True,\n",
    +    ")\n",
    +    "\n",
    +    "if res.returncode == 0:\n",
    +    "    print(f\"✓ Namespace '{namespace}' reachable on cluster.\")\n",
    +    "else:\n",
    +    "    print(f\"Warning: Cluster connectivity check returned: {res.stderr.strip()}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Example 1: Create SparkConnect Session with Defaults\n",
    +    "\n",
    +    "Launch an interactive session using default sizing. Once ready, inspect the assigned service URL and driver pod."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"demo-sparkconnect-{uuid.uuid4().hex[:6]}\"\n",
    +    "print(f\"Launching SparkConnect session: {session_name}...\")\n",
    +    "spark = client.connect(options=[Name(session_name)], timeout=120)\n",
    +    "\n",
    +    "# Discover the auto-generated session\n",
    +    "session = client.get_session(name=session_name)\n",
    +    "default_session_name = session.name if session else None\n",
    +    "\n",
    +    "if default_session_name:\n",
    +    "    info = client.get_session(default_session_name)\n",
    +    "    print(f\"Session Name: {info.name}\")\n",
    +    "    print(f\"State:        {info.state.value}\")\n",
    +    "    print(f\"Driver Pod:   {info.driver_pod_name}\")\n",
    +    "    print(f\"Service Name: {info.service_name}\")\n",
    +    "\n",
    +    "spark.stop()\n",
    +    "print(\"Local SparkSession disconnected.\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 3. Example 2: Create Named Session with Custom Compute Specs\n",
    +    "\n",
    +    "Define a custom driver and executor topology using `Driver` and `Executor` objects."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "custom_name = \"my-spark-session\"\n",

    I updated custom_name to add a random 6-character UUID (f"my-spark-session-{uuid.uuid4().hex[:6]}") so there is no chance of name collision.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 21, 2026 16:25 UTC
    Code Review
    examples/spark/connect_existing_session.ipynb:1
    @@ -0,0 +1,155 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Connecting to an Existing Spark Connect Session\n",
    +    "\n",
    +    "This notebook demonstrates the two-client (\"bring your own server\") pattern:\n",
    +    "1. **Setup Client**: Provisions the Spark Connect server on Kubernetes and resolves its service URL.\n",
    +    "2. **Consumer Client**: Attaches to the running remote server using `client.connect(base_url=...)` without provisioning new cluster resources.\n",
    +    "3. **Execution & Cleanup**: Executes distributed transformations and deletes the server resource."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Imports and Backend Setup\n",
    +    "\n",
    +    "Configure backend client settings and import connection helpers."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Name, SparkClient\n",
    +    "from kubeflow.spark.backends.kubernetes.utils import build_service_url\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"spark-test\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "print(f\"Backend configured for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Phase 1: Provision Spark Connect Server (Setup Client)\n",
    +    "\n",
    +    "Create the Spark Connect server instance and extract its connection URL (`sc://...`)."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"connect-existing-{uuid.uuid4().hex[:8]}\"\n",
    +    "setup_client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"Deploying Spark Connect server: {session_name}...\")\n",
    +    "setup_spark = setup_client.connect(options=[Name(session_name)], timeout=180)\n",
    +    "\n",
    +    "info = setup_client.get_session(session_name)\n",
    +    "if os.environ.get(\"KUBERNETES_SERVICE_HOST\"):\n",
    +    "    service_url = build_service_url(info)\n",
    +    "else:\n",
    +    "    service_url, _ = setup_client.backend.get_connect_url(info)\n",

    I captured pf_proc and added pf_proc.terminate() in the final cleanup cell, so the port-forward process gets killed properly.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 21, 2026 16:26 UTC
    Code Review
    docs/source/examples.rst:1

    I added all 5 missing notebook rows (demo_existing_sparkconnect.ipynb and all 4 batch job notebooks) in the Sphinx table, so docs match the README now....

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 21, 2026 16:27 UTC
    Code Review
    examples/spark/spark_connect_simple.ipynb:1
    @@ -0,0 +1,189 @@
    +{
    + "cells": [
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "# SparkClient: Interactive Spark Connect (KEP-107 Three-Level API Pattern)\n",
    +    "\n",
    +    "This notebook demonstrates the three levels of the `SparkClient` interactive session API as specified in KEP-107:\n",
    +    "\n",
    +    "1. **Level 1 (Minimal)**: Use defaults for zero-configuration interactive sessions.\n",
    +    "2. **Level 2 (Simple)**: Configure basic executor counts and resource requests directly.\n",
    +    "3. **Level 3 (Advanced)**: Use granular `Driver` and `Executor` objects for custom pod controls.\n",
    +    "4. **Connecting to Existing Sessions**: Attach to an external or running Spark Connect server via base URL."
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 1. Environment and Imports\n",
    +    "\n",
    +    "Import necessary types and configure backend settings."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "import os\n",
    +    "import uuid\n",
    +    "\n",
    +    "from kubeflow.common.types import KubernetesBackendConfig\n",
    +    "from kubeflow.spark import Driver, Executor, Name, SparkClient\n",
    +    "\n",
    +    "namespace = os.environ.get(\"SPARK_TEST_NAMESPACE\", \"default\")\n",
    +    "backend_config = KubernetesBackendConfig(namespace=namespace)\n",
    +    "client = SparkClient(backend_config=backend_config)\n",
    +    "\n",
    +    "print(f\"SparkClient initialized for namespace: {namespace}\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 2. Level 1: Minimal Usage\n",
    +    "\n",
    +    "Spin up a Spark Connect session using defaults for executor counts and resource limits."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"spark-connect-minimal-{uuid.uuid4().hex[:8]}\"\n",
    +    "\n",
    +    "spark = client.connect(\n",
    +    "    spark_conf={\"spark.serializer\": \"org.apache.spark.serializer.KryoSerializer\"},\n",
    +    "    options=[Name(session_name)],\n",
    +    ")\n",
    +    "\n",
    +    "df = spark.range(10)\n",
    +    "print(f\"Generated range with {df.count()} rows on session: {session_name}\")\n",
    +    "df.show()\n",
    +    "\n",
    +    "spark.stop()\n",
    +    "client.delete_session(session_name)\n",
    +    "print(\"Level 1 session stopped and cleaned up.\")"
    +   ]
    +  },
    +  {
    +   "cell_type": "markdown",
    +   "metadata": {},
    +   "source": [
    +    "## 3. Level 2: Simple Parameters\n",
    +    "\n",
    +    "Customize compute sizing by passing `num_executors`, `resources_per_executor`, and custom Spark settings."
    +   ]
    +  },
    +  {
    +   "cell_type": "code",
    +   "execution_count": null,
    +   "metadata": {},
    +   "outputs": [],
    +   "source": [
    +    "session_name = f\"my-simple-session-{uuid.uuid4().hex[:8]}\"\n",
    +    "\n",
    +    "spark = client.connect(\n",
    +    "    num_executors=5,\n",
    +    "    resources_per_executor={\"cpu\": \"2\", \"memory\": \"4Gi\"},\n",

    I scaled down Level 2 to 1 executor with 1 CPU and 512m RAM (and also scaled down Level 3), so it stays light and works fine on KinD....

    RobuRishabh RobuRishabh commented on Sep 21, 2026 19:52 UTC
    Contributor

    /lgtm

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 20:56 UTC
    Code Review
    CLAUDE.md:1
    @@ -1 +0,0 @@
    -AGENTS.md

    This change should be removed. The CLAUDE.md symlink should remain as is - unrelated to this PR.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 20:57 UTC
    Code Review
    hack/e2e-run-notebook.sh:1
    @@ -0,0 +1,44 @@
    +#!/usr/bin/env bash
    +# Copyright 2026 The Kubeflow Authors.
    +#

    This is the new header we want to use in subprojects.

    #!/usr/bin/env bash
    # Copyright The Kubeflow Authors.
    #
    

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 21:41 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1

    Since you've removed cluster_watcher.py diagnostics for SparkApplications should be added. Let's remove this portion and them in e2e-run-notebook.sh similar to how it is done in the Trainer script: .https://github.com/kubeflow/trainer/blob/44819cff07b4d7363ed3fc0803be611d7206ddb7/hack/e2e-run-notebook.sh#L43-L63

    On a longer term basis the goal would be for the dignostics to be refactored as a failure hook and called from the action planned as part of https://github.com/kubeflow/testing/issues/1088. But that is beyond immediate scope. For now let's just add the diagnostics since we are deleting cluster_watcher.py.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 21:44 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -69,21 +70,43 @@ jobs:
               SPARK_OPERATOR_IMAGE_TAG: local
             timeout-minutes: 15
     
    -      - name: Build and load Spark E2E runner image (in-cluster)
    +      - name: Run E2E test for Spark example Notebooks
             run: |
    -          docker build -f hack/Dockerfile.spark-e2e-runner -t spark-e2e-runner:local .
    -          kind load docker-image spark-e2e-runner:local --name spark-test
    -        timeout-minutes: 5
    +          mkdir -p ./artifacts/notebooks
    +          chmod +x ./hack/e2e-run-notebook.sh

    Do we need chmod +x ./hack/e2e-run-notebook.sh? I think we can remove this. I don't see .github/workflows/test-e2e.yaml needing this.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 22:13 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -37,10 +37,11 @@ jobs:
             uses: astral-sh/setup-uv@v7
             with:
               enable-cache: true
    -      - name: Install project and test deps
    +      - name: Install project, test, and notebook deps
             run: |
    -          uv sync --extra spark
    -          uv pip install pytest pytest-timeout
    +          uv sync --extra spark --group notebooks
    +          uv pip install papermill ipykernel
    +          echo "$PWD/.venv/bin" >> "$GITHUB_PATH"

    Let's not add any redundancy. papermill and ipykernel are already in pyproject.toml so uv pip install papermill ipykernel is not needed here.

    This next bit might border on cosmetic but for consistency let's just replace with the following - aligning with .github/workflows/test-e2e.yaml.

          - name: Install Python dependencies
            run: |
              echo "Installing Kubeflow SDK from source with the Notebook dependencies"
              make install-dev extras=docker groups="--no-default-groups --group notebooks"
    
              # SDK's hack/e2e-run-notebook.sh calls `papermill` from PATH
              echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
    

    https://github.com/kubeflow/sdk/blob/3febcd7377d0cdb322bbb420207c3c26cbf7afd7/.github/workflows/test-e2e.yaml#L40-L46

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 22:19 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -69,21 +70,43 @@ jobs:
               SPARK_OPERATOR_IMAGE_TAG: local
             timeout-minutes: 15
     
    -      - name: Build and load Spark E2E runner image (in-cluster)
    +      - name: Run E2E test for Spark example Notebooks
             run: |
    -          docker build -f hack/Dockerfile.spark-e2e-runner -t spark-e2e-runner:local .
    -          kind load docker-image spark-e2e-runner:local --name spark-test
    -        timeout-minutes: 5
    +          mkdir -p ./artifacts/notebooks
    +          chmod +x ./hack/e2e-run-notebook.sh
     
    -      - name: Run example validation tests
    -        run: uv run pytest test/e2e/spark/test_spark_examples.py -v --tb=short
    +          notebooks=(
    +            "examples/spark/batch_job_lifecycle.ipynb"
    +            "examples/spark/batch_func_job_lifecycle.ipynb"
    +            "examples/spark/batch_job_options.ipynb"
    +            "examples/spark/batch_failed_job.ipynb"
    +            "examples/spark/connect_existing_session.ipynb"
    +            "examples/spark/demo_existing_sparkconnect.ipynb"
    +            "examples/spark/spark_advanced_options.ipynb"
    +            "examples/spark/spark_connect_simple.ipynb"
    +          )
    +
    +          for nb in "${notebooks[@]}"; do
    +            nb_name=$(basename "$nb")
    +            echo "Running notebook: $nb"
    +            NOTEBOOK_INPUT="$nb" \
    +            NOTEBOOK_OUTPUT="./artifacts/notebooks/${nb_name}" \
    +            PAPERMILL_TIMEOUT=600 \
    +            ./hack/e2e-run-notebook.sh
    +          done

    It is important that you rewrite this portion using the test-e2e-notebook Makefile target that you have added in this PR - otherwise the target is not being used.

    On a side note the goal is to try to align with .github/workflows/test-e2e.yaml as much as we can for now to maintain consistency.

    https://github.com/kubeflow/sdk/blob/3febcd7377d0cdb322bbb420207c3c26cbf7afd7/.github/workflows/test-e2e.yaml#L56-L74

    On a longer term basis a lot of the shared infra such as cluster setup will move to kubeflow/testing repo. There're active and planned items in the testing repo for this - https://github.com/kubeflow/testing/issues/1068, https://github.com/kubeflow/testing/issues/1075, https://github.com/kubeflow/testing/issues/1088. And then we would want to consolidate e2e setup for consumer subprojects/repos. But that is beyond immediate scope. For now let's try to maintain consistency with .github/workflows/test-e2e.yaml as much as we can.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 22:42 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -69,21 +70,43 @@ jobs:
               SPARK_OPERATOR_IMAGE_TAG: local
             timeout-minutes: 15
     
    -      - name: Build and load Spark E2E runner image (in-cluster)
    +      - name: Run E2E test for Spark example Notebooks
             run: |
    -          docker build -f hack/Dockerfile.spark-e2e-runner -t spark-e2e-runner:local .
    -          kind load docker-image spark-e2e-runner:local --name spark-test
    -        timeout-minutes: 5
    +          mkdir -p ./artifacts/notebooks
    +          chmod +x ./hack/e2e-run-notebook.sh
     
    -      - name: Run example validation tests
    -        run: uv run pytest test/e2e/spark/test_spark_examples.py -v --tb=short
    +          notebooks=(
    +            "examples/spark/batch_job_lifecycle.ipynb"
    +            "examples/spark/batch_func_job_lifecycle.ipynb"
    +            "examples/spark/batch_job_options.ipynb"
    +            "examples/spark/batch_failed_job.ipynb"
    +            "examples/spark/connect_existing_session.ipynb"
    +            "examples/spark/demo_existing_sparkconnect.ipynb"
    +            "examples/spark/spark_advanced_options.ipynb"
    +            "examples/spark/spark_connect_simple.ipynb"
    +          )
    +
    +          for nb in "${notebooks[@]}"; do
    +            nb_name=$(basename "$nb")
    +            echo "Running notebook: $nb"
    +            NOTEBOOK_INPUT="$nb" \
    +            NOTEBOOK_OUTPUT="./artifacts/notebooks/${nb_name}" \
    +            PAPERMILL_TIMEOUT=600 \
    +            ./hack/e2e-run-notebook.sh
    +          done
             env:
               SPARK_TEST_CLUSTER: spark-test
               SPARK_TEST_NAMESPACE: spark-test
    -          SPARK_E2E_DEBUG: "1"
    -          SPARK_E2E_RUN_IN_CLUSTER: "1"
    -          SPARK_E2E_RUNNER_IMAGE: spark-e2e-runner:local
    -        timeout-minutes: 15
    +        timeout-minutes: 40
    +
    +      - name: Upload Notebook Artifacts
    +        if: always()
    +        uses: actions/upload-artifact@v4
    +        with:
    +          name: executed-notebooks-${{ matrix.kubernetes-version }}
    +          path: ./artifacts/notebooks/*

    More of a nit but let's rewrite this step as below

          - name: Upload Artifacts to GitHub
            uses: actions/upload-artifact@v6
            if: always() # Ensure artifacts are uploaded even if previous steps fail
            with:
              name: ${{ matrix.kubernetes-version }}
              path: ./artifacts/notebooks/* # Path relative to the workspace root
              retention-days: 1 #
    

    so we are consistent with .github/workflows/test-e2e.yaml

    https://github.com/kubeflow/sdk/blob/3febcd7377d0cdb322bbb420207c3c26cbf7afd7/.github/workflows/test-e2e.yaml#L76-L82

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 23:16 UTC
    Code Review
    hack/e2e-run-notebook.sh:1
    @@ -0,0 +1,44 @@
    +#!/usr/bin/env bash
    +# Copyright 2026 The Kubeflow Authors.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +
    +set -euo pipefail
    +
    +NOTEBOOK_INPUT="${NOTEBOOK_INPUT:?NOTEBOOK_INPUT must be set}"
    +NOTEBOOK_OUTPUT="${NOTEBOOK_OUTPUT:-/tmp/output.ipynb}"
    +PAPERMILL_TIMEOUT="${PAPERMILL_TIMEOUT:-900}"
    +
    +echo "=================================================================="
    +echo "Running Notebook: ${NOTEBOOK_INPUT}"
    +echo "Output Path:      ${NOTEBOOK_OUTPUT}"
    +echo "Execution Timeout:${PAPERMILL_TIMEOUT}s"
    +echo "=================================================================="
    +
    +# Ensure output directory exists
    +mkdir -p "$(dirname "${NOTEBOOK_OUTPUT}")"
    +
    +# Install ipykernel kernel spec if not present using uv environment
    +uv run python3 -m ipykernel install --user --name python3 --display-name "Python 3"
    +
    +# Execute notebook via papermill inside uv environment
    +uv run papermill \
    +    "${NOTEBOOK_INPUT}" \
    +    "${NOTEBOOK_OUTPUT}" \
    +    --kernel python3 \
    +    --execution-timeout "${PAPERMILL_TIMEOUT}" \
    +    --stdout-file /dev/stdout \
    +    --stderr-file /dev/stderr \
    +    --log-output
    +
    +echo "✓ Notebook ${NOTEBOOK_INPUT} passed successfully!"

    Do we need to deviate from how Trainer script is written?

    https://github.com/kubeflow/trainer/blob/44819cff07b4d7363ed3fc0803be611d7206ddb7/hack/e2e-run-notebook.sh#L1-L66

    Unless there are Spark-specific reasons to deviate I would strongly suggest to maintain a verbatim copy of the Trainer script in hack/e2e-run-notebook.sh. The reason again has to do with the eventual goal of moving logic to run notebook in the testing repo (https://github.com/kubeflow/testing/issues/1088). The less deviations the easier is the migration. It is important to not deviate also for consistency reasons and because the Trainer script has been heavily tested in CI already.

    The only portion that would change is the print_results() portion. This is where the Spark-specific diagnostic would go in.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 23:37 UTC
    Code Review
    hack/e2e-setup-cluster.sh:1

    This is not needed anymore since we are not running the notebooks in in-cluster mode.

    Two points I need to make here.

    First of all not testing notebooks in in-cluster mode is a genuine degradation in current e2e. And also it is in-cluster mode that tests genuine use cases since Kubeflow Notebooks run within a cluster and that's where these SDK clients should live in for e2e purposes. We should keep https://github.com/kubeflow/sdk/issues/635 open to revisit this and complete in-cluster papermill on KinD as a follow-up PR. This PR is only implementing host papermill on KinD.

    The second point is that everything in ensure_sparkconnect_rbac() will need to go - we will do that as part of https://github.com/kubeflow/sdk/issues/611. The reason all these permissions need to go is because these permissions do not represent the typical use case. If permissions are needed for a driver to create executor they need to align with how Kubeflow Notebooks/Workspaces and Kubeflow Community Distribution would set those permissions otherwise we should use the default Helm chart installation without additional permissions to test the e2e. But this second point is beyond the scope of this PR. We will revisit this in https://github.com/kubeflow/sdk/issues/611. For now let's remove only the highlighted role and rolebinding.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 23:47 UTC
    Code Review
    hack/e2e-setup-cluster.sh:1

    Please remove all E2E_CRD_ONLY references since you deleted the smoke test that uses it. All E2E_CRD_ONLY references in hack/e2e-setup-cluster.sh are now redundant and should be removed.

    In addition please remove the following line in pyproject.toml since it is also redundant in lieu of deleting the smoke test.

    https://github.com/kubeflow/sdk/blob/3febcd7377d0cdb322bbb420207c3c26cbf7afd7/pyproject.toml#L153

    I would think it is okay to remove the smoke test since it was a one-off test and we have deleted test/e2e/spark/test_spark_examples.py anyway - sp it won't make sense to retain the ad-hoc smoke test.

    tariq-hasan tariq-hasan commented on code on Sep 22, 2026 23:48 UTC
    Code Review
    test/e2e/spark/cluster_watcher.py:1
    @@ -1,127 +0,0 @@
    -# Copyright 2025 The Kubeflow Authors.

    Since you are removing all the modules from test/e2e/spark please delete the test directory since nothing else is left in there after deletion.

    tariq-hasan tariq-hasan requested changes on Sep 23, 2026 04:39 UTC
    Changes Requested Reviewer

    Hi @Neha-Nimsatkar! A few additional comments from me on the CI harness. Overall lgtm.

    The goal is to ensure consistency with the more mature Trainer subproject and to align with the stream of work in the testing repo to consolidate CI harness.

    Neha-Nimsatkar Neha-Nimsatkar commented on Sep 28, 2026 10:12 UTC
    Author

    Hi @tariq-hasan! Thanks for the detailed review.

    I have updated the PR and squashed all changes into a single clean commit to align with the Kubeflow Trainer conventions:

    1. CLAUDE.md: Reverted the accidental modification and restored the original upstream symlink.
    2. License header: Updated hack/e2e-run-notebook.sh header to # Copyright The Kubeflow Authors..
    3. Trainer parity & diagnostics: Aligned hack/e2e-run-notebook.sh directly with the Trainer script structure. Removed the standalone failure log step from .github/workflows/test-spark-examples.yaml and moved the Spark pod, resource, and log diagnostics into the print_results() failure trap.
    4. Workflow cleanup: Removed redundant chmod +x and updated the Python dependency step to match test-e2e.yaml using make install-dev extras=docker groups="--no-default-groups --group notebooks".
    5. RBAC & redundant references: Removed the e2e-sparkconnect-client Role/RoleBinding and E2E_CRD_ONLY references from hack/e2e-setup-cluster.sh. Also removed the smoke marker from pyproject.toml.
    6. Test folder cleanup: Deleted the empty test/e2e/spark directory.
    7. Makefile defaults: Added $(or ...) fallback defaults for NOTEBOOK_INPUT, NOTEBOOK_OUTPUT, and PAPERMILL_TIMEOUT in the test-e2e-notebook target.

    Regarding in-cluster notebook execution—understood! We will keep #635 open and follow up with the in-cluster Papermill execution on KinD in a separate PR.

    tariq-hasan tariq-hasan commented on code on Sep 29, 2026 04:03 UTC
    Code Review
    hack/e2e-run-notebook.sh:1
    @@ -0,0 +1,44 @@
    +#!/usr/bin/env bash
    +# Copyright 2026 The Kubeflow Authors.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +
    +set -euo pipefail
    +
    +NOTEBOOK_INPUT="${NOTEBOOK_INPUT:?NOTEBOOK_INPUT must be set}"
    +NOTEBOOK_OUTPUT="${NOTEBOOK_OUTPUT:-/tmp/output.ipynb}"
    +PAPERMILL_TIMEOUT="${PAPERMILL_TIMEOUT:-900}"
    +
    +echo "=================================================================="
    +echo "Running Notebook: ${NOTEBOOK_INPUT}"
    +echo "Output Path:      ${NOTEBOOK_OUTPUT}"
    +echo "Execution Timeout:${PAPERMILL_TIMEOUT}s"
    +echo "=================================================================="
    +
    +# Ensure output directory exists
    +mkdir -p "$(dirname "${NOTEBOOK_OUTPUT}")"
    +
    +# Install ipykernel kernel spec if not present using uv environment
    +uv run python3 -m ipykernel install --user --name python3 --display-name "Python 3"
    +
    +# Execute notebook via papermill inside uv environment
    +uv run papermill \
    +    "${NOTEBOOK_INPUT}" \
    +    "${NOTEBOOK_OUTPUT}" \
    +    --kernel python3 \
    +    --execution-timeout "${PAPERMILL_TIMEOUT}" \
    +    --stdout-file /dev/stdout \
    +    --stderr-file /dev/stderr \
    +    --log-output
    +
    +echo "✓ Notebook ${NOTEBOOK_INPUT} passed successfully!"

    This comment has not been addressed. Please make this an exact verbatim copy of trainer/hack/e2e-run-notebook.sh - the only change should. be in print_results to add Spark-specific diagnostics.

    Neha-Nimsatkar Neha-Nimsatkar commented on code on Sep 29, 2026 05:10 UTC
    Code Review
    hack/e2e-run-notebook.sh:1
    @@ -0,0 +1,44 @@
    +#!/usr/bin/env bash
    +# Copyright 2026 The Kubeflow Authors.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +
    +set -euo pipefail
    +
    +NOTEBOOK_INPUT="${NOTEBOOK_INPUT:?NOTEBOOK_INPUT must be set}"
    +NOTEBOOK_OUTPUT="${NOTEBOOK_OUTPUT:-/tmp/output.ipynb}"
    +PAPERMILL_TIMEOUT="${PAPERMILL_TIMEOUT:-900}"
    +
    +echo "=================================================================="
    +echo "Running Notebook: ${NOTEBOOK_INPUT}"
    +echo "Output Path:      ${NOTEBOOK_OUTPUT}"
    +echo "Execution Timeout:${PAPERMILL_TIMEOUT}s"
    +echo "=================================================================="
    +
    +# Ensure output directory exists
    +mkdir -p "$(dirname "${NOTEBOOK_OUTPUT}")"
    +
    +# Install ipykernel kernel spec if not present using uv environment
    +uv run python3 -m ipykernel install --user --name python3 --display-name "Python 3"
    +
    +# Execute notebook via papermill inside uv environment
    +uv run papermill \
    +    "${NOTEBOOK_INPUT}" \
    +    "${NOTEBOOK_OUTPUT}" \
    +    --kernel python3 \
    +    --execution-timeout "${PAPERMILL_TIMEOUT}" \
    +    --stdout-file /dev/stdout \
    +    --stderr-file /dev/stderr \
    +    --log-output
    +
    +echo "✓ Notebook ${NOTEBOOK_INPUT} passed successfully!"

    Addressed in the latest push. hack/e2e-run-notebook.sh is now an exact verbatim copy of Trainer's script, with only the Spark diagnostics inside print_results().

    tariq-hasan tariq-hasan commented on code on Sep 30, 2026 06:02 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -69,21 +70,43 @@ jobs:
               SPARK_OPERATOR_IMAGE_TAG: local
             timeout-minutes: 15
     
    -      - name: Build and load Spark E2E runner image (in-cluster)
    +      - name: Run E2E test for Spark example Notebooks
             run: |
    -          docker build -f hack/Dockerfile.spark-e2e-runner -t spark-e2e-runner:local .
    -          kind load docker-image spark-e2e-runner:local --name spark-test
    -        timeout-minutes: 5
    +          mkdir -p ./artifacts/notebooks
    +          chmod +x ./hack/e2e-run-notebook.sh
     
    -      - name: Run example validation tests
    -        run: uv run pytest test/e2e/spark/test_spark_examples.py -v --tb=short
    +          notebooks=(
    +            "examples/spark/batch_job_lifecycle.ipynb"
    +            "examples/spark/batch_func_job_lifecycle.ipynb"
    +            "examples/spark/batch_job_options.ipynb"
    +            "examples/spark/batch_failed_job.ipynb"
    +            "examples/spark/connect_existing_session.ipynb"
    +            "examples/spark/demo_existing_sparkconnect.ipynb"
    +            "examples/spark/spark_advanced_options.ipynb"
    +            "examples/spark/spark_connect_simple.ipynb"
    +          )
    +
    +          for nb in "${notebooks[@]}"; do
    +            nb_name=$(basename "$nb")
    +            echo "Running notebook: $nb"
    +            NOTEBOOK_INPUT="$nb" \
    +            NOTEBOOK_OUTPUT="./artifacts/notebooks/${nb_name}" \
    +            PAPERMILL_TIMEOUT=600 \
    +            ./hack/e2e-run-notebook.sh
    +          done

    This comment need to be addressed.

    tariq-hasan tariq-hasan commented on code on Sep 30, 2026 06:02 UTC
    Code Review
    .github/workflows/test-spark-examples.yaml:1
    @@ -69,21 +70,43 @@ jobs:
               SPARK_OPERATOR_IMAGE_TAG: local
             timeout-minutes: 15
     
    -      - name: Build and load Spark E2E runner image (in-cluster)
    +      - name: Run E2E test for Spark example Notebooks
             run: |
    -          docker build -f hack/Dockerfile.spark-e2e-runner -t spark-e2e-runner:local .
    -          kind load docker-image spark-e2e-runner:local --name spark-test
    -        timeout-minutes: 5
    +          mkdir -p ./artifacts/notebooks
    +          chmod +x ./hack/e2e-run-notebook.sh
     
    -      - name: Run example validation tests
    -        run: uv run pytest test/e2e/spark/test_spark_examples.py -v --tb=short
    +          notebooks=(
    +            "examples/spark/batch_job_lifecycle.ipynb"
    +            "examples/spark/batch_func_job_lifecycle.ipynb"
    +            "examples/spark/batch_job_options.ipynb"
    +            "examples/spark/batch_failed_job.ipynb"
    +            "examples/spark/connect_existing_session.ipynb"
    +            "examples/spark/demo_existing_sparkconnect.ipynb"
    +            "examples/spark/spark_advanced_options.ipynb"
    +            "examples/spark/spark_connect_simple.ipynb"
    +          )
    +
    +          for nb in "${notebooks[@]}"; do
    +            nb_name=$(basename "$nb")
    +            echo "Running notebook: $nb"
    +            NOTEBOOK_INPUT="$nb" \
    +            NOTEBOOK_OUTPUT="./artifacts/notebooks/${nb_name}" \
    +            PAPERMILL_TIMEOUT=600 \
    +            ./hack/e2e-run-notebook.sh
    +          done
             env:
               SPARK_TEST_CLUSTER: spark-test
               SPARK_TEST_NAMESPACE: spark-test
    -          SPARK_E2E_DEBUG: "1"
    -          SPARK_E2E_RUN_IN_CLUSTER: "1"
    -          SPARK_E2E_RUNNER_IMAGE: spark-e2e-runner:local
    -        timeout-minutes: 15
    +        timeout-minutes: 40
    +
    +      - name: Upload Notebook Artifacts
    +        if: always()
    +        uses: actions/upload-artifact@v4
    +        with:
    +          name: executed-notebooks-${{ matrix.kubernetes-version }}
    +          path: ./artifacts/notebooks/*

    Please address this too.

    tariq-hasan tariq-hasan commented on code on Sep 30, 2026 06:10 UTC
    Code Review
    test/e2e/spark/cluster_watcher.py:1
    @@ -1,127 +0,0 @@
    -# Copyright 2025 The Kubeflow Authors.

    Please remove the test directory altogether - since it is empty now.

    https://github.com/Neha-Nimsatkar/sdk/tree/feat/spark-notebooks-635/test

    Shekharrajak Shekharrajak requested changes on Sep 30, 2026 18:05 UTC
    Changes Requested Reviewer

    Seems like lots of files are changed - I would suggest to reduce the scope of the PR.

    Also the intention is to have notebook examples along with existing examples

    tariq-hasan tariq-hasan commented on Sep 30, 2026 19:08 UTC
    Contributor

    Actually the reason for the fairly large scope of the PR has to do with the harness itself - given that the notebooks and the harness needed to be aligned for the tests to pass.

    There are a couple of different pieces here that all needed to be aligned for this PR.

    The first is that notebook examples are for end-users - separate E2E tests (to replace the .py examples) can be written and exercised and that could become a separate SDK issue altogether.

    The second is that there is a stream of work currently in motion to centralize E2E cluster provisioning logic in the testing repo. Since notebook harness needed to be added in as well that harness was re-architected to mimic the more mature Trainer subproject to ensure we can easily migrate the Spark SDK cluster setup when it is due.

    The third is that the notebooks currently exercise only host papermill. In-cluster papermill would need a harness that's different from what we currently support in test/e2e/spark so that portion needed to go out as well in this PR since it would become redundant with the notebook conversion.

    On a separate note we also need to re-architect the cluster setup process in hack/e2e-setup-cluster.sh since there are some over-provisioning of permissions that does not quite mimic how Kubeflow Community Distribution and Kubeflow Workspaces would provision those permissions. And the E2E tests need to be able to catch drift with the upstream operator changes as well. These have been deliberately left out of this PR and have been scoped as part of https://github.com/kubeflow/sdk/issues/611.

    Would appreciate thoughts from @andreyvelich and @RobuRishabh as well.

    tariq-hasan tariq-hasan commented on Oct 02, 2026 00:57 UTC
    Contributor

    /retitle chore(spark): convert Spark examples to Jupyter notebooks

    tariq-hasan tariq-hasan commented on Oct 02, 2026 01:01 UTC
    Contributor

    /retest

    tariq-hasan tariq-hasan commented on Oct 02, 2026 01:01 UTC
    Contributor

    /ok-to-test
    /retest

    RobuRishabh RobuRishabh commented on Oct 02, 2026 01:57 UTC
    Contributor

    Thanks @tariq-hasan, I agree with the framing. notebook conversion and harness changes need to land together. The old in-cluster .py harness cannot validate the new notebooks, and keeping a half-migrated harness would leave CI broken or duplicated. Aligning hack/e2e-run-notebook.sh / the Spark examples workflow with Trainer also makes sense given the kubeflow/testing consolidation work.

    On keeping the old .py examples alongside notebooks (@Shekharrajak): I’d prefer replacement rather than duplication here.
    1. #635 is framed as a conversion, not “add notebooks and keep scripts.”
    2. Dual copies will drift, notebooks are the primary Spark UX (and match Trainer).
    3. Non-tutorial scripts that still have a real role (spark_job.py for FileJob, test_connect_url.py) are correctly retained.

    For CI : example-validation is still action_required on the latest merge commit. Once that check is green on HEAD, this looks good to land from my side.

    tariq-hasan tariq-hasan commented on Oct 02, 2026 06:43 UTC
    Reviewer

    Thanks for the alignment @RobuRishabh!

    I have just a few additional comments @Neha-Nimsatkar.

    /cc @andreyvelich

    Neha-Nimsatkar Neha-Nimsatkar commented on Oct 06, 2026 03:35 UTC
    Author

    Thanks for the review @tariq-hasan , I've addressed all the feedback:

    Added natural assertions across notebook examples to maintain test coverage
    Set realistic defaults with KinD-sized PAPERMILL_PARAMS in spark_advanced_options.ipynb
    Cleaned up demo_existing_sparkconnect.ipynb, spark_connect_simple.ipynb, and the setup/run scripts
    Updated examples/spark/README.md dependencies

    All CI checks are passing now. Could you please take another look when you get a chance?

    tariq-hasan tariq-hasan commented on Oct 07, 2026 14:46 UTC
    Contributor

    Thanks for the contrbution @Neha-Nimsatkar!
    /lgtm

    andreyvelich andreyvelich commented on Oct 07, 2026 15:35 UTC
    Contributor

    /milestone v0.6

    andreyvelich andreyvelich commented on Oct 07, 2026 16:25 UTC
    Reviewer

    Thanks @Neha-Nimsatkar for working on this! This review was done with the help of AI tools.

    andreyvelich andreyvelich commented on Oct 07, 2026 17:54 UTC
    Contributor

    @Neha-Nimsatkar LGTM, could you rebase this PR, so we can merge it please?

    andreyvelich andreyvelich commented on Oct 07, 2026 17:55 UTC
    Contributor

    /ok-to-test
    /retest

    Neha-Nimsatkar Neha-Nimsatkar commented on Oct 07, 2026 17:58 UTC
    Author

    Hi @tariq-hasan @andreyvelich,

    While rebasing this PR with latest main, I ran into a merge conflict in test/e2e/spark/test_spark_examples.py which was recently merged into main.

    That test suite runs the standalone .py scripts, but this PR transitions those Spark examples into Jupyter notebooks (.ipynb).

    How should I handle this file for #796? Should I keep test_spark_examples.py from main as is for now, or will the tests be updated for notebooks in a separate follow-up PR?

    andreyvelich andreyvelich commented on Oct 07, 2026 18:00 UTC
    Contributor

    @Neha-Nimsatkar Just delete all files from test/e2e as part of your PR, since we don't need them after transition to Notebooks.

    Neha-Nimsatkar Neha-Nimsatkar commented on Oct 07, 2026 18:29 UTC
    Author

    @Neha-Nimsatkar Just delete all files from test/e2e as part of your PR, since we don't need them after transition to Notebooks.

    Done... I've removed the test/e2e files, resolved the merge conflicts with main, verified pre-commit checks and squashed everything into a single clean commit.

    CI checks are currently running. Ready for final review!

    andreyvelich andreyvelich commented on Oct 07, 2026 19:10 UTC
    Contributor

    Thanks for this great work @Neha-Nimsatkar!
    /lgtm
    /approve

    google-oss-prow[bot] google-oss-prow[bot] commented on Oct 07, 2026 19:10 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubeflow/sdk/pull/796#issuecomment-6044952535" title="Approved">andreyvelich</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [andreyvelich]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Neha-Nimsatkar Neha-Nimsatkar commented on Oct 07, 2026 19:36 UTC
    Author

    Thank you so much @tariq-hasan, @andreyvelich, @RobuRishabh and @Shekharrajak for the guidance and reviews throughout! Really enjoyed working on this.

    Reviewers
    Assignees
    Neha-Nimsatkar Neha-Nimsatkar
    Labels
    risk: low confidence: 77.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 77.4% · Lower = rushed or shallow review
    77.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.2% · Safe to merge
    16.2%
    Repository