chore(spark): convert Spark examples to Jupyter notebooks #796
Check out this pull request on <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>
🎉 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:
Join the community:
Feel free to ask questions in the comments if you need any help or clarification!
Thanks again for contributing to Kubeflow! 🙏
/ok-to-test
/retest
sessions[-1] can select and delete another user’s session because Kubernetes does not guarantee list order. Preserve the exact created session name
All five examples stop the local client but leave SparkConnect clusters running. Explicitly delete each session after use.
SPARK_TEST_NAMESPACE is interpolated into a shell=True command, allowing command injection. Pass arguments as a list without a shell.
Addressed. Removed shell=True and passed command arguments as a list (["kubectl", "get", "namespace", namespace]) to avoid command injection risks.
Addressed. Assigned a unique UUID-based session name upfront and directly queried/deleted that specific session instead of relying on list index ordering.
Addressed. Added explicit unique session names and appended client.delete_session(...) across all 5 example blocks to prevent resource leaks on remote clusters.
still uses hardcoded custom_name = "my-spark-session" collision risk vs UUID names elsewhere
Fine for short papermill runs (process dies with the kernel), but keeping/terminate() on cleanup would be cleaner
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.ipynbbatch_job_lifecycle.ipynbbatch_func_job_lifecycle.ipynbbatch_failed_job.ipynbbatch_job_options.ipynbOtherwise the published docs examples page stays out of sync with the README / shipped notebooks.
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.
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.
I captured pf_proc and added pf_proc.terminate() in the final cleanup cell, so the port-forward process gets killed properly.
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....
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....
/lgtm
This change should be removed. The CLAUDE.md symlink should remain as is - unrelated to this PR.
This is the new header we want to use in subprojects.
#!/usr/bin/env bash
# Copyright The Kubeflow Authors.
#
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.
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.
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"
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.
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.
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
Do we need to deviate from how Trainer script is written?
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.
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.
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.
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.
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.
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.
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.
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().
This comment need to be addressed.
Please address this too.
Please remove the test directory altogether - since it is empty now.
https://github.com/Neha-Nimsatkar/sdk/tree/feat/spark-notebooks-635/test
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
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.
/retitle chore(spark): convert Spark examples to Jupyter notebooks
/retest
/ok-to-test
/retest
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.
Thanks for the alignment @RobuRishabh!
I have just a few additional comments @Neha-Nimsatkar.
/cc @andreyvelich
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?
Thanks for the contrbution @Neha-Nimsatkar!
/lgtm
/milestone v0.6
Thanks @Neha-Nimsatkar for working on this! This review was done with the help of AI tools.
@Neha-Nimsatkar LGTM, could you rebase this PR, so we can merge it please?
/ok-to-test
/retest
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?
@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 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!
Thanks for this great work @Neha-Nimsatkar!
/lgtm
/approve
[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:
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":[]} -->
Thank you so much @tariq-hasan, @andreyvelich, @RobuRishabh and @Shekharrajak for the guidance and reviews throughout! Really enjoyed working on this.
RobuRishabh
Neha-Nimsatkar
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 inkubeflow/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.ipynbbatch_func_job_lifecycle.ipynbbatch_job_options.ipynbbatch_failed_job.ipynbSpark Connect lifecycle & sessions:
connect_existing_session.ipynbdemo_existing_sparkconnect.ipynbspark_advanced_options.ipynbspark_connect_simple.ipynbOut-of-cluster connection handling & bug fixes (#801)
CellTimeoutErrorduring host execution: Migrating from in-cluster jobs to host-level Papermill runner execution causedbuild_service_url(info)to construct internal DNS (.svc.cluster.local:15002), which cannot be resolved from the host runner. Updatedconnect_existing_session.ipynbto check forKUBERNETES_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.setup_client.backendproperty to resolve the previousAttributeError: 'SparkClient' object has no attribute '_backend'.KEP-107 & SDK spec alignment
options=[Name(...)]rather than direct kwargs.DriverandExecutorarguments to pass standard resource dictionaries (resources={"cpu": "1", "memory": "512m"}) andresources_per_executor.info.service_urlwithinfo.service_name.kubernetes.io/os: linux, and removed non-provisioned customservice_account) so all sessions schedule and pass reliably on single-node KinD CI environments.Security, teardown & review feedback
subprocess.runcalls indemo_existing_sparkconnect.ipynbby passing arguments as an explicit list withoutshell=True.sessions[-1]) with unique UUID-based session names (f"...-{uuid.uuid4().hex[:8]}").client.delete_session(...)teardown calls across all demo blocks inspark_advanced_options.ipynb.Legacy test harness removal & workflow modernization
test/e2e/spark/test_spark_examples.py,run_in_cluster.py,cluster_watcher.py,test/e2e/spark/README.md, andhack/Dockerfile.spark-e2e-runner.batch_.py,connect_*.py,spark_connect_simple.py,spark_advanced_options.py).examples/spark/spark_job.py(for driver pod execution) andexamples/spark/test_connect_url.py(URL connection test).docs/source/examples.rstandexamples/spark/README.mdto reference.ipynbnotebook paths and cleaned up lingering references to deleted.pytest files.python3kernelspec metadata across all notebooks, introducedhack/e2e-run-notebook.sh, and updated.github/workflows/test-spark-examples.yamlto spin up KinD, execute all 8 notebooks sequentially via Papermill, and export execution artifacts.Verification
Formatting and repo checks:
SDK and unit tests:
CI runs:
Spark Examples E2E Test / example-validation (1.32.0)passes completely green across all 8 notebooks.Checklist
git commit -s) per DCO.pytest files remain