From 4c96bbf9e3a465b036dd2e4f85081ee9ed862226 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 09:36:43 +0000 Subject: [PATCH 01/12] Add libraries field to the clusters resource Re-lands #6365, which was reverted so the cluster libraries feature can be fixed before it ships. This reverts commit 3862ef880 (the revert of 76872b50ab9488133d54dac14c5d9aa11e69dda0). Co-authored-by: Isaac --- .nextchanges/bundles/cluster-libraries.md | 1 + .../configs/cluster_libraries.yml.tmpl | 14 + .../bundle/invariant/continue_293/test.toml | 3 + .../invariant/delete_idempotent/out.test.toml | 1 + .../destroy_idempotent/out.test.toml | 1 + acceptance/bundle/invariant/migrate/test.toml | 2 + .../bundle/invariant/no_drift/out.test.toml | 1 + acceptance/bundle/invariant/test.toml | 1 + acceptance/bundle/refschema/out.fields.txt | 17 ++ .../databricks.yml.tmpl | 23 ++ .../my_test_code/__init__.py | 2 + .../my_test_code/__main__.py | 16 + .../libraries-content-change/out.test.toml | 5 + .../libraries-content-change/output.txt | 33 ++ .../clusters/libraries-content-change/script | 30 ++ .../libraries-content-change/script.prepare | 3 + .../libraries-content-change/setup.py | 15 + .../libraries-content-change/test.toml | 14 + .../libraries-repo/databricks.yml.tmpl | 18 ++ .../clusters/libraries-repo/out.test.toml | 5 + .../clusters/libraries-repo/output.txt | 21 ++ .../resources/clusters/libraries-repo/script | 21 ++ .../clusters/libraries-repo/test.toml | 12 + .../libraries-restart/databricks.yml.tmpl | 17 ++ .../clusters/libraries-restart/out.test.toml | 5 + .../clusters/libraries-restart/output.txt | 31 ++ .../clusters/libraries-restart/script | 38 +++ .../clusters/libraries-restart/test.toml | 14 + .../databricks.yml.tmpl | 19 ++ .../libraries-stopped-cluster/out.test.toml | 5 + .../libraries-stopped-cluster/output.txt | 14 + .../clusters/libraries-stopped-cluster/script | 25 ++ .../libraries-stopped-cluster/test.toml | 12 + .../clusters/libraries/databricks.yml.tmpl | 25 ++ .../libraries/my_test_code/__init__.py | 2 + .../libraries/my_test_code/__main__.py | 16 + .../clusters/libraries/out.test.toml | 5 + .../resources/clusters/libraries/output.txt | 65 ++++ .../resources/clusters/libraries/script | 29 ++ .../clusters/libraries/script.prepare | 3 + .../resources/clusters/libraries/setup.py | 15 + .../resources/clusters/libraries/test.toml | 12 + .../mutator/validate_cluster_libraries.go | 43 +++ bundle/config/resources/clusters.go | 3 + bundle/direct/dresources/cluster.go | 282 +++++++++++++++++- bundle/internal/schema/annotations.yml | 3 + .../validation/generated/required_fields.go | 3 + bundle/libraries/expand_glob_references.go | 11 + bundle/libraries/remote_path.go | 2 + bundle/libraries/same_name_libraries.go | 2 + bundle/libraries/switch_to_patched_wheels.go | 16 + bundle/phases/plan.go | 1 + bundle/schema/jsonschema.json | 4 + bundle/terraform_dabs_map/generated.go | 32 +- libs/testserver/clusters.go | 29 ++ libs/testserver/fake_workspace.go | 4 +- libs/testserver/handlers.go | 17 ++ libs/testserver/libraries.go | 87 ++++++ .../databricks/bundles/clusters/__init__.py | 32 ++ .../bundles/clusters/_models/cluster.py | 11 + .../bundles/clusters/_models/library.py | 134 +++++++++ .../bundles/clusters/_models/maven_library.py | 72 +++++ .../clusters/_models/python_py_pi_library.py | 54 ++++ .../clusters/_models/r_cran_library.py | 50 ++++ .../core/_generated/clusters.py | 3 + 65 files changed, 1476 insertions(+), 30 deletions(-) create mode 100644 .nextchanges/bundles/cluster-libraries.md create mode 100644 acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/script create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/script.prepare create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/setup.py create mode 100644 acceptance/bundle/resources/clusters/libraries-content-change/test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-repo/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-repo/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries-repo/script create mode 100644 acceptance/bundle/resources/clusters/libraries-repo/test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-restart/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-restart/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries-restart/script create mode 100644 acceptance/bundle/resources/clusters/libraries-restart/test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries-stopped-cluster/script create mode 100644 acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py create mode 100644 acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py create mode 100644 acceptance/bundle/resources/clusters/libraries/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries/script create mode 100644 acceptance/bundle/resources/clusters/libraries/script.prepare create mode 100644 acceptance/bundle/resources/clusters/libraries/setup.py create mode 100644 acceptance/bundle/resources/clusters/libraries/test.toml create mode 100644 bundle/config/mutator/validate_cluster_libraries.go create mode 100644 libs/testserver/libraries.go create mode 100644 python/databricks/bundles/clusters/_models/library.py create mode 100644 python/databricks/bundles/clusters/_models/maven_library.py create mode 100644 python/databricks/bundles/clusters/_models/python_py_pi_library.py create mode 100644 python/databricks/bundles/clusters/_models/r_cran_library.py diff --git a/.nextchanges/bundles/cluster-libraries.md b/.nextchanges/bundles/cluster-libraries.md new file mode 100644 index 00000000000..1ff0e422fa5 --- /dev/null +++ b/.nextchanges/bundles/cluster-libraries.md @@ -0,0 +1 @@ +* Add libraries field to clusters. ([#6365](https://github.com/databricks/cli/pull/6365)) diff --git a/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl b/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl new file mode 100644 index 00000000000..507730ec287 --- /dev/null +++ b/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl @@ -0,0 +1,14 @@ +bundle: + name: test-bundle-$UNIQUE_NAME + +resources: + clusters: + foo: + cluster_name: test-cluster-$UNIQUE_NAME + spark_version: 13.3.x-scala2.12 + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/invariant/continue_293/test.toml b/acceptance/bundle/invariant/continue_293/test.toml index a02577b3504..15890459519 100644 --- a/acceptance/bundle/invariant/continue_293/test.toml +++ b/acceptance/bundle/invariant/continue_293/test.toml @@ -23,6 +23,9 @@ EnvMatrixExclude.no_instance_pool = ["INPUT_CONFIG=instance_pool.yml.tmpl"] # cluster_policies resource is not supported on v0.293.0 EnvMatrixExclude.no_cluster_policy = ["INPUT_CONFIG=cluster_policy.yml.tmpl"] +# cluster libraries (clusters.libraries) are not supported on v0.293.0 +EnvMatrixExclude.no_cluster_libraries = ["INPUT_CONFIG=cluster_libraries.yml.tmpl"] + # job_runs resource is not supported on v0.293.0 EnvMatrixExclude.no_job_run = ["INPUT_CONFIG=job_run.yml.tmpl"] diff --git a/acceptance/bundle/invariant/delete_idempotent/out.test.toml b/acceptance/bundle/invariant/delete_idempotent/out.test.toml index 9b900c7722d..5f37ab6036c 100644 --- a/acceptance/bundle/invariant/delete_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/delete_idempotent/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml index 9b900c7722d..5f37ab6036c 100644 --- a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/migrate/test.toml b/acceptance/bundle/invariant/migrate/test.toml index 43fb485e622..bfbcf9bb430 100644 --- a/acceptance/bundle/invariant/migrate/test.toml +++ b/acceptance/bundle/invariant/migrate/test.toml @@ -28,6 +28,8 @@ EnvMatrixExclude.no_genie_space = ["INPUT_CONFIG=genie_space.yml.tmpl"] EnvMatrixExclude.no_instance_pool = ["INPUT_CONFIG=instance_pool.yml.tmpl"] # Cluster policies are direct-only; the terraform deploy that seeds the migration fails for them. EnvMatrixExclude.no_cluster_policy = ["INPUT_CONFIG=cluster_policy.yml.tmpl"] +# Cluster libraries are direct-only; the terraform deploy that seeds the migration fails for them. +EnvMatrixExclude.no_cluster_libraries = ["INPUT_CONFIG=cluster_libraries.yml.tmpl"] # AI Gateway securables are direct-only; the terraform deploy that seeds the migration fails for them. EnvMatrixExclude.no_model_service = ["INPUT_CONFIG=model_service.yml.tmpl"] diff --git a/acceptance/bundle/invariant/no_drift/out.test.toml b/acceptance/bundle/invariant/no_drift/out.test.toml index a7c6da3e8ac..16ac514f8f2 100644 --- a/acceptance/bundle/invariant/no_drift/out.test.toml +++ b/acceptance/bundle/invariant/no_drift/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/test.toml b/acceptance/bundle/invariant/test.toml index 09d4507c261..7e51bc36e1e 100644 --- a/acceptance/bundle/invariant/test.toml +++ b/acceptance/bundle/invariant/test.toml @@ -25,6 +25,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/refschema/out.fields.txt b/acceptance/bundle/refschema/out.fields.txt index b4d9cbd22c8..3264827f9c1 100644 --- a/acceptance/bundle/refschema/out.fields.txt +++ b/acceptance/bundle/refschema/out.fields.txt @@ -461,6 +461,23 @@ resources.clusters.*.jdbc_port int REMOTE resources.clusters.*.kind compute.Kind ALL resources.clusters.*.last_restarted_time int64 REMOTE resources.clusters.*.last_state_loss_time int64 REMOTE +resources.clusters.*.libraries []compute.Library ALL +resources.clusters.*.libraries[*] compute.Library ALL +resources.clusters.*.libraries[*].cran *compute.RCranLibrary ALL +resources.clusters.*.libraries[*].cran.package string ALL +resources.clusters.*.libraries[*].cran.repo string ALL +resources.clusters.*.libraries[*].egg string ALL +resources.clusters.*.libraries[*].jar string ALL +resources.clusters.*.libraries[*].maven *compute.MavenLibrary ALL +resources.clusters.*.libraries[*].maven.coordinates string ALL +resources.clusters.*.libraries[*].maven.exclusions []string ALL +resources.clusters.*.libraries[*].maven.exclusions[*] string ALL +resources.clusters.*.libraries[*].maven.repo string ALL +resources.clusters.*.libraries[*].pypi *compute.PythonPyPiLibrary ALL +resources.clusters.*.libraries[*].pypi.package string ALL +resources.clusters.*.libraries[*].pypi.repo string ALL +resources.clusters.*.libraries[*].requirements string ALL +resources.clusters.*.libraries[*].whl string ALL resources.clusters.*.lifecycle *dresources.StateLifecycle REMOTE STATE resources.clusters.*.lifecycle *resources.LifecycleWithStarted INPUT resources.clusters.*.lifecycle resources.Lifecycle INPUT diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl new file mode 100644 index 00000000000..f5e3173e888 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl @@ -0,0 +1,23 @@ +bundle: + name: cluster-libraries-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +artifacts: + my_test_code: + type: whl + path: . + # Use 'python' because 'python3' does not exist in Windows virtualenvs. + build: python setup.py bdist_wheel + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - whl: ./dist/*.whl diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml b/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/output.txt b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt new file mode 100644 index 00000000000..eee0ba47348 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt @@ -0,0 +1,33 @@ + +=== Deploy a cluster with a local wheel library +OK: cluster created with wheel + +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} + +=== Badness: wheel code changes but version does not, so redeploy neither reinstalls nor restarts +>>> jq .plan["resources.clusters.mycluster"].action tmp.plan.json +"skip" + +OK: no restart on content-only change (known limitation) + +>>> print_requests.py //libraries/install + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/script b/acceptance/bundle/resources/clusters/libraries-content-change/script new file mode 100644 index 00000000000..747f9f68d45 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/script @@ -0,0 +1,30 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy a cluster with a local wheel library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with wheel" +trace print_requests.py //libraries/install + +# Change only the wheel's code, keeping version 0.0.1 so the built filename - and +# thus the uploaded workspace path - is byte-for-byte identical to the first deploy. +title "Badness: wheel code changes but version does not, so redeploy neither reinstalls nor restarts" +update_file.py my_test_code/__main__.py "Hello from my func" "Hello from my func v2" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan + +# The wheel path is unchanged, so the cluster plans as "skip" - the library change goes undetected and +# the stale wheel keeps running. +trace jq '.plan["resources.clusters.mycluster"].action' tmp.plan.json +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +cat LOG.redeploy | contains.py "!Restarting cluster" > /dev/null +printf '\n%s\n' "OK: no restart on content-only change (known limitation)" +trace print_requests.py //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare b/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare new file mode 100644 index 00000000000..31e6de1dbf5 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare @@ -0,0 +1,3 @@ +uv venv -q .venv +venv_activate +uv pip install -q --no-index setuptools diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/setup.py b/acceptance/bundle/resources/clusters/libraries-content-change/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/test.toml b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml new file mode 100644 index 00000000000..1abd9f3ecba --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml @@ -0,0 +1,14 @@ +Badness = "A local wheel whose contents change but whose version (and thus workspace path) does not is not detected in non-dev mode, so redeploy neither reinstalls it nor restarts the cluster; the stale wheel keeps running. See the TODO in bundle/direct/dresources/cluster.go DoUpdate." + +Cloud = true +CloudSlow = true +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", ".venv", "build", "dist", "my_test_code.egg-info", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl new file mode 100644 index 00000000000..40f63c9241c --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl @@ -0,0 +1,18 @@ +bundle: + name: cluster-libraries-repo-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests + repo: https://pypi.org/simple diff --git a/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml b/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-repo/output.txt b/acceptance/bundle/resources/clusters/libraries-repo/output.txt new file mode 100644 index 00000000000..03dfa68dc62 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/output.txt @@ -0,0 +1,21 @@ + +=== Deploy creates the cluster and installs the pypi library +OK: cluster created with pypi library + +=== Plan is a no-op after deploy: the repo round-trips +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Changing only the repo is planned as an update +>>> [CLI] bundle plan +update clusters.mycluster + +Plan: 0 to add, 1 to change, 0 to delete, 0 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-repo/script b/acceptance/bundle/resources/clusters/libraries-repo/script new file mode 100644 index 00000000000..c44c39e8b1f --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/script @@ -0,0 +1,21 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy creates the cluster and installs the pypi library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with pypi library" + +title "Plan is a no-op after deploy: the repo round-trips" +trace $CLI bundle plan + +title "Changing only the repo is planned as an update" +update_file.py databricks.yml "repo: https://pypi.org/simple" "repo: https://example.invalid/simple" +trace $CLI bundle plan diff --git a/acceptance/bundle/resources/clusters/libraries-repo/test.toml b/acceptance/bundle/resources/clusters/libraries-repo/test.toml new file mode 100644 index 00000000000..4724ab632f1 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = false + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl new file mode 100644 index 00000000000..3c9a4946638 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl @@ -0,0 +1,17 @@ +bundle: + name: cluster-libraries-restart-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/resources/clusters/libraries-restart/out.test.toml b/acceptance/bundle/resources/clusters/libraries-restart/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-restart/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-restart/output.txt b/acceptance/bundle/resources/clusters/libraries-restart/output.txt new file mode 100644 index 00000000000..df7c44549eb --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-restart/output.txt @@ -0,0 +1,31 @@ + +=== Install (create): libraries install on the fresh cluster with no restart +>>> print_requests.py //clusters/restart + +=== Update: adding a library restarts the running cluster +>>> print_requests.py //clusters/restart +{ + "method": "POST", + "path": "/api/2.1/clusters/restart", + "body": { + "cluster_id": "[UUID]" + } +} + +=== Delete: removing all libraries restarts the running cluster +>>> print_requests.py //clusters/restart +{ + "method": "POST", + "path": "/api/2.1/clusters/restart", + "body": { + "cluster_id": "[UUID]" + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-restart/script b/acceptance/bundle/resources/clusters/libraries-restart/script new file mode 100644 index 00000000000..21ac92e7312 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-restart/script @@ -0,0 +1,38 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); the captured restart request is the proof. +title "Install (create): libraries install on the fresh cluster with no restart" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.create +cat LOG.create | contains.py "Created clusters.mycluster" > /dev/null +# No restart request on create (empty below). +trace print_requests.py //clusters/restart + +title "Update: adding a library restarts the running cluster" +update_file.py databricks.yml " - pypi: + package: requests" " - pypi: + package: requests + - pypi: + package: six" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.update +cat LOG.update | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //clusters/restart + +title "Delete: removing all libraries restarts the running cluster" +update_file.py databricks.yml " libraries: + - pypi: + package: requests + - pypi: + package: six +" "" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.remove +cat LOG.remove | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //clusters/restart diff --git a/acceptance/bundle/resources/clusters/libraries-restart/test.toml b/acceptance/bundle/resources/clusters/libraries-restart/test.toml new file mode 100644 index 00000000000..472e3f3459e --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-restart/test.toml @@ -0,0 +1,14 @@ +Cloud = true +CloudSlow = true +# This test runs three full cluster lifecycles (create, add-library restart, remove-library +# restart); on slower clouds that exceeds the default 25m cloud timeout, so give it 50m. +TimeoutCloud = '50m' + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl new file mode 100644 index 00000000000..705177abe13 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl @@ -0,0 +1,19 @@ +bundle: + name: cluster-libraries-stopped-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + lifecycle: + started: false + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt new file mode 100644 index 00000000000..6319906394e --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt @@ -0,0 +1,14 @@ + +=== Deploy libraries on a started=false cluster: no restart +OK: created on stopped cluster, no restart + +=== Change the libraries and redeploy: cluster is stopped, so no restart is issued +OK: libraries changed on stopped cluster, no restart + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script new file mode 100644 index 00000000000..02f0b8eeed6 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script @@ -0,0 +1,25 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy libraries on a started=false cluster: no restart" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" "!Restarting cluster" > /dev/null +printf '\n%s\n' "OK: created on stopped cluster, no restart" + +title "Change the libraries and redeploy: cluster is stopped, so no restart is issued" +update_file.py databricks.yml " - pypi: + package: requests" " - pypi: + package: requests + - pypi: + package: numpy" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +cat LOG.redeploy | contains.py "Updated clusters.mycluster" "!Restarting cluster" > /dev/null +printf '\n%s\n' "OK: libraries changed on stopped cluster, no restart" diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml new file mode 100644 index 00000000000..4724ab632f1 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = false + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl new file mode 100644 index 00000000000..2364bafe42a --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl @@ -0,0 +1,25 @@ +bundle: + name: cluster-libraries-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +artifacts: + my_test_code: + type: whl + path: . + # Use 'python' because 'python3' does not exist in Windows virtualenvs. + build: python setup.py bdist_wheel + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - pypi: + package: requests + - whl: ./dist/*.whl diff --git a/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py b/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py b/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/resources/clusters/libraries/out.test.toml b/acceptance/bundle/resources/clusters/libraries/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries/output.txt b/acceptance/bundle/resources/clusters/libraries/output.txt new file mode 100644 index 00000000000..0528ead2ddc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/output.txt @@ -0,0 +1,65 @@ + +=== Deploy a cluster with a pypi and a local wheel library +>>> jq .plan["resources.clusters.mycluster"].new_state.value.libraries tmp.plan.json +[ + { + "pypi": { + "package": "requests" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } +] + +OK: cluster created with libraries + +=== Libraries installed via the Libraries API (wheel rewritten to its uploaded path) +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} + +=== Removing the wheel and redeploying uninstalls it and restarts the running cluster +>>> print_requests.py //libraries/uninstall //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} +{ + "method": "POST", + "path": "/api/2.1/clusters/restart", + "body": { + "cluster_id": "[UUID]" + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries/script b/acceptance/bundle/resources/clusters/libraries/script new file mode 100644 index 00000000000..b5402378019 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/script @@ -0,0 +1,29 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy a cluster with a pypi and a local wheel library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan + +# The plan carries the local wheel rewritten to its uploaded .internal/ path, so +# `bundle deploy --plan` installs it without rebuilding. +trace jq '.plan["resources.clusters.mycluster"].new_state.value.libraries' tmp.plan.json +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with libraries" + +title "Libraries installed via the Libraries API (wheel rewritten to its uploaded path)" +trace print_requests.py //libraries/install + +title "Removing the wheel and redeploying uninstalls it and restarts the running cluster" +update_file.py databricks.yml " - whl: ./dist/*.whl" "" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +cat LOG.redeploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/uninstall //clusters/restart diff --git a/acceptance/bundle/resources/clusters/libraries/script.prepare b/acceptance/bundle/resources/clusters/libraries/script.prepare new file mode 100644 index 00000000000..31e6de1dbf5 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/script.prepare @@ -0,0 +1,3 @@ +uv venv -q .venv +venv_activate +uv pip install -q --no-index setuptools diff --git a/acceptance/bundle/resources/clusters/libraries/setup.py b/acceptance/bundle/resources/clusters/libraries/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/resources/clusters/libraries/test.toml b/acceptance/bundle/resources/clusters/libraries/test.toml new file mode 100644 index 00000000000..ea6413633ba --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", ".venv", "build", "dist", "my_test_code.egg-info", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/bundle/config/mutator/validate_cluster_libraries.go b/bundle/config/mutator/validate_cluster_libraries.go new file mode 100644 index 00000000000..f13cd3be373 --- /dev/null +++ b/bundle/config/mutator/validate_cluster_libraries.go @@ -0,0 +1,43 @@ +package mutator + +import ( + "context" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config/engine" + "github.com/databricks/cli/libs/diag" +) + +type validateClusterLibraries struct { + engine engine.EngineType +} + +// ValidateClusterLibraries returns a mutator that errors when cluster libraries are used with +// the terraform deployment engine. Cluster libraries are only supported in direct deployment mode. +func ValidateClusterLibraries(e engine.EngineType) bundle.Mutator { + return &validateClusterLibraries{engine: e} +} + +func (m *validateClusterLibraries) Name() string { + return "ValidateClusterLibraries" +} + +func (m *validateClusterLibraries) Apply(_ context.Context, b *bundle.Bundle) diag.Diagnostics { + if m.engine.IsDirect() { + return nil + } + + var diags diag.Diagnostics + for key, cluster := range b.Config.Resources.Clusters { + if cluster == nil || len(cluster.Libraries) == 0 { + continue + } + path := "resources.clusters." + key + ".libraries" + diags = diags.Append(diag.Diagnostic{ + Severity: diag.Error, + Summary: "cluster libraries are only supported in direct deployment mode", + Locations: b.Config.GetLocations(path), + }) + } + return diags +} diff --git a/bundle/config/resources/clusters.go b/bundle/config/resources/clusters.go index aec5e886346..75b8f66b93d 100644 --- a/bundle/config/resources/clusters.go +++ b/bundle/config/resources/clusters.go @@ -19,6 +19,9 @@ type Cluster struct { // Lifecycle shadows BaseResource.Lifecycle to add support for lifecycle.started. Lifecycle *LifecycleWithStarted `json:"lifecycle,omitempty"` + // Libraries are installed via the Libraries API, not the cluster spec. + Libraries []compute.Library `json:"libraries,omitempty"` + Permissions []ClusterPermission `json:"permissions,omitempty"` } diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index a2348a5b6ea..0dd7d00e7cd 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -4,10 +4,12 @@ import ( "context" "errors" "fmt" + "strings" "time" "github.com/databricks/cli/bundle/config/resources" "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/structs/structpath" "github.com/databricks/cli/libs/utils" @@ -16,8 +18,12 @@ import ( "github.com/databricks/databricks-sdk-go/marshal" "github.com/databricks/databricks-sdk-go/retries" "github.com/databricks/databricks-sdk-go/service/compute" + "golang.org/x/sync/errgroup" ) +// librariesWaitTimeout bounds how long we poll for libraries to finish installing. +const librariesWaitTimeout = 15 * time.Minute + // clusterWaitTimeout bounds how long we poll for a cluster to reach its target // state (RUNNING/TERMINATED) after create, edit, or start/stop. Provisioning can // legitimately take longer than 15 minutes on capacity-constrained workspaces @@ -33,6 +39,10 @@ type ClusterState struct { compute.ClusterSpec Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` + + // Libraries are installed via the Libraries API, not the cluster spec, and managed as + // part of the cluster (see reconcileLibraries and the install in WaitAfterCreate). + Libraries []compute.Library `json:"libraries,omitempty"` } // Custom marshalers needed because embedded compute.ClusterSpec has its own MarshalJSON @@ -57,6 +67,10 @@ type ClusterRemote struct { compute.ClusterDetails ApplyPolicyDefaultValues bool `json:"apply_policy_default_values,omitempty"` Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` + + // Libraries is populated by DoRead from the Libraries cluster-status API (the cluster + // GET does not return installed libraries), so it participates in drift detection. + Libraries []compute.Library `json:"libraries,omitempty"` } func (r *ClusterRemote) UnmarshalJSON(b []byte) error { @@ -81,6 +95,7 @@ func (r *ResourceCluster) PrepareState(input *resources.Cluster) *ClusterState { s := &ClusterState{ ClusterSpec: input.ClusterSpec, Lifecycle: nil, + Libraries: input.Libraries, } if input.Lifecycle != nil && input.Lifecycle.Started != nil { s.Lifecycle = &StateLifecycle{Started: input.Lifecycle.Started} @@ -131,19 +146,36 @@ func (r *ResourceCluster) RemapState(input *ClusterRemote) *ClusterState { ForceSendFields: utils.FilterFields[compute.ClusterSpec](input.ForceSendFields), }, Lifecycle: input.Lifecycle, + Libraries: input.Libraries, } return spec } func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote, error) { - details, err := r.client.Clusters.GetByClusterId(ctx, id) - if err != nil { + var details *compute.ClusterDetails + var libraries []compute.Library + + // The cluster GET and the library-status GET are independent, so run them concurrently. + g, ctx := errgroup.WithContext(ctx) + g.Go(func() error { + var err error + details, err = r.client.Clusters.GetByClusterId(ctx, id) + return err + }) + g.Go(func() error { + var err error + libraries, err = r.readLibraries(ctx, id) + return err + }) + if err := g.Wait(); err != nil { return nil, err } + remote := &ClusterRemote{ ClusterDetails: *details, ApplyPolicyDefaultValues: false, Lifecycle: nil, + Libraries: libraries, } // The GET response carries apply_policy_default_values only under .spec (a snapshot of the // create/edit settings), not at the top level. Promote it so RemapState is a dumb copy. @@ -161,9 +193,29 @@ func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote default: remote.Lifecycle = nil } + return remote, nil } +// readLibraries returns the bundle-managed libraries installed on the cluster. +// https://docs.databricks.com/api/workspace/libraries/clusterstatus +func (r *ResourceCluster) readLibraries(ctx context.Context, id string) ([]compute.Library, error) { + statuses, err := r.client.Libraries.ClusterStatusByClusterId(ctx, id) + if err != nil { + return nil, err + } + var libraries []compute.Library + for _, s := range statuses.LibraryStatuses { + // Libraries set for all clusters via the UI are not managed by the bundle; a library + // pending uninstall on restart is on its way out. Skip both. + if s.Library == nil || s.IsLibraryForAllClusters || s.Status == compute.LibraryInstallStatusUninstallOnRestart { + continue + } + libraries = append(libraries, *s.Library) + } + return libraries, nil +} + func (r *ResourceCluster) DoCreate(ctx context.Context, config *ClusterState) (string, *ClusterRemote, error) { wait, err := r.client.Clusters.Create(ctx, makeCreateCluster(&config.ClusterSpec)) if err != nil { @@ -172,14 +224,28 @@ func (r *ResourceCluster) DoCreate(ctx context.Context, config *ClusterState) (s return wait.ClusterId, nil, nil } -// hasClusterChanges reports whether the plan entry contains any Update changes -// to fields that belong to the Cluster Edit API (i.e., not lifecycle-only fields). -func hasClusterChanges(entry *PlanEntry) bool { - return entry.Changes.HasChangeExcept("lifecycle", "lifecycle.started") +// hasClusterSpecChanges reports whether the plan entry changes a Cluster Edit API field — +// anything other than lifecycle (start/stop) and libraries (handled via the Libraries API). +func hasClusterSpecChanges(entry *PlanEntry) bool { + for field, change := range entry.Changes { + if change.Action == deployplan.Skip { + continue + } + node, err := structpath.ParsePath(field) + if err != nil { + continue + } + top, _ := node.Prefix(1).StringKey() + if top != "lifecycle" && top != "libraries" { + return true + } + } + return false } func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *ClusterState, entry *PlanEntry) (*ClusterRemote, error) { - if hasClusterChanges(entry) { + edited := hasClusterSpecChanges(entry) + if edited { // Same retry as in TF provider logic // https://github.com/databricks/terraform-provider-databricks/blob/3eecd0f90cf99d7777e79a3d03c41f9b2aafb004/clusters/resource_cluster.go#L624 _, err := retries.Poll(ctx, clusterWaitTimeout, func() (*compute.WaitGetClusterRunning[struct{}], *retries.Err) { @@ -200,6 +266,25 @@ func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *Clust } } + // TODO: a local whl/jar whose workspace path is unchanged but whose contents + // changed (same name+version, non-dev mode) is not detected here, so no restart fires. + // Dev mode handles this via patchwheel (a source-derived version bump). + if entry.Changes.HasChange(librariesPath) { + if err := r.reconcileLibraries(ctx, id, config.Libraries, entry); err != nil { + return nil, err + } + // A cluster edit restarts the cluster on its own, which applies the library change. + // Without an edit we restart so the change takes effect on a running cluster. + if !edited { + if err := r.restartIfRunning(ctx, id); err != nil { + return nil, err + } + if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { + return nil, err + } + } + } + if config.Lifecycle == nil || config.Lifecycle.Started == nil { return nil, nil } @@ -244,6 +329,21 @@ func (r *ResourceCluster) WaitAfterCreate(ctx context.Context, id string, config return nil, err } + // Install libraries once the cluster is running. A freshly-created cluster has no + // attached sessions, so the install applies live without a restart. + // TODO: Wait is supposed to be side effect free, but in this case moving it to + // the create will cause a wait for libraries to be installed befor the cluster is installed. + // this increases the risk of losing the cluster. This is a limitation + if len(config.Libraries) > 0 { + err = r.client.Libraries.Install(ctx, compute.InstallLibraries{ClusterId: id, Libraries: config.Libraries}) + if err != nil { + return nil, err + } + if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { + return nil, err + } + } + if config.Lifecycle != nil && config.Lifecycle.Started != nil && !*config.Lifecycle.Started { // started=false: terminate the cluster after it reaches RUNNING. // Note: Delete terminates the cluster; permanent removal is a separate API (permanent-delete). @@ -426,3 +526,171 @@ func makeEditCluster(id string, config *compute.ClusterSpec) compute.EditCluster return edit } + +// librariesPath is the ClusterState path of the libraries slice, used to detect library changes. +var librariesPath = structpath.MustParsePath("libraries") + +// KeyedSlices compares libraries by identity rather than index so reordering (or the +// read-order the status API returns) does not produce phantom diffs. +func (*ResourceCluster) KeyedSlices() map[string]any { + return map[string]any{"libraries": libraryKey} +} + +// reconcileLibraries uninstalls libraries dropped from config and installs the desired set. +// The Libraries API exposes install and uninstall as separate endpoints, so this is two calls. +func (r *ResourceCluster) reconcileLibraries(ctx context.Context, id string, desired []compute.Library, entry *PlanEntry) error { + removed := removedLibraries(desired, entry) + if len(removed) > 0 { + err := r.client.Libraries.Uninstall(ctx, compute.UninstallLibraries{ClusterId: id, Libraries: removed}) + if err != nil { + return err + } + } + if len(desired) > 0 { + return r.client.Libraries.Install(ctx, compute.InstallLibraries{ClusterId: id, Libraries: desired}) + } + return nil +} + +// removedLibraries returns libraries present in the remote state but absent from the desired set. +func removedLibraries(desired []compute.Library, entry *PlanEntry) []compute.Library { + remote, ok := entry.RemoteState.(*ClusterRemote) + if !ok || remote == nil { + return nil + } + desiredKeys := make(map[string]struct{}, len(desired)) + for _, l := range desired { + desiredKeys[libraryMapKey(l)] = struct{}{} + } + var result []compute.Library + for _, l := range remote.Libraries { + if _, ok := desiredKeys[libraryMapKey(l)]; !ok { + result = append(result, l) + } + } + return result +} + +// restartIfRunning restarts the cluster so a library change takes effect, but only when it is +// running: a stopped cluster applies pending install/uninstall on its next start. It waits for +// the cluster to return to RUNNING before returning. +func (r *ResourceCluster) restartIfRunning(ctx context.Context, id string) error { + details, err := r.client.Clusters.GetByClusterId(ctx, id) + if err != nil { + return err + } + if details.State != compute.StateRunning { + log.Debugf(ctx, "cluster %s is not running (%s); skipping restart for library change", id, details.State) + return nil + } + cmdio.LogString(ctx, fmt.Sprintf("Restarting cluster %s because its libraries changed", id)) + wait, err := r.client.Clusters.Restart(ctx, compute.RestartCluster{ClusterId: id, RestartUser: "", ForceSendFields: nil}) + if err != nil { + return err + } + _, err = wait.GetWithTimeout(clusterWaitTimeout) + return err +} + +// waitForInstall polls until every desired library reaches a terminal installed state. It returns +// early without waiting when the cluster is not running: installs only progress on a running +// cluster and are queued until it next starts. +func (r *ResourceCluster) waitForInstall(ctx context.Context, id string, desired []compute.Library) error { + if len(desired) == 0 { + return nil + } + details, err := r.client.Clusters.GetByClusterId(ctx, id) + if err != nil { + return err + } + if details.State != compute.StateRunning { + log.Debugf(ctx, "cluster %s is not running (%s); skipping wait for library installation", id, details.State) + return nil + } + + desiredKeys := make(map[string]struct{}, len(desired)) + for _, l := range desired { + typ, val := libraryWaitKey(l) + if typ == "" { + // Unknown library type: it can't be matched in cluster-status, so don't wait for it. + continue + } + desiredKeys[typ+"="+val] = struct{}{} + } + + _, err = retries.Poll(ctx, librariesWaitTimeout, func() (*struct{}, *retries.Err) { + statuses, err := r.client.Libraries.ClusterStatusByClusterId(ctx, id) + if err != nil { + return nil, retries.Halt(err) + } + pending := len(desiredKeys) + for _, s := range statuses.LibraryStatuses { + if s.Library == nil { + continue + } + if _, ok := desiredKeys[libraryWaitMapKey(*s.Library)]; !ok { + continue + } + switch s.Status { + case compute.LibraryInstallStatusFailed: + return nil, retries.Halt(fmt.Errorf("library %s failed to install: %s", libraryWaitMapKey(*s.Library), strings.Join(s.Messages, "; "))) + case compute.LibraryInstallStatusInstalled, compute.LibraryInstallStatusSkipped, compute.LibraryInstallStatusRestored: + pending-- + case compute.LibraryInstallStatusPending, compute.LibraryInstallStatusResolving, compute.LibraryInstallStatusInstalling, compute.LibraryInstallStatusUninstallOnRestart: + // Still in progress (or being removed); keep polling. + } + } + if pending > 0 { + return nil, retries.Continues(fmt.Sprintf("waiting for %d librar(ies) to install on cluster %s", pending, id)) + } + return &struct{}{}, nil + }) + return err +} + +// libraryWaitKey identifies a library by its primary field only, used to match install-status reports. +func libraryWaitKey(l compute.Library) (string, string) { + switch { + case l.Whl != "": + return "whl", l.Whl + case l.Jar != "": + return "jar", l.Jar + case l.Egg != "": + return "egg", l.Egg + case l.Requirements != "": + return "requirements", l.Requirements + case l.Pypi != nil: + return "pypi", l.Pypi.Package + case l.Maven != nil: + return "maven", l.Maven.Coordinates + case l.Cran != nil: + return "cran", l.Cran.Package + } + return "", "" +} + +// libraryKey extends libraryWaitKey with repo/exclusions so a repo-only change is detected. +func libraryKey(l compute.Library) (string, string) { + typ, id := libraryWaitKey(l) + switch { + case l.Pypi != nil: + return typ, id + ";" + l.Pypi.Repo + case l.Maven != nil: + return typ, id + ";" + l.Maven.Repo + ";" + strings.Join(l.Maven.Exclusions, ",") + case l.Cran != nil: + return typ, id + ";" + l.Cran.Repo + } + return typ, id +} + +// libraryMapKey flattens libraryKey into a single string for map lookups. +func libraryMapKey(l compute.Library) string { + f, v := libraryKey(l) + return f + "=" + v +} + +// libraryWaitMapKey flattens libraryWaitKey into a single string for map lookups. +func libraryWaitMapKey(l compute.Library) string { + f, v := libraryWaitKey(l) + return f + "=" + v +} diff --git a/bundle/internal/schema/annotations.yml b/bundle/internal/schema/annotations.yml index 11f39b90d1b..d0ce96db7eb 100644 --- a/bundle/internal/schema/annotations.yml +++ b/bundle/internal/schema/annotations.yml @@ -624,6 +624,9 @@ resources: notebook_path: "./src/my_notebook.py" ``` "$fields": + "libraries": + "description": |- + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. "lifecycle": "description": |- Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. diff --git a/bundle/internal/validation/generated/required_fields.go b/bundle/internal/validation/generated/required_fields.go index 5617f9f5ffa..41e2b93687f 100644 --- a/bundle/internal/validation/generated/required_fields.go +++ b/bundle/internal/validation/generated/required_fields.go @@ -56,6 +56,9 @@ var RequiredFields = map[string][]string{ "resources.clusters.*.init_scripts[*].s3": {"destination"}, "resources.clusters.*.init_scripts[*].volumes": {"destination"}, "resources.clusters.*.init_scripts[*].workspace": {"destination"}, + "resources.clusters.*.libraries[*].cran": {"package"}, + "resources.clusters.*.libraries[*].maven": {"coordinates"}, + "resources.clusters.*.libraries[*].pypi": {"package"}, "resources.clusters.*.permissions[*]": {"level"}, "resources.clusters.*.workload_type": {"clients"}, diff --git a/bundle/libraries/expand_glob_references.go b/bundle/libraries/expand_glob_references.go index 720142fe6d7..ab1da3df68d 100644 --- a/bundle/libraries/expand_glob_references.go +++ b/bundle/libraries/expand_glob_references.go @@ -198,6 +198,13 @@ var pipelineEnvDepsPattern = dyn.NewPattern( dyn.Key("dependencies"), ) +var clusterLibrariesPattern = dyn.NewPattern( + dyn.Key("resources"), + dyn.Key("clusters"), + dyn.AnyKey(), + dyn.Key("libraries"), +) + func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { expanders := []expandPattern{ { @@ -216,6 +223,10 @@ func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { pattern: pipelineEnvDepsPattern, fn: expandEnvironmentDeps, }, + { + pattern: clusterLibrariesPattern, + fn: expandLibraries, + }, } var diags diag.Diagnostics diff --git a/bundle/libraries/remote_path.go b/bundle/libraries/remote_path.go index bc23bca4446..d45e8ff4c7e 100644 --- a/bundle/libraries/remote_path.go +++ b/bundle/libraries/remote_path.go @@ -139,6 +139,8 @@ func collectLocalLibraries(b *bundle.Bundle) (map[string][]LocationToUpdate, err taskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), envDepsPattern.Append(dyn.AnyIndex()), pipelineEnvDepsPattern.Append(dyn.AnyIndex()), // The AI Runtime task's code_source_path is a local archive (typically an diff --git a/bundle/libraries/same_name_libraries.go b/bundle/libraries/same_name_libraries.go index 49776fbd8c9..8fb140d7aa4 100644 --- a/bundle/libraries/same_name_libraries.go +++ b/bundle/libraries/same_name_libraries.go @@ -17,6 +17,8 @@ var patterns = []dyn.Pattern{ taskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), envDepsPattern.Append(dyn.AnyIndex()), pipelineEnvDepsPattern.Append(dyn.AnyIndex()), } diff --git a/bundle/libraries/switch_to_patched_wheels.go b/bundle/libraries/switch_to_patched_wheels.go index 56250d713a7..3c5ff184a97 100644 --- a/bundle/libraries/switch_to_patched_wheels.go +++ b/bundle/libraries/switch_to_patched_wheels.go @@ -79,6 +79,22 @@ func (c switchToPatchedWheels) Apply(ctx context.Context, b *bundle.Bundle) diag } } + // Update resources.clusters.*.libraries[*].whl + for clusterName, clusterRef := range b.Config.Resources.Clusters { + if clusterRef == nil { + continue + } + for libInd, lib := range clusterRef.Libraries { + repl := replacements[lib.Whl] + if repl != "" { + log.Debugf(ctx, "Updating resources.clusters.%s.libraries[%d].whl from %s to %s", clusterName, libInd, lib.Whl, repl) + clusterRef.Libraries[libInd].Whl = repl + } else { + log.Debugf(ctx, "Not updating resources.clusters.%s.libraries[%d].whl from %s. Available replacements: %v", clusterName, libInd, lib.Whl, slices.Sorted(maps.Keys(replacements))) + } + } + } + return nil } diff --git a/bundle/phases/plan.go b/bundle/phases/plan.go index aee481b2b14..f937e2e91c9 100644 --- a/bundle/phases/plan.go +++ b/bundle/phases/plan.go @@ -28,6 +28,7 @@ func PreDeployChecks(ctx context.Context, b *bundle.Bundle, isPlan bool, engine mutator.ValidateGitDetails(), mutator.ValidateDirectOnlyResources(engine), mutator.ValidateLifecycleStarted(engine), + mutator.ValidateClusterLibraries(engine), mutator.ValidateCascadeOnDestroy(engine), statemgmt.CheckRunningResource(engine), ) diff --git a/bundle/schema/jsonschema.json b/bundle/schema/jsonschema.json index d6b7dcf0b32..79b576dc88a 100644 --- a/bundle/schema/jsonschema.json +++ b/bundle/schema/jsonschema.json @@ -538,6 +538,10 @@ "$ref": "#/$defs/github.com/databricks/databricks-sdk-go/service/compute.Kind", "x-databricks-launch-stage": "GA" }, + "libraries": { + "description": "A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode.", + "$ref": "#/$defs/slice/github.com/databricks/databricks-sdk-go/service/compute.Library" + }, "lifecycle": { "description": "Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed.", "$ref": "#/$defs/github.com/databricks/cli/bundle/config/resources.LifecycleWithStarted" diff --git a/bundle/terraform_dabs_map/generated.go b/bundle/terraform_dabs_map/generated.go index fc245721c8a..c1d2430d36e 100644 --- a/bundle/terraform_dabs_map/generated.go +++ b/bundle/terraform_dabs_map/generated.go @@ -6,7 +6,8 @@ package terraform_dabs_map // alerts / databricks_alert_v2: 3 tf-only // apps / databricks_app: 6 dabs-only // apps / databricks_app: 1 tf-only -// clusters / databricks_cluster: 26 tf-only +// clusters / databricks_cluster: 1 renames +// clusters / databricks_cluster: 11 tf-only // dashboards / databricks_dashboard: 2 tf-only // database_instances / databricks_database_instance: 1 tf-only // experiments / databricks_mlflow_experiment: 1 tf-only @@ -34,6 +35,9 @@ package terraform_dabs_map // TerraformToDABsFieldMap maps DABs group name → nested TF segments → DABs segment name. // Navigate using TF field name segments; DABs is the corresponding DABs name when it differs. var TerraformToDABsFieldMap = map[string]RenameTree{ + "clusters": { + "library": {NewName: "libraries"}, + }, "jobs": { "environment": {NewName: "environments"}, "git_source": {Children: RenameTree{ @@ -168,27 +172,8 @@ var TerraformOnlyFields = map[string]FieldSet{ }, "idempotency_token": {}, "is_pinned": {}, - "library": { - "cran": { - "package": {}, // databricks_cluster.*.library.cran.package - "repo": {}, // databricks_cluster.*.library.cran.repo - }, - "egg": {}, // databricks_cluster.*.library.egg - "jar": {}, // databricks_cluster.*.library.jar - "maven": { - "coordinates": {}, // databricks_cluster.*.library.maven.coordinates - "exclusions": {}, // databricks_cluster.*.library.maven.exclusions - "repo": {}, // databricks_cluster.*.library.maven.repo - }, - "pypi": { - "package": {}, // databricks_cluster.*.library.pypi.package - "repo": {}, // databricks_cluster.*.library.pypi.repo - }, - "requirements": {}, // databricks_cluster.*.library.requirements - "whl": {}, // databricks_cluster.*.library.whl - }, - "no_wait": {}, - "url": {}, + "no_wait": {}, + "url": {}, }, "dashboards": { "dashboard_change_detected": {}, @@ -571,6 +556,9 @@ var TerraformOnlyFields = map[string]FieldSet{ // DABsToTerraformRenameMap maps DABs group name → nested DABs segments → TF segment name. // Navigate using DABs field name segments; NewName is the TF name when it differs. var DABsToTerraformRenameMap = map[string]RenameTree{ + "clusters": { + "libraries": {NewName: "library"}, + }, "jobs": { "environments": {NewName: "environment"}, "git_source": {Children: RenameTree{ diff --git a/libs/testserver/clusters.go b/libs/testserver/clusters.go index e0a046031e6..e24be06216d 100644 --- a/libs/testserver/clusters.go +++ b/libs/testserver/clusters.go @@ -244,6 +244,35 @@ func (s *FakeWorkspace) ClustersStart(req Request) any { return Response{} } +// ClustersRestart restarts a running cluster. It moves the cluster back to PENDING so the next +// ClustersGet transitions it to RUNNING, mirroring how a real restart cycles through states, and +// clears the venv cache like ClustersEdit (a restart rebuilds the library environment). +func (s *FakeWorkspace) ClustersRestart(req Request) any { + var request compute.RestartCluster + if err := json.Unmarshal(req.Body, &request); err != nil { + return Response{ + StatusCode: 400, + Body: fmt.Sprintf("request parsing error: %s", err), + } + } + defer s.LockUnlock()() + + cluster, ok := s.Clusters[request.ClusterId] + if !ok { + return Response{StatusCode: 404} + } + + cluster.State = compute.StatePending + s.Clusters[request.ClusterId] = cluster + + if env, ok := s.clusterVenvs[request.ClusterId]; ok { + os.RemoveAll(env.dir) + delete(s.clusterVenvs, request.ClusterId) + } + + return Response{} +} + func (s *FakeWorkspace) ClustersPermanentDelete(req Request) any { var request compute.PermanentDeleteCluster if err := json.Unmarshal(req.Body, &request); err != nil { diff --git a/libs/testserver/fake_workspace.go b/libs/testserver/fake_workspace.go index 44d6ccd1889..b73803751b6 100644 --- a/libs/testserver/fake_workspace.go +++ b/libs/testserver/fake_workspace.go @@ -208,6 +208,7 @@ type FakeWorkspace struct { ModelRegistryModels map[string]ml.Model ModelRegistryModelIDs map[string]string // model name -> numeric ID Clusters map[string]compute.ClusterDetails + ClusterLibraries map[string][]compute.Library // cluster id -> installed libraries InstancePools map[string]compute.GetInstancePool ClusterPolicies map[string]compute.Policy Catalogs map[string]catalog.CatalogInfo @@ -549,7 +550,8 @@ func NewFakeWorkspace(url, token string) *FakeWorkspace { SingleUserName: TestUser.UserName, }, }, - InstancePools: map[string]compute.GetInstancePool{}, + InstancePools: map[string]compute.GetInstancePool{}, + ClusterLibraries: map[string][]compute.Library{}, ClusterPolicies: map[string]compute.Policy{ // Seeded so the stateful list keeps backing the variable-lookup tests // (e.g. acceptance/bundle/variables/env_overrides resolves these by name). diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 750f220bf33..41750d6802d 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -1030,10 +1030,27 @@ func AddDefaultHandlers(server *Server) { return req.Workspace.ClustersStart(req) }) + server.Handle("POST", "/api/2.1/clusters/restart", func(req Request) any { + return req.Workspace.ClustersRestart(req) + }) + server.Handle("POST", "/api/2.1/clusters/permanent-delete", func(req Request) any { return req.Workspace.ClustersPermanentDelete(req) }) + // Cluster libraries: + server.Handle("POST", "/api/2.0/libraries/install", func(req Request) any { + return req.Workspace.LibrariesInstall(req) + }) + + server.Handle("POST", "/api/2.0/libraries/uninstall", func(req Request) any { + return req.Workspace.LibrariesUninstall(req) + }) + + server.Handle("GET", "/api/2.0/libraries/cluster-status", func(req Request) any { + return req.Workspace.LibrariesClusterStatus(req, req.URL.Query().Get("cluster_id")) + }) + // MLflow Experiments: server.Handle("GET", "/api/2.0/mlflow/experiments/get", func(req Request) any { experimentId := req.URL.Query().Get("experiment_id") diff --git a/libs/testserver/libraries.go b/libs/testserver/libraries.go new file mode 100644 index 00000000000..63042ca8e66 --- /dev/null +++ b/libs/testserver/libraries.go @@ -0,0 +1,87 @@ +package testserver + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + + "github.com/databricks/databricks-sdk-go/service/compute" +) + +func (s *FakeWorkspace) LibrariesInstall(req Request) any { + var request compute.InstallLibraries + if err := json.Unmarshal(req.Body, &request); err != nil { + return Response{StatusCode: http.StatusBadRequest, Body: fmt.Sprintf("request parsing error: %s", err)} + } + + defer s.LockUnlock()() + + if _, ok := s.Clusters[request.ClusterId]; !ok { + return Response{StatusCode: http.StatusNotFound} + } + + // Install is additive and idempotent: installing an already-present library is a no-op. + installed := s.ClusterLibraries[request.ClusterId] + for _, lib := range request.Libraries { + if !containsLibrary(installed, lib) { + installed = append(installed, lib) + } + } + s.ClusterLibraries[request.ClusterId] = installed + + return Response{} +} + +func (s *FakeWorkspace) LibrariesUninstall(req Request) any { + var request compute.UninstallLibraries + if err := json.Unmarshal(req.Body, &request); err != nil { + return Response{StatusCode: http.StatusBadRequest, Body: fmt.Sprintf("request parsing error: %s", err)} + } + + defer s.LockUnlock()() + + installed := s.ClusterLibraries[request.ClusterId] + remaining := make([]compute.Library, 0, len(installed)) + for _, lib := range installed { + if !containsLibrary(request.Libraries, lib) { + remaining = append(remaining, lib) + } + } + s.ClusterLibraries[request.ClusterId] = remaining + + return Response{} +} + +func (s *FakeWorkspace) LibrariesClusterStatus(req Request, clusterId string) any { + defer s.LockUnlock()() + + if _, ok := s.Clusters[clusterId]; !ok { + return Response{StatusCode: http.StatusNotFound} + } + + installed := s.ClusterLibraries[clusterId] + statuses := make([]compute.LibraryFullStatus, 0, len(installed)) + for i := range installed { + statuses = append(statuses, compute.LibraryFullStatus{ + Library: &installed[i], + Status: compute.LibraryInstallStatusInstalled, + }) + } + + return Response{ + Body: compute.ClusterLibraryStatuses{ + ClusterId: clusterId, + LibraryStatuses: statuses, + }, + } +} + +func containsLibrary(libs []compute.Library, target compute.Library) bool { + for _, l := range libs { + if reflect.DeepEqual(l, target) { + return true + } + } + return false +} diff --git a/python/databricks/bundles/clusters/__init__.py b/python/databricks/bundles/clusters/__init__.py index a24c8ac4fdc..0ccecb208b0 100644 --- a/python/databricks/bundles/clusters/__init__.py +++ b/python/databricks/bundles/clusters/__init__.py @@ -61,6 +61,9 @@ "InitScriptInfoParam", "Kind", "KindParam", + "Library", + "LibraryDict", + "LibraryParam", "LifecycleWithStarted", "LifecycleWithStartedDict", "LifecycleWithStartedParam", @@ -70,9 +73,18 @@ "LogAnalyticsInfo", "LogAnalyticsInfoDict", "LogAnalyticsInfoParam", + "MavenLibrary", + "MavenLibraryDict", + "MavenLibraryParam", "NodeTypeFlexibility", "NodeTypeFlexibilityDict", "NodeTypeFlexibilityParam", + "PythonPyPiLibrary", + "PythonPyPiLibraryDict", + "PythonPyPiLibraryParam", + "RCranLibrary", + "RCranLibraryDict", + "RCranLibraryParam", "RuntimeEngine", "RuntimeEngineParam", "S3StorageInfo", @@ -193,6 +205,11 @@ InitScriptInfoParam, ) from databricks.bundles.clusters._models.kind import Kind, KindParam +from databricks.bundles.clusters._models.library import ( + Library, + LibraryDict, + LibraryParam, +) from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, LifecycleWithStartedDict, @@ -208,11 +225,26 @@ LogAnalyticsInfoDict, LogAnalyticsInfoParam, ) +from databricks.bundles.clusters._models.maven_library import ( + MavenLibrary, + MavenLibraryDict, + MavenLibraryParam, +) from databricks.bundles.clusters._models.node_type_flexibility import ( NodeTypeFlexibility, NodeTypeFlexibilityDict, NodeTypeFlexibilityParam, ) +from databricks.bundles.clusters._models.python_py_pi_library import ( + PythonPyPiLibrary, + PythonPyPiLibraryDict, + PythonPyPiLibraryParam, +) +from databricks.bundles.clusters._models.r_cran_library import ( + RCranLibrary, + RCranLibraryDict, + RCranLibraryParam, +) from databricks.bundles.clusters._models.runtime_engine import ( RuntimeEngine, RuntimeEngineParam, diff --git a/python/databricks/bundles/clusters/_models/cluster.py b/python/databricks/bundles/clusters/_models/cluster.py index 3e517975100..042a2c14a52 100644 --- a/python/databricks/bundles/clusters/_models/cluster.py +++ b/python/databricks/bundles/clusters/_models/cluster.py @@ -44,6 +44,7 @@ InitScriptInfoParam, ) from databricks.bundles.clusters._models.kind import Kind, KindParam +from databricks.bundles.clusters._models.library import Library, LibraryParam from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, LifecycleWithStartedParam, @@ -242,6 +243,11 @@ class Cluster(Resource): By using the [simple form](https://docs.databricks.com/compute/simple-form.html), your clusters are automatically using `kind = CLASSIC_PREVIEW`. """ + libraries: VariableOrList[Library] = field(default_factory=list) + """ + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. + """ + lifecycle: VariableOrOptional[LifecycleWithStarted] = None """ Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. @@ -530,6 +536,11 @@ class ClusterDict(TypedDict, total=False): By using the [simple form](https://docs.databricks.com/compute/simple-form.html), your clusters are automatically using `kind = CLASSIC_PREVIEW`. """ + libraries: VariableOrList[LibraryParam] + """ + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. + """ + lifecycle: VariableOrOptional[LifecycleWithStartedParam] """ Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. diff --git a/python/databricks/bundles/clusters/_models/library.py b/python/databricks/bundles/clusters/_models/library.py new file mode 100644 index 00000000000..8961f8fe744 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/library.py @@ -0,0 +1,134 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.clusters._models.maven_library import ( + MavenLibrary, + MavenLibraryParam, +) +from databricks.bundles.clusters._models.python_py_pi_library import ( + PythonPyPiLibrary, + PythonPyPiLibraryParam, +) +from databricks.bundles.clusters._models.r_cran_library import ( + RCranLibrary, + RCranLibraryParam, +) +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class Library: + """""" + + cran: VariableOrOptional[RCranLibrary] = None + """ + Specification of a CRAN library to be installed as part of the library + """ + + egg: VariableOrOptional[str] = None + """ + [DEPRECATED] Deprecated. URI of the egg library to install. Installing Python egg files is deprecated and is not supported in Databricks Runtime 14.0 and above. + """ + + jar: VariableOrOptional[str] = None + """ + URI of the JAR library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "jar": "/Workspace/path/to/library.jar" }`, `{ "jar" : "/Volumes/path/to/library.jar" }` or + `{ "jar": "s3://my-bucket/library.jar" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + maven: VariableOrOptional[MavenLibrary] = None + """ + Specification of a maven library to be installed. For example: + `{ "coordinates": "org.jsoup:jsoup:1.7.2" }` + """ + + pypi: VariableOrOptional[PythonPyPiLibrary] = None + """ + Specification of a PyPi library to be installed. For example: + `{ "package": "simplejson" }` + """ + + requirements: VariableOrOptional[str] = None + """ + URI of the requirements.txt file to install. Only Workspace paths and Unity Catalog Volumes paths are supported. + For example: `{ "requirements": "/Workspace/path/to/requirements.txt" }` or `{ "requirements" : "/Volumes/path/to/requirements.txt" }` + """ + + whl: VariableOrOptional[str] = None + """ + URI of the wheel library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "whl": "/Workspace/path/to/library.whl" }`, `{ "whl" : "/Volumes/path/to/library.whl" }` or + `{ "whl": "s3://my-bucket/library.whl" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + @classmethod + def from_dict(cls, value: "LibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "LibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class LibraryDict(TypedDict, total=False): + """""" + + cran: VariableOrOptional[RCranLibraryParam] + """ + Specification of a CRAN library to be installed as part of the library + """ + + egg: VariableOrOptional[str] + """ + [DEPRECATED] Deprecated. URI of the egg library to install. Installing Python egg files is deprecated and is not supported in Databricks Runtime 14.0 and above. + """ + + jar: VariableOrOptional[str] + """ + URI of the JAR library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "jar": "/Workspace/path/to/library.jar" }`, `{ "jar" : "/Volumes/path/to/library.jar" }` or + `{ "jar": "s3://my-bucket/library.jar" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + maven: VariableOrOptional[MavenLibraryParam] + """ + Specification of a maven library to be installed. For example: + `{ "coordinates": "org.jsoup:jsoup:1.7.2" }` + """ + + pypi: VariableOrOptional[PythonPyPiLibraryParam] + """ + Specification of a PyPi library to be installed. For example: + `{ "package": "simplejson" }` + """ + + requirements: VariableOrOptional[str] + """ + URI of the requirements.txt file to install. Only Workspace paths and Unity Catalog Volumes paths are supported. + For example: `{ "requirements": "/Workspace/path/to/requirements.txt" }` or `{ "requirements" : "/Volumes/path/to/requirements.txt" }` + """ + + whl: VariableOrOptional[str] + """ + URI of the wheel library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "whl": "/Workspace/path/to/library.whl" }`, `{ "whl" : "/Volumes/path/to/library.whl" }` or + `{ "whl": "s3://my-bucket/library.whl" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + +LibraryParam = LibraryDict | Library diff --git a/python/databricks/bundles/clusters/_models/maven_library.py b/python/databricks/bundles/clusters/_models/maven_library.py new file mode 100644 index 00000000000..25be1599c28 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/maven_library.py @@ -0,0 +1,72 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import ( + VariableOr, + VariableOrList, + VariableOrOptional, +) + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class MavenLibrary: + """""" + + coordinates: VariableOr[str] + """ + Gradle-style maven coordinates. For example: "org.jsoup:jsoup:1.7.2". + """ + + exclusions: VariableOrList[str] = field(default_factory=list) + """ + List of dependences to exclude. For example: `["slf4j:slf4j", "*:hadoop-client"]`. + + Maven dependency exclusions: + https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html. + """ + + repo: VariableOrOptional[str] = None + """ + Maven repo to install the Maven package from. If omitted, both Maven Central Repository + and Spark Packages are searched. + """ + + @classmethod + def from_dict(cls, value: "MavenLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "MavenLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class MavenLibraryDict(TypedDict, total=False): + """""" + + coordinates: VariableOr[str] + """ + Gradle-style maven coordinates. For example: "org.jsoup:jsoup:1.7.2". + """ + + exclusions: VariableOrList[str] + """ + List of dependences to exclude. For example: `["slf4j:slf4j", "*:hadoop-client"]`. + + Maven dependency exclusions: + https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html. + """ + + repo: VariableOrOptional[str] + """ + Maven repo to install the Maven package from. If omitted, both Maven Central Repository + and Spark Packages are searched. + """ + + +MavenLibraryParam = MavenLibraryDict | MavenLibrary diff --git a/python/databricks/bundles/clusters/_models/python_py_pi_library.py b/python/databricks/bundles/clusters/_models/python_py_pi_library.py new file mode 100644 index 00000000000..037c2029f50 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/python_py_pi_library.py @@ -0,0 +1,54 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOr, VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class PythonPyPiLibrary: + """""" + + package: VariableOr[str] + """ + The name of the pypi package to install. An optional exact version specification is also + supported. Examples: "simplejson" and "simplejson==3.8.0". + """ + + repo: VariableOrOptional[str] = None + """ + The repository where the package can be found. If not specified, the default pip index is + used. + """ + + @classmethod + def from_dict(cls, value: "PythonPyPiLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "PythonPyPiLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class PythonPyPiLibraryDict(TypedDict, total=False): + """""" + + package: VariableOr[str] + """ + The name of the pypi package to install. An optional exact version specification is also + supported. Examples: "simplejson" and "simplejson==3.8.0". + """ + + repo: VariableOrOptional[str] + """ + The repository where the package can be found. If not specified, the default pip index is + used. + """ + + +PythonPyPiLibraryParam = PythonPyPiLibraryDict | PythonPyPiLibrary diff --git a/python/databricks/bundles/clusters/_models/r_cran_library.py b/python/databricks/bundles/clusters/_models/r_cran_library.py new file mode 100644 index 00000000000..0bd2c4d5296 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/r_cran_library.py @@ -0,0 +1,50 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOr, VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class RCranLibrary: + """""" + + package: VariableOr[str] + """ + The name of the CRAN package to install. + """ + + repo: VariableOrOptional[str] = None + """ + The repository where the package can be found. If not specified, the default CRAN repo is used. + """ + + @classmethod + def from_dict(cls, value: "RCranLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "RCranLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class RCranLibraryDict(TypedDict, total=False): + """""" + + package: VariableOr[str] + """ + The name of the CRAN package to install. + """ + + repo: VariableOrOptional[str] + """ + The repository where the package can be found. If not specified, the default CRAN repo is used. + """ + + +RCranLibraryParam = RCranLibraryDict | RCranLibrary diff --git a/python/databricks_tests/core/_generated/clusters.py b/python/databricks_tests/core/_generated/clusters.py index c3de32f3016..2de29367b86 100644 --- a/python/databricks_tests/core/_generated/clusters.py +++ b/python/databricks_tests/core/_generated/clusters.py @@ -15,6 +15,7 @@ from databricks.bundles.clusters._models.gcp_attributes import GcpAttributes from databricks.bundles.clusters._models.init_script_info import InitScriptInfo from databricks.bundles.clusters._models.kind import Kind +from databricks.bundles.clusters._models.library import Library from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, ) @@ -44,6 +45,7 @@ def _test_case(): "gcp_attributes": {}, "init_scripts": [{}], "kind": "CLASSIC_PREVIEW", + "libraries": [{}], "lifecycle": {}, "permissions": [{"level": "CAN_MANAGE"}], "runtime_engine": "NULL", @@ -65,6 +67,7 @@ def _test_case(): gcp_attributes=GcpAttributes(), init_scripts=[InitScriptInfo()], kind=Kind.CLASSIC_PREVIEW, + libraries=[Library()], lifecycle=LifecycleWithStarted(), permissions=[ ClusterPermission(level=ClusterPermissionLevel.CAN_MANAGE) From 1a0467ad3ac5b532a1bb23298d3a353a6f93a21e Mon Sep 17 00:00:00 2001 From: Sankalp Mittal <120563575+Sankalp-Mittal@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:45:57 +0200 Subject: [PATCH 02/12] Update pull request reference for libraries field --- .nextchanges/bundles/cluster-libraries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.nextchanges/bundles/cluster-libraries.md b/.nextchanges/bundles/cluster-libraries.md index 1ff0e422fa5..d40748798cf 100644 --- a/.nextchanges/bundles/cluster-libraries.md +++ b/.nextchanges/bundles/cluster-libraries.md @@ -1 +1 @@ -* Add libraries field to clusters. ([#6365](https://github.com/databricks/cli/pull/6365)) +* Add libraries field to clusters. ([#6831](https://github.com/databricks/cli/pull/6831)) From 1b5e207df01e64073f810003500d9b7922ce7c33 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 12:57:39 +0000 Subject: [PATCH 03/12] Stop restarting clusters on library changes Restarting an all-purpose cluster kills attached sessions and running work, which is too disruptive to trigger implicitly on deploy. Installs apply live on a running cluster; uninstalls are marked UNINSTALL_ON_RESTART and take effect at the cluster's next restart. Co-authored-by: Isaac --- .../libraries-content-change/output.txt | 4 +-- .../clusters/libraries-content-change/script | 5 ++- .../libraries-content-change/test.toml | 2 +- .../clusters/libraries-restart/output.txt | 18 ++-------- .../clusters/libraries-restart/script | 7 ++-- .../clusters/libraries-restart/test.toml | 3 -- .../libraries-stopped-cluster/output.txt | 2 +- .../clusters/libraries-stopped-cluster/script | 2 +- .../resources/clusters/libraries/output.txt | 9 +---- .../resources/clusters/libraries/script | 2 +- bundle/direct/dresources/cluster.go | 33 +++---------------- 11 files changed, 19 insertions(+), 68 deletions(-) diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/output.txt b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt index eee0ba47348..ef3f8cf7c11 100644 --- a/acceptance/bundle/resources/clusters/libraries-content-change/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt @@ -16,11 +16,11 @@ OK: cluster created with wheel } } -=== Badness: wheel code changes but version does not, so redeploy neither reinstalls nor restarts +=== Badness: wheel code changes but version does not, so redeploy does not reinstall it >>> jq .plan["resources.clusters.mycluster"].action tmp.plan.json "skip" -OK: no restart on content-only change (known limitation) +OK: redeployed without reinstalling the changed wheel (known limitation) >>> print_requests.py //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/script b/acceptance/bundle/resources/clusters/libraries-content-change/script index 747f9f68d45..4dcfa152f27 100644 --- a/acceptance/bundle/resources/clusters/libraries-content-change/script +++ b/acceptance/bundle/resources/clusters/libraries-content-change/script @@ -17,7 +17,7 @@ trace print_requests.py //libraries/install # Change only the wheel's code, keeping version 0.0.1 so the built filename - and # thus the uploaded workspace path - is byte-for-byte identical to the first deploy. -title "Badness: wheel code changes but version does not, so redeploy neither reinstalls nor restarts" +title "Badness: wheel code changes but version does not, so redeploy does not reinstall it" update_file.py my_test_code/__main__.py "Hello from my func" "Hello from my func v2" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan @@ -25,6 +25,5 @@ $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan # the stale wheel keeps running. trace jq '.plan["resources.clusters.mycluster"].action' tmp.plan.json $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy -cat LOG.redeploy | contains.py "!Restarting cluster" > /dev/null -printf '\n%s\n' "OK: no restart on content-only change (known limitation)" +printf '\n%s\n' "OK: redeployed without reinstalling the changed wheel (known limitation)" trace print_requests.py //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/test.toml b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml index 1abd9f3ecba..8eba7f22dfc 100644 --- a/acceptance/bundle/resources/clusters/libraries-content-change/test.toml +++ b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml @@ -1,4 +1,4 @@ -Badness = "A local wheel whose contents change but whose version (and thus workspace path) does not is not detected in non-dev mode, so redeploy neither reinstalls it nor restarts the cluster; the stale wheel keeps running. See the TODO in bundle/direct/dresources/cluster.go DoUpdate." +Badness = "A local wheel whose contents change but whose version (and thus workspace path) does not is not detected in non-dev mode, so redeploy does not reinstall it; the stale wheel keeps running. See the TODO in bundle/direct/dresources/cluster.go DoUpdate." Cloud = true CloudSlow = true diff --git a/acceptance/bundle/resources/clusters/libraries-restart/output.txt b/acceptance/bundle/resources/clusters/libraries-restart/output.txt index df7c44549eb..c6a829eb951 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-restart/output.txt @@ -2,25 +2,11 @@ === Install (create): libraries install on the fresh cluster with no restart >>> print_requests.py //clusters/restart -=== Update: adding a library restarts the running cluster +=== Update: adding a library does not restart the running cluster >>> print_requests.py //clusters/restart -{ - "method": "POST", - "path": "/api/2.1/clusters/restart", - "body": { - "cluster_id": "[UUID]" - } -} -=== Delete: removing all libraries restarts the running cluster +=== Delete: removing all libraries does not restart the running cluster >>> print_requests.py //clusters/restart -{ - "method": "POST", - "path": "/api/2.1/clusters/restart", - "body": { - "cluster_id": "[UUID]" - } -} >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: diff --git a/acceptance/bundle/resources/clusters/libraries-restart/script b/acceptance/bundle/resources/clusters/libraries-restart/script index 21ac92e7312..09af0ef068f 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/script +++ b/acceptance/bundle/resources/clusters/libraries-restart/script @@ -6,15 +6,14 @@ cleanup() { } trap cleanup EXIT -# Deploy output goes to LOG (differs fake vs cloud); the captured restart request is the proof. +# Deploy output goes to LOG (differs fake vs cloud); the empty restart requests are the proof. title "Install (create): libraries install on the fresh cluster with no restart" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.create cat LOG.create | contains.py "Created clusters.mycluster" > /dev/null -# No restart request on create (empty below). trace print_requests.py //clusters/restart -title "Update: adding a library restarts the running cluster" +title "Update: adding a library does not restart the running cluster" update_file.py databricks.yml " - pypi: package: requests" " - pypi: package: requests @@ -25,7 +24,7 @@ $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.update cat LOG.update | contains.py "Updated clusters.mycluster" > /dev/null trace print_requests.py //clusters/restart -title "Delete: removing all libraries restarts the running cluster" +title "Delete: removing all libraries does not restart the running cluster" update_file.py databricks.yml " libraries: - pypi: package: requests diff --git a/acceptance/bundle/resources/clusters/libraries-restart/test.toml b/acceptance/bundle/resources/clusters/libraries-restart/test.toml index 472e3f3459e..24d1138996d 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/test.toml +++ b/acceptance/bundle/resources/clusters/libraries-restart/test.toml @@ -1,8 +1,5 @@ Cloud = true CloudSlow = true -# This test runs three full cluster lifecycles (create, add-library restart, remove-library -# restart); on slower clouds that exceeds the default 25m cloud timeout, so give it 50m. -TimeoutCloud = '50m' EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt index 6319906394e..e67758ffdbd 100644 --- a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt @@ -2,7 +2,7 @@ === Deploy libraries on a started=false cluster: no restart OK: created on stopped cluster, no restart -=== Change the libraries and redeploy: cluster is stopped, so no restart is issued +=== Change the libraries and redeploy the stopped cluster: no restart OK: libraries changed on stopped cluster, no restart >>> [CLI] bundle destroy --auto-approve diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script index 02f0b8eeed6..7bb1536c861 100644 --- a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script @@ -13,7 +13,7 @@ $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "Created clusters.mycluster" "!Restarting cluster" > /dev/null printf '\n%s\n' "OK: created on stopped cluster, no restart" -title "Change the libraries and redeploy: cluster is stopped, so no restart is issued" +title "Change the libraries and redeploy the stopped cluster: no restart" update_file.py databricks.yml " - pypi: package: requests" " - pypi: package: requests diff --git a/acceptance/bundle/resources/clusters/libraries/output.txt b/acceptance/bundle/resources/clusters/libraries/output.txt index 0528ead2ddc..b7fba0b4b3f 100644 --- a/acceptance/bundle/resources/clusters/libraries/output.txt +++ b/acceptance/bundle/resources/clusters/libraries/output.txt @@ -34,7 +34,7 @@ OK: cluster created with libraries } } -=== Removing the wheel and redeploying uninstalls it and restarts the running cluster +=== Removing the wheel and redeploying uninstalls it without restarting the running cluster >>> print_requests.py //libraries/uninstall //clusters/restart { "method": "POST", @@ -48,13 +48,6 @@ OK: cluster created with libraries ] } } -{ - "method": "POST", - "path": "/api/2.1/clusters/restart", - "body": { - "cluster_id": "[UUID]" - } -} >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: diff --git a/acceptance/bundle/resources/clusters/libraries/script b/acceptance/bundle/resources/clusters/libraries/script index b5402378019..ef65e0bf5c1 100644 --- a/acceptance/bundle/resources/clusters/libraries/script +++ b/acceptance/bundle/resources/clusters/libraries/script @@ -21,7 +21,7 @@ printf '\n%s\n' "OK: cluster created with libraries" title "Libraries installed via the Libraries API (wheel rewritten to its uploaded path)" trace print_requests.py //libraries/install -title "Removing the wheel and redeploying uninstalls it and restarts the running cluster" +title "Removing the wheel and redeploying uninstalls it without restarting the running cluster" update_file.py databricks.yml " - whl: ./dist/*.whl" "" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index 0dd7d00e7cd..e220929d210 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -9,7 +9,6 @@ import ( "github.com/databricks/cli/bundle/config/resources" "github.com/databricks/cli/bundle/deployplan" - "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/structs/structpath" "github.com/databricks/cli/libs/utils" @@ -267,18 +266,17 @@ func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *Clust } // TODO: a local whl/jar whose workspace path is unchanged but whose contents - // changed (same name+version, non-dev mode) is not detected here, so no restart fires. + // changed (same name+version, non-dev mode) is not detected here, so it is not reinstalled. // Dev mode handles this via patchwheel (a source-derived version bump). if entry.Changes.HasChange(librariesPath) { if err := r.reconcileLibraries(ctx, id, config.Libraries, entry); err != nil { return nil, err } - // A cluster edit restarts the cluster on its own, which applies the library change. - // Without an edit we restart so the change takes effect on a running cluster. + // We never restart the cluster for a library change: that would kill attached sessions + // and running work. Installs apply live on a running cluster; uninstalls are marked + // UNINSTALL_ON_RESTART and take effect at the cluster's next restart. + // A cluster edit restarts the cluster on its own, so only wait when there was no edit. if !edited { - if err := r.restartIfRunning(ctx, id); err != nil { - return nil, err - } if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { return nil, err } @@ -571,27 +569,6 @@ func removedLibraries(desired []compute.Library, entry *PlanEntry) []compute.Lib return result } -// restartIfRunning restarts the cluster so a library change takes effect, but only when it is -// running: a stopped cluster applies pending install/uninstall on its next start. It waits for -// the cluster to return to RUNNING before returning. -func (r *ResourceCluster) restartIfRunning(ctx context.Context, id string) error { - details, err := r.client.Clusters.GetByClusterId(ctx, id) - if err != nil { - return err - } - if details.State != compute.StateRunning { - log.Debugf(ctx, "cluster %s is not running (%s); skipping restart for library change", id, details.State) - return nil - } - cmdio.LogString(ctx, fmt.Sprintf("Restarting cluster %s because its libraries changed", id)) - wait, err := r.client.Clusters.Restart(ctx, compute.RestartCluster{ClusterId: id, RestartUser: "", ForceSendFields: nil}) - if err != nil { - return err - } - _, err = wait.GetWithTimeout(clusterWaitTimeout) - return err -} - // waitForInstall polls until every desired library reaches a terminal installed state. It returns // early without waiting when the cluster is not running: installs only progress on a running // cluster and are queued until it next starts. From 9a1a30a934d1306c0cc59dbf55034ab5544c1d21 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 12:57:40 +0000 Subject: [PATCH 04/12] Install job task libraries on the existing cluster in the testserver The Jobs service installs a task's libraries on its existing all-purpose cluster via the Libraries API when a run starts, and they persist there. Mirror that so cluster-status reports them locally, like on cloud. This makes the integration_whl/interactive_* regression from #6365 reproduce without a real workspace. The direct engine now reads the job's wheel as cluster drift on redeploy, so interactive_cluster records its second deploy per engine. Co-authored-by: Isaac --- .../out.deploy2.direct.txt | 9 ++++++++ .../out.deploy2.terraform.txt | 7 +++++++ .../interactive_cluster/output.txt | 7 ------- .../interactive_cluster/script | 4 +++- libs/testserver/jobs.go | 21 +++++++++++++++++++ 5 files changed, 40 insertions(+), 8 deletions(-) create mode 100644 acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt create mode 100644 acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt diff --git a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt new file mode 100644 index 00000000000..9c274c375ac --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt @@ -0,0 +1,9 @@ + +>>> [CLI] bundle deploy +Building python_artifact... +Uploading dist/my_test_code-0.0.1-py3-none-any.whl... +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... +Updated clusters.test_cluster +Updated jobs.some_other_job +Files: 10 uploaded, 0 deleted +Resources: 0 created, 2 changed, 0 deleted, 0 unchanged diff --git a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt new file mode 100644 index 00000000000..2aaaedbb5a2 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt @@ -0,0 +1,7 @@ + +>>> [CLI] bundle deploy +Building python_artifact... +Uploading dist/my_test_code-0.0.1-py3-none-any.whl... +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... +Files: 10 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 2 unchanged diff --git a/acceptance/bundle/integration_whl/interactive_cluster/output.txt b/acceptance/bundle/integration_whl/interactive_cluster/output.txt index 8d7e5ec8ffd..b4800ecf04e 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster/output.txt +++ b/acceptance/bundle/integration_whl/interactive_cluster/output.txt @@ -49,13 +49,6 @@ Got arguments: ['my_test_code', 'one', 'two'] === Make a change to code without version change and run the job again ->>> [CLI] bundle deploy -Building python_artifact... -Uploading dist/my_test_code-0.0.1-py3-none-any.whl... -Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... -Files: 9 uploaded, 0 deleted -Resources: 0 created, 0 changed, 0 deleted, 2 unchanged - >>> [CLI] bundle run some_other_job Run URL: [DATABRICKS_URL]/jobs/[SOME_OTHER_JOB_ID]/runs/[NUMID]?o=[NUMID] diff --git a/acceptance/bundle/integration_whl/interactive_cluster/script b/acceptance/bundle/integration_whl/interactive_cluster/script index 49ad28155b3..fd0e0591fc0 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster/script +++ b/acceptance/bundle/integration_whl/interactive_cluster/script @@ -11,5 +11,7 @@ trace $CLI bundle run some_other_job title "Make a change to code without version change and run the job again" update_file.py my_test_code/__main__.py 'Hello from my func' 'UPDATED MY FUNC' -trace $CLI bundle deploy +# Direct reads the wheel the job run installed on the cluster as drift and uninstalls it +# (deferred until the next restart); terraform does not manage cluster libraries. +trace $CLI bundle deploy &> out.deploy2.$DATABRICKS_BUNDLE_ENGINE.txt trace $CLI bundle run some_other_job diff --git a/libs/testserver/jobs.go b/libs/testserver/jobs.go index 6b3e4d74de3..ed2a7ac48b0 100644 --- a/libs/testserver/jobs.go +++ b/libs/testserver/jobs.go @@ -452,6 +452,23 @@ func (s *FakeWorkspace) JobsList() Response { return Response{Body: jobs.ListJobsResponse{Jobs: list}} } +// installTaskLibrariesOnCluster records a task's libraries on its existing (all-purpose) cluster, +// mirroring the Jobs service, which installs task libraries via the Libraries API when a run starts. +// Cluster-status then reports them, matching cloud (where they are cluster-wide, so other jobs and +// interactive sessions see them too). Callers must hold the workspace lock. +func (s *FakeWorkspace) installTaskLibrariesOnCluster(task jobs.Task) { + if task.ExistingClusterId == "" || len(task.Libraries) == 0 { + return + } + installed := s.ClusterLibraries[task.ExistingClusterId] + for _, lib := range task.Libraries { + if !containsLibrary(installed, lib) { + installed = append(installed, lib) + } + } + s.ClusterLibraries[task.ExistingClusterId] = installed +} + func (s *FakeWorkspace) JobsRunNow(req Request) Response { var request jobs.RunNow if err := json.Unmarshal(req.Body, &request); err != nil { @@ -486,6 +503,10 @@ func (s *FakeWorkspace) JobsRunNow(req Request) Response { var tasks []jobs.RunTask if job.Settings != nil { for _, t := range job.Settings.Tasks { + // Mirror the Jobs service installing a task's libraries on its existing + // (all-purpose) cluster at run time, so cluster-status reports them like on cloud. + s.installTaskLibrariesOnCluster(t) + taskRunId := nextID() taskRun := jobs.RunTask{ RunId: taskRunId, From 09524f4f6c75861d75e87dece4b89309bbc9d1f7 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 12:57:41 +0000 Subject: [PATCH 05/12] Add libraries-scenarios acceptance test for cluster libraries Covers declaring, drifting and removing cluster libraries alongside an out-of-band library, and asserts that no change restarts the cluster. Co-authored-by: Isaac --- .../libraries-scenarios/databricks.yml.tmpl | 13 ++ .../libraries-scenarios/out.test.toml | 4 + .../clusters/libraries-scenarios/output.txt | 194 ++++++++++++++++++ .../clusters/libraries-scenarios/script | 64 ++++++ .../clusters/libraries-scenarios/test.toml | 9 + 5 files changed, 284 insertions(+) create mode 100644 acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl create mode 100644 acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml create mode 100644 acceptance/bundle/resources/clusters/libraries-scenarios/output.txt create mode 100644 acceptance/bundle/resources/clusters/libraries-scenarios/script create mode 100644 acceptance/bundle/resources/clusters/libraries-scenarios/test.toml diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl new file mode 100644 index 00000000000..b5d17cb9690 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl @@ -0,0 +1,13 @@ +bundle: + name: cluster-libraries-scenarios-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml new file mode 100644 index 00000000000..dd03baaabb6 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml @@ -0,0 +1,4 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt new file mode 100644 index 00000000000..24bb9132087 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt @@ -0,0 +1,194 @@ + +=== Deploy a cluster that declares no libraries +OK: cluster created + +=== Out of band: a job run (or the UI) installs 'six' on the shared cluster +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} + +=== Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart +>>> plan_libs +{ + "libraries": { + "action": "update", + "new": [ + { + "pypi": { + "package": "requests" + } + } + ], + "remote": [ + { + "pypi": { + "package": "six" + } + } + ] + }, + "libraries[pypi='requests;']": { + "action": "update", + "new": { + "pypi": { + "package": "requests" + } + } + }, + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + } +} + +>>> print_requests.py //libraries/install //libraries/uninstall //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Drift: 'requests' is uninstalled out of band; plan reinstalls the declared library +>>> print_requests.py //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> plan_libs +{ + "libraries": { + "action": "update", + "old": [ + { + "pypi": { + "package": "requests" + } + } + ], + "new": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> print_requests.py //libraries/install //libraries/uninstall //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Remove the declared library: plan uninstalls requests, no restart +>>> plan_libs +{ + "libraries": { + "action": "update", + "old": [ + { + "pypi": { + "package": "requests" + } + } + ], + "remote": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== No-op redeploy: no libraries remain and nothing changes +>>> plan_libs +{} + +>>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/script b/acceptance/bundle/resources/clusters/libraries-scenarios/script new file mode 100644 index 00000000000..e353b60e972 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/script @@ -0,0 +1,64 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt tmp.plan.json +} +trap cleanup EXIT + +# Show the cluster's libraries plan entries; reading the saved plan keeps output identical across READPLAN. +plan_libs() { + jq '.plan["resources.clusters.mycluster"].changes | with_entries(select(.key | startswith("libraries")))' tmp.plan.json +} + +# Deploy output is verbose and differs plan/no-plan; send it to LOG and assert the key line. +title "Deploy a cluster that declares no libraries" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created" + +# Server-generated cluster id, read from state to target the out-of-band calls. +CLUSTER_ID=$(read_id.py mycluster) + +title "Out of band: a job run (or the UI) installs 'six' on the shared cluster" +MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/install --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"six\"}}]}" > /dev/null +trace print_requests.py //libraries/install + +title "Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart" +update_file.py databricks.yml " num_workers: 1" " num_workers: 1 + libraries: + - pypi: + package: requests" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart + +title "Drift: 'requests' is uninstalled out of band; plan reinstalls the declared library" +MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/uninstall --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"requests\"}}]}" > /dev/null +trace print_requests.py //libraries/uninstall +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart + +title "Remove the declared library: plan uninstalls requests, no restart" +update_file.py databricks.yml " num_workers: 1 + libraries: + - pypi: + package: requests" " num_workers: 1" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart + +title "No-op redeploy: no libraries remain and nothing changes" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "1 unchanged" > /dev/null +trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml new file mode 100644 index 00000000000..3b83369483b --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml @@ -0,0 +1,9 @@ +# The cluster manages every library on it: an out-of-band library (job task lib or API install) is drift and gets uninstalled, declared libs install/uninstall, and drift is corrected. No change restarts the cluster. +# Local only: the out-of-band library is injected via the Libraries API, deterministic locally but racy on cloud (the job-installed variant runs on cloud in interactive_cluster_declared_libs). +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +# READPLAN=1 feeds the serialized plan to `bundle deploy --plan`. +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] From 69d1a51616e0cf40f5325630ed31e3777b440774 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 12:57:42 +0000 Subject: [PATCH 06/12] Add cloud test for cluster libraries alongside job-installed libraries The cluster declares libraries and a wheel job targets it via existing_cluster_id. Removing a declared library uninstalls it together with the job's libraries and does not restart the cluster. Co-authored-by: Isaac --- .../databricks.yml.tmpl | 36 +++++++ .../my_test_code/__init__.py | 2 + .../my_test_code/__main__.py | 16 ++++ .../out.test.toml | 4 + .../output.txt | 94 +++++++++++++++++++ .../interactive_cluster_declared_libs/script | 35 +++++++ .../setup.py | 15 +++ .../test.toml | 8 ++ 8 files changed, 210 insertions(+) create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py create mode 100644 acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl new file mode 100644 index 00000000000..c8eba0a0bcb --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl @@ -0,0 +1,36 @@ +bundle: + name: wheel-task-declared-libs + +workspace: + root_path: "~/.bundle/$UNIQUE_NAME" + +resources: + clusters: + test_cluster: + cluster_name: "test-cluster-$UNIQUE_NAME" + spark_version: "$DEFAULT_SPARK_VERSION" + node_type_id: "$NODE_TYPE_ID" + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - pypi: + package: requests + - pypi: + package: urllib3 + + jobs: + some_other_job: + name: "[${bundle.target}] Test Wheel Job $UNIQUE_NAME" + tasks: + - task_key: TestTask + existing_cluster_id: "${resources.clusters.test_cluster.cluster_id}" + python_wheel_task: + package_name: my_test_code + entry_point: run + parameters: + - "one" + - "two" + libraries: + - whl: ./dist/*.whl + - pypi: + package: six diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml new file mode 100644 index 00000000000..f9f4880725d --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml @@ -0,0 +1,4 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt new file mode 100644 index 00000000000..52a6edb14c5 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt @@ -0,0 +1,94 @@ + +=== Deploy the cluster (declares requests and urllib3) and the wheel job that targets it +OK: deployed + +=== Run the job: its task installs the wheel and pypi 'six' on the shared cluster, out of band +OK: job ran + +=== Plan: the job's out-of-band 'six' shows as a removal, the declared libraries are unchanged +>>> plan_pypi_libs +{ + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + } +} + +=== Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests, no restart +>>> plan_pypi_libs +{ + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + }, + "libraries[pypi='urllib3;']": { + "action": "update", + "old": { + "pypi": { + "package": "urllib3" + } + }, + "remote": { + "pypi": { + "package": "urllib3" + } + } + } +} + +OK: redeployed + +>>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[TEST_CLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "urllib3" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[TEST_CLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.test_cluster + delete resources.jobs.some_other_job + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 2 deleted diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script new file mode 100644 index 00000000000..1c1c7698bbd --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script @@ -0,0 +1,35 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml +trap "errcode trace '$CLI' bundle destroy --auto-approve" EXIT + +# Show the cluster's pypi library plan entries; build/plan noise and the noisy wheel path go to LOG. +plan_pypi_libs() { + $CLI bundle plan -o json 2>>LOG.plan | jq '.plan["resources.clusters.test_cluster"].changes | with_entries(select(.key | startswith("libraries[pypi")))' +} + +title "Deploy the cluster (declares requests and urllib3) and the wheel job that targets it" +$CLI bundle deploy &> LOG.deploy +cat LOG.deploy | contains.py "clusters.test_cluster" > /dev/null +printf '\n%s\n' "OK: deployed" + +# Normalize server-generated resource IDs before we read requests/plans. +replace_ids.py + +title "Run the job: its task installs the wheel and pypi 'six' on the shared cluster, out of band" +$CLI bundle run some_other_job &> LOG.run +printf '\n%s\n' "OK: job ran" +# Flush the install requests the run recorded so they do not leak into the redeploy assertions. +print_requests.py //libraries/install > /dev/null + +title "Plan: the job's out-of-band 'six' shows as a removal, the declared libraries are unchanged" +trace plan_pypi_libs + +title "Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests, no restart" +update_file.py databricks.yml " + - pypi: + package: urllib3" "" +trace plan_pypi_libs +$CLI bundle deploy &> LOG.deploy2 +cat LOG.deploy2 | contains.py "Updated clusters.test_cluster" > /dev/null +printf '\n%s\n' "OK: redeployed" +trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml new file mode 100644 index 00000000000..c3061b595bc --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml @@ -0,0 +1,8 @@ +# The cluster declares `requests` and `urllib3`; the wheel job's task targets the same cluster via +# existing_cluster_id and installs the wheel and pypi `six` on it. So the cluster reads back +# libraries it never declared and treats them as drift: removing `urllib3` uninstalls it and the +# job's libraries (marked UNINSTALL_ON_RESTART on cloud) without restarting the cluster. Cloud + CloudSlow and the venv/wheel harness are inherited from the parent. +# Direct engine only (cluster libraries are a direct-engine feature). +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] From 5d0fe69745466a897eb4db40b151519af88a97ef Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 14:16:02 +0000 Subject: [PATCH 07/12] Read cluster libraries only when the config declares them A cluster without a libraries section now behaves as before the field existed: the plan does not read the cluster's libraries, so libraries installed by job runs or out of band are not drift, and no library calls are made. Removing the section stops managing the libraries and leaves them installed; `libraries: []` still uninstalls them. To make the read depend on the config, add an optional DoReadWithState resource method that receives the node's local state. Planning uses it when implemented; reads without a local state (deletes, the post-apply refresh for remote references) keep using DoRead. Co-authored-by: Isaac --- .../out.deploy2.direct.txt | 9 ----- .../out.deploy2.terraform.txt | 7 ---- .../interactive_cluster/output.txt | 7 ++++ .../interactive_cluster/script | 4 +-- bundle/direct/bundle_plan.go | 2 +- bundle/direct/dresources/README.md | 4 +++ bundle/direct/dresources/adapter.go | 33 +++++++++++++++++++ bundle/direct/dresources/cluster.go | 31 +++++++++++++---- 8 files changed, 70 insertions(+), 27 deletions(-) delete mode 100644 acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt delete mode 100644 acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt diff --git a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt deleted file mode 100644 index 9c274c375ac..00000000000 --- a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.direct.txt +++ /dev/null @@ -1,9 +0,0 @@ - ->>> [CLI] bundle deploy -Building python_artifact... -Uploading dist/my_test_code-0.0.1-py3-none-any.whl... -Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... -Updated clusters.test_cluster -Updated jobs.some_other_job -Files: 10 uploaded, 0 deleted -Resources: 0 created, 2 changed, 0 deleted, 0 unchanged diff --git a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt b/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt deleted file mode 100644 index 2aaaedbb5a2..00000000000 --- a/acceptance/bundle/integration_whl/interactive_cluster/out.deploy2.terraform.txt +++ /dev/null @@ -1,7 +0,0 @@ - ->>> [CLI] bundle deploy -Building python_artifact... -Uploading dist/my_test_code-0.0.1-py3-none-any.whl... -Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... -Files: 10 uploaded, 0 deleted -Resources: 0 created, 0 changed, 0 deleted, 2 unchanged diff --git a/acceptance/bundle/integration_whl/interactive_cluster/output.txt b/acceptance/bundle/integration_whl/interactive_cluster/output.txt index b4800ecf04e..8d7e5ec8ffd 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster/output.txt +++ b/acceptance/bundle/integration_whl/interactive_cluster/output.txt @@ -49,6 +49,13 @@ Got arguments: ['my_test_code', 'one', 'two'] === Make a change to code without version change and run the job again +>>> [CLI] bundle deploy +Building python_artifact... +Uploading dist/my_test_code-0.0.1-py3-none-any.whl... +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/files... +Files: 9 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 2 unchanged + >>> [CLI] bundle run some_other_job Run URL: [DATABRICKS_URL]/jobs/[SOME_OTHER_JOB_ID]/runs/[NUMID]?o=[NUMID] diff --git a/acceptance/bundle/integration_whl/interactive_cluster/script b/acceptance/bundle/integration_whl/interactive_cluster/script index fd0e0591fc0..49ad28155b3 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster/script +++ b/acceptance/bundle/integration_whl/interactive_cluster/script @@ -11,7 +11,5 @@ trace $CLI bundle run some_other_job title "Make a change to code without version change and run the job again" update_file.py my_test_code/__main__.py 'Hello from my func' 'UPDATED MY FUNC' -# Direct reads the wheel the job run installed on the cluster as drift and uninstalls it -# (deferred until the next restart); terraform does not manage cluster libraries. -trace $CLI bundle deploy &> out.deploy2.$DATABRICKS_BUNDLE_ENGINE.txt +trace $CLI bundle deploy trace $CLI bundle run some_other_job diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index c44aeef52c8..f40e8aae081 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -315,7 +315,7 @@ func (b *DeploymentBundle) CalculatePlan(ctx context.Context, client *databricks } remoteState, err := retryOnTransient(ctx, func() (any, error) { - return adapter.DoRead(ctx, dbentry.ID) + return adapter.DoReadWithState(ctx, dbentry.ID, sv.Value) }) if err != nil { if apierr.IsMissing(err) { diff --git a/bundle/direct/dresources/README.md b/bundle/direct/dresources/README.md index 5487042c965..c6388f4d53a 100644 --- a/bundle/direct/dresources/README.md +++ b/bundle/direct/dresources/README.md @@ -103,6 +103,10 @@ So when a field comes back under a different path than `StateType` uses: This makes the field present in `InputType`, `StateType`, and `RemoteType`, so it participates in normal drift detection and is no longer subject to the `missing_in_remote` suppression. +## Reading only what the config manages: DoReadWithState + +If whether to read part of the remote depends on the config, implement `DoReadWithState(ctx, id, state)` next to `DoRead`. Planning calls it with the node's local state; reads without one (deletes, the post-apply refresh for remote references) still call `DoRead`. Clusters use it to read installed libraries only when the config declares a `libraries` section, so a cluster without one makes no library calls and libraries installed by job runs are not drift. + ## OverrideChangeDesc Use `OverrideChangeDesc` only as a last resort when the `.yml` settings cannot express the needed logic. Skipping an action with `change.Action = deployplan.Skip` in `OverrideChangeDesc` creates a silent no-op: the plan shows no change even if the user's config differs from remote. Document the skip reason clearly in both the comment and `change.Reason`. diff --git a/bundle/direct/dresources/adapter.go b/bundle/direct/dresources/adapter.go index 6210a952112..21e47e0b0dc 100644 --- a/bundle/direct/dresources/adapter.go +++ b/bundle/direct/dresources/adapter.go @@ -58,6 +58,12 @@ type IResource interface { // Example: func (r *ResourceJob) DoRead(ctx context.Context, id string) (*jobs.Job, error) DoRead(ctx context.Context, id string) (remoteState any, e error) + // [Optional] DoReadWithState is DoRead that also gets the node's local state. Planning uses it when + // implemented, so a resource can skip reading parts the config does not manage. Reads without a local + // state (deletes, the post-apply refresh for remote references) still use DoRead. + // Example: func (r *ResourceCluster) DoReadWithState(ctx context.Context, id string, state *ClusterState) (*ClusterRemote, error) + DoReadWithState(ctx context.Context, id string, state any) (remoteState any, e error) + // [Optional] DoDelete deletes the resource. The state argument is the last-persisted // state for the resource; resources that don't need it should accept it as // _ to satisfy the interface. @@ -131,6 +137,7 @@ type Adapter struct { // Optional: doDelete *calladapt.BoundCaller + doReadWithState *calladapt.BoundCaller prepareInputConfig *calladapt.BoundCaller isEmptyState *calladapt.BoundCaller doUpdate *calladapt.BoundCaller @@ -171,6 +178,7 @@ func NewAdapter(typedNil any, resourceType string, client *databricks.WorkspaceC remapState: nil, doRefresh: nil, doDelete: nil, + doReadWithState: nil, doCreate: nil, prepareInputConfig: nil, isEmptyState: nil, @@ -249,6 +257,11 @@ func (a *Adapter) initMethods(resource any) error { return err } + a.doReadWithState, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "DoReadWithState") + if err != nil { + return err + } + // Optional methods with varying signatures: // DoDelete is optional: a resource that omits it declares that deleting it has @@ -381,6 +394,13 @@ func (a *Adapter) validate() error { } validations = append(validations, "DoCreate remoteState return", a.doCreate.OutTypes[1], remoteType) + if a.doReadWithState != nil { + validations = append(validations, + "DoReadWithState state", a.doReadWithState.InTypes[2], stateType, + "DoReadWithState remoteState return", a.doReadWithState.OutTypes[0], remoteType, + ) + } + if a.isEmptyState != nil { validations = append(validations, "IsEmptyState newState", a.isEmptyState.InTypes[0], stateType) } @@ -536,6 +556,19 @@ func (a *Adapter) DoRead(ctx context.Context, id string) (any, error) { return outs[0], nil } +// DoReadWithState reads remote state for planning, passing the local state to resources that +// implement DoReadWithState and falling back to DoRead otherwise. +func (a *Adapter) DoReadWithState(ctx context.Context, id string, state any) (any, error) { + if a.doReadWithState == nil { + return a.DoRead(ctx, id) + } + outs, err := a.doReadWithState.Call(ctx, id, state) + if err != nil { + return nil, err + } + return outs[0], nil +} + // HasDoDelete reports whether the resource implements DoDelete. When false, the // resource's delete has no backend effect and the engine treats a planned Delete // as a state-only cleanup. diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index e220929d210..10d4ec3899f 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -67,8 +67,9 @@ type ClusterRemote struct { ApplyPolicyDefaultValues bool `json:"apply_policy_default_values,omitempty"` Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` - // Libraries is populated by DoRead from the Libraries cluster-status API (the cluster - // GET does not return installed libraries), so it participates in drift detection. + // Libraries is populated by DoReadWithState from the Libraries cluster-status API (the cluster + // GET does not return installed libraries), so it participates in drift detection. It is only + // read when the config declares libraries. Libraries []compute.Library `json:"libraries,omitempty"` } @@ -150,7 +151,21 @@ func (r *ResourceCluster) RemapState(input *ClusterRemote) *ClusterState { return spec } +// DoRead reads the cluster without its libraries. It serves reads that have no local state +// (deletes, the post-apply refresh for remote references), which don't need them. func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote, error) { + return r.read(ctx, id, false) +} + +// DoReadWithState also reads the cluster's libraries, but only when the config declares a +// libraries section. Without one the bundle does not manage libraries at all, matching the +// behaviour before the field existed: no library calls, and libraries installed by job runs +// or out of band are not drift. +func (r *ResourceCluster) DoReadWithState(ctx context.Context, id string, state *ClusterState) (*ClusterRemote, error) { + return r.read(ctx, id, state.Libraries != nil) +} + +func (r *ResourceCluster) read(ctx context.Context, id string, withLibraries bool) (*ClusterRemote, error) { var details *compute.ClusterDetails var libraries []compute.Library @@ -161,11 +176,13 @@ func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote details, err = r.client.Clusters.GetByClusterId(ctx, id) return err }) - g.Go(func() error { - var err error - libraries, err = r.readLibraries(ctx, id) - return err - }) + if withLibraries { + g.Go(func() error { + var err error + libraries, err = r.readLibraries(ctx, id) + return err + }) + } if err := g.Wait(); err != nil { return nil, err } From 86bd6c657ee3e14491052c109608b3c22b683915 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Thu, 24 Sep 2026 14:16:03 +0000 Subject: [PATCH 08/12] Update cluster library tests for unmanaged libraries interactive_cluster declares no cluster libraries, so it is back to its original output on both engines. libraries-scenarios checks that the plan reads no libraries without a section and that removing the section makes no library calls. libraries-restart empties the list instead of dropping it, so it still exercises an uninstall. Co-authored-by: Isaac --- .../clusters/libraries-restart/output.txt | 23 +++++++++++-- .../clusters/libraries-restart/script | 8 +++-- .../clusters/libraries-scenarios/output.txt | 34 +++++++++---------- .../clusters/libraries-scenarios/script | 11 ++++-- .../clusters/libraries-scenarios/test.toml | 2 +- 5 files changed, 51 insertions(+), 27 deletions(-) diff --git a/acceptance/bundle/resources/clusters/libraries-restart/output.txt b/acceptance/bundle/resources/clusters/libraries-restart/output.txt index c6a829eb951..13f7de12da5 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-restart/output.txt @@ -5,8 +5,27 @@ === Update: adding a library does not restart the running cluster >>> print_requests.py //clusters/restart -=== Delete: removing all libraries does not restart the running cluster ->>> print_requests.py //clusters/restart +=== Delete: emptying the libraries list uninstalls them without restarting the running cluster +>>> print_requests.py //libraries/uninstall //clusters/restart +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: diff --git a/acceptance/bundle/resources/clusters/libraries-restart/script b/acceptance/bundle/resources/clusters/libraries-restart/script index 09af0ef068f..bfd5ab45ac0 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/script +++ b/acceptance/bundle/resources/clusters/libraries-restart/script @@ -24,14 +24,16 @@ $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.update cat LOG.update | contains.py "Updated clusters.mycluster" > /dev/null trace print_requests.py //clusters/restart -title "Delete: removing all libraries does not restart the running cluster" +# An empty list keeps the libraries managed, so it uninstalls them; dropping the section would leave them unmanaged. +title "Delete: emptying the libraries list uninstalls them without restarting the running cluster" update_file.py databricks.yml " libraries: - pypi: package: requests - pypi: package: six -" "" +" " libraries: [] +" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.remove cat LOG.remove | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //clusters/restart +trace print_requests.py //libraries/uninstall //clusters/restart diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt index 24bb9132087..66cf394569c 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt @@ -19,6 +19,12 @@ OK: cluster created } } +=== No libraries section: plan does not read the cluster's libraries, so six is not drift +>>> plan_libs +{} + +>>> print_requests.py --get //libraries + === Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart >>> plan_libs { @@ -141,35 +147,31 @@ OK: cluster created } } -=== Remove the declared library: plan uninstalls requests, no restart +=== Remove the libraries section: libraries become unmanaged, requests stays installed, no library calls >>> plan_libs { "libraries": { - "action": "update", + "action": "skip", + "reason": "remote_already_set", "old": [ { "pypi": { "package": "requests" } } - ], - "remote": [ - { - "pypi": { - "package": "requests" - } - } ] } } >>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart + +=== No-op redeploy: libraries are unmanaged and nothing changes +>>> plan_libs { - "method": "POST", - "path": "/api/2.0/libraries/uninstall", - "body": { - "cluster_id": "[MYCLUSTER_ID]", - "libraries": [ + "libraries": { + "action": "skip", + "reason": "remote_already_set", + "old": [ { "pypi": { "package": "requests" @@ -179,10 +181,6 @@ OK: cluster created } } -=== No-op redeploy: no libraries remain and nothing changes ->>> plan_libs -{} - >>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart >>> [CLI] bundle destroy --auto-approve diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/script b/acceptance/bundle/resources/clusters/libraries-scenarios/script index e353b60e972..f0b65a6a9c0 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/script +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/script @@ -25,6 +25,11 @@ title "Out of band: a job run (or the UI) installs 'six' on the shared cluster" MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/install --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"six\"}}]}" > /dev/null trace print_requests.py //libraries/install +title "No libraries section: plan does not read the cluster's libraries, so six is not drift" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +trace print_requests.py --get //libraries + title "Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart" update_file.py databricks.yml " num_workers: 1" " num_workers: 1 libraries: @@ -45,7 +50,7 @@ $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart -title "Remove the declared library: plan uninstalls requests, no restart" +title "Remove the libraries section: libraries become unmanaged, requests stays installed, no library calls" update_file.py databricks.yml " num_workers: 1 libraries: - pypi: @@ -53,10 +58,10 @@ update_file.py databricks.yml " num_workers: 1 $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy -cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +cat LOG.deploy | contains.py "1 unchanged" > /dev/null trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart -title "No-op redeploy: no libraries remain and nothing changes" +title "No-op redeploy: libraries are unmanaged and nothing changes" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml index 3b83369483b..a50e63513a8 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml @@ -1,4 +1,4 @@ -# The cluster manages every library on it: an out-of-band library (job task lib or API install) is drift and gets uninstalled, declared libs install/uninstall, and drift is corrected. No change restarts the cluster. +# Without a libraries section the cluster's libraries are unmanaged: they are not read, so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. No change restarts the cluster. # Local only: the out-of-band library is injected via the Libraries API, deterministic locally but racy on cloud (the job-installed variant runs on cloud in interactive_cluster_declared_libs). RecordRequests = true From ad9aa3596d3147723445da88e346f6e5db393950 Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Fri, 25 Sep 2026 12:37:14 +0000 Subject: [PATCH 09/12] Skip undeclared cluster libraries in OverrideChangeDesc Replace the DoReadWithState framework method from 5d0fe6974 with a cluster-only override, as suggested in review. The cluster reads its libraries unconditionally again, and when the config has no libraries section the whole-field change is skipped with the new reason `unmanaged`: no drift, no "Updated clusters.*" line, and no install or uninstall calls. Removing the section also leaves the libraries installed and unmanaged, while `libraries: []` stays managed. config-remote-sync ignores skips other than remote_addition, so unmanaged libraries are not synced into the config. Co-authored-by: Isaac --- bundle/deployplan/plan.go | 4 ++ bundle/direct/bundle_plan.go | 2 +- bundle/direct/dresources/README.md | 4 -- bundle/direct/dresources/adapter.go | 33 ------------ bundle/direct/dresources/cluster.go | 41 ++++++-------- bundle/direct/dresources/cluster_test.go | 68 ++++++++++++++++++++++++ 6 files changed, 90 insertions(+), 62 deletions(-) create mode 100644 bundle/direct/dresources/cluster_test.go diff --git a/bundle/deployplan/plan.go b/bundle/deployplan/plan.go index 28ae78dde40..0fd97868ce4 100644 --- a/bundle/deployplan/plan.go +++ b/bundle/deployplan/plan.go @@ -184,6 +184,10 @@ const ( // set but the backend populated (old and new nil, remote set). It is left in place rather // than recreated - the user does not manage it and the value cannot be changed anyway. ReasonImmutableBackendValue = "immutable_backend_value" + // ReasonUnmanaged: the config does not declare the field at all, so the bundle does not manage + // it and whatever the remote reports is not drift (e.g. cluster libraries without a libraries + // section, where job runs install their task libraries cluster-wide). + ReasonUnmanaged = "unmanaged" // Special reason that results in removing this change from the plan ReasonDrop = "!drop" diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index f40e8aae081..c44aeef52c8 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -315,7 +315,7 @@ func (b *DeploymentBundle) CalculatePlan(ctx context.Context, client *databricks } remoteState, err := retryOnTransient(ctx, func() (any, error) { - return adapter.DoReadWithState(ctx, dbentry.ID, sv.Value) + return adapter.DoRead(ctx, dbentry.ID) }) if err != nil { if apierr.IsMissing(err) { diff --git a/bundle/direct/dresources/README.md b/bundle/direct/dresources/README.md index c6388f4d53a..5487042c965 100644 --- a/bundle/direct/dresources/README.md +++ b/bundle/direct/dresources/README.md @@ -103,10 +103,6 @@ So when a field comes back under a different path than `StateType` uses: This makes the field present in `InputType`, `StateType`, and `RemoteType`, so it participates in normal drift detection and is no longer subject to the `missing_in_remote` suppression. -## Reading only what the config manages: DoReadWithState - -If whether to read part of the remote depends on the config, implement `DoReadWithState(ctx, id, state)` next to `DoRead`. Planning calls it with the node's local state; reads without one (deletes, the post-apply refresh for remote references) still call `DoRead`. Clusters use it to read installed libraries only when the config declares a `libraries` section, so a cluster without one makes no library calls and libraries installed by job runs are not drift. - ## OverrideChangeDesc Use `OverrideChangeDesc` only as a last resort when the `.yml` settings cannot express the needed logic. Skipping an action with `change.Action = deployplan.Skip` in `OverrideChangeDesc` creates a silent no-op: the plan shows no change even if the user's config differs from remote. Document the skip reason clearly in both the comment and `change.Reason`. diff --git a/bundle/direct/dresources/adapter.go b/bundle/direct/dresources/adapter.go index 21e47e0b0dc..6210a952112 100644 --- a/bundle/direct/dresources/adapter.go +++ b/bundle/direct/dresources/adapter.go @@ -58,12 +58,6 @@ type IResource interface { // Example: func (r *ResourceJob) DoRead(ctx context.Context, id string) (*jobs.Job, error) DoRead(ctx context.Context, id string) (remoteState any, e error) - // [Optional] DoReadWithState is DoRead that also gets the node's local state. Planning uses it when - // implemented, so a resource can skip reading parts the config does not manage. Reads without a local - // state (deletes, the post-apply refresh for remote references) still use DoRead. - // Example: func (r *ResourceCluster) DoReadWithState(ctx context.Context, id string, state *ClusterState) (*ClusterRemote, error) - DoReadWithState(ctx context.Context, id string, state any) (remoteState any, e error) - // [Optional] DoDelete deletes the resource. The state argument is the last-persisted // state for the resource; resources that don't need it should accept it as // _ to satisfy the interface. @@ -137,7 +131,6 @@ type Adapter struct { // Optional: doDelete *calladapt.BoundCaller - doReadWithState *calladapt.BoundCaller prepareInputConfig *calladapt.BoundCaller isEmptyState *calladapt.BoundCaller doUpdate *calladapt.BoundCaller @@ -178,7 +171,6 @@ func NewAdapter(typedNil any, resourceType string, client *databricks.WorkspaceC remapState: nil, doRefresh: nil, doDelete: nil, - doReadWithState: nil, doCreate: nil, prepareInputConfig: nil, isEmptyState: nil, @@ -257,11 +249,6 @@ func (a *Adapter) initMethods(resource any) error { return err } - a.doReadWithState, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "DoReadWithState") - if err != nil { - return err - } - // Optional methods with varying signatures: // DoDelete is optional: a resource that omits it declares that deleting it has @@ -394,13 +381,6 @@ func (a *Adapter) validate() error { } validations = append(validations, "DoCreate remoteState return", a.doCreate.OutTypes[1], remoteType) - if a.doReadWithState != nil { - validations = append(validations, - "DoReadWithState state", a.doReadWithState.InTypes[2], stateType, - "DoReadWithState remoteState return", a.doReadWithState.OutTypes[0], remoteType, - ) - } - if a.isEmptyState != nil { validations = append(validations, "IsEmptyState newState", a.isEmptyState.InTypes[0], stateType) } @@ -556,19 +536,6 @@ func (a *Adapter) DoRead(ctx context.Context, id string) (any, error) { return outs[0], nil } -// DoReadWithState reads remote state for planning, passing the local state to resources that -// implement DoReadWithState and falling back to DoRead otherwise. -func (a *Adapter) DoReadWithState(ctx context.Context, id string, state any) (any, error) { - if a.doReadWithState == nil { - return a.DoRead(ctx, id) - } - outs, err := a.doReadWithState.Call(ctx, id, state) - if err != nil { - return nil, err - } - return outs[0], nil -} - // HasDoDelete reports whether the resource implements DoDelete. When false, the // resource's delete has no backend effect and the engine treats a planned Delete // as a state-only cleanup. diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index 10d4ec3899f..9c971aee85f 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -67,9 +67,8 @@ type ClusterRemote struct { ApplyPolicyDefaultValues bool `json:"apply_policy_default_values,omitempty"` Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` - // Libraries is populated by DoReadWithState from the Libraries cluster-status API (the cluster - // GET does not return installed libraries), so it participates in drift detection. It is only - // read when the config declares libraries. + // Libraries is populated by DoRead from the Libraries cluster-status API (the cluster + // GET does not return installed libraries), so it participates in drift detection. Libraries []compute.Library `json:"libraries,omitempty"` } @@ -151,21 +150,7 @@ func (r *ResourceCluster) RemapState(input *ClusterRemote) *ClusterState { return spec } -// DoRead reads the cluster without its libraries. It serves reads that have no local state -// (deletes, the post-apply refresh for remote references), which don't need them. func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote, error) { - return r.read(ctx, id, false) -} - -// DoReadWithState also reads the cluster's libraries, but only when the config declares a -// libraries section. Without one the bundle does not manage libraries at all, matching the -// behaviour before the field existed: no library calls, and libraries installed by job runs -// or out of band are not drift. -func (r *ResourceCluster) DoReadWithState(ctx context.Context, id string, state *ClusterState) (*ClusterRemote, error) { - return r.read(ctx, id, state.Libraries != nil) -} - -func (r *ResourceCluster) read(ctx context.Context, id string, withLibraries bool) (*ClusterRemote, error) { var details *compute.ClusterDetails var libraries []compute.Library @@ -176,13 +161,11 @@ func (r *ResourceCluster) read(ctx context.Context, id string, withLibraries boo details, err = r.client.Clusters.GetByClusterId(ctx, id) return err }) - if withLibraries { - g.Go(func() error { - var err error - libraries, err = r.readLibraries(ctx, id) - return err - }) - } + g.Go(func() error { + var err error + libraries, err = r.readLibraries(ctx, id) + return err + }) if err := g.Wait(); err != nil { return nil, err } @@ -426,6 +409,16 @@ func (r *ResourceCluster) OverrideChangeDesc(ctx context.Context, p *structpath. if remoteState != nil && remoteState.State == compute.StateRunning { change.Action = deployplan.Resize } + + case "libraries": + // Without a libraries section the bundle does not manage the cluster's libraries, matching + // the behaviour before the field existed: job runs install their task libraries cluster-wide, + // so what the cluster reports is not drift. With no section, New is nil and the difference + // arrives as a single whole-field change; `libraries: []` keeps New non-nil and stays managed. + if p.String() == "libraries" && change.New == nil { + change.Action = deployplan.Skip + change.Reason = deployplan.ReasonUnmanaged + } } return nil } diff --git a/bundle/direct/dresources/cluster_test.go b/bundle/direct/dresources/cluster_test.go new file mode 100644 index 00000000000..7d3af4440d4 --- /dev/null +++ b/bundle/direct/dresources/cluster_test.go @@ -0,0 +1,68 @@ +package dresources + +import ( + "testing" + + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/structs/structpath" + "github.com/databricks/databricks-sdk-go/service/compute" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClusterOverrideChangeDescLibraries(t *testing.T) { + jobLib := []compute.Library{{Whl: "/Workspace/job.whl"}} + + tests := []struct { + name string + path string + change ChangeDesc + action deployplan.ActionType + reason string + }{ + { + name: "no section with remote libraries is unmanaged", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: nil, Remote: jobLib}, + action: deployplan.Skip, + reason: deployplan.ReasonUnmanaged, + }, + { + name: "removed section is unmanaged", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: jobLib, New: nil, Remote: jobLib}, + action: deployplan.Skip, + reason: deployplan.ReasonUnmanaged, + }, + { + name: "empty list stays managed", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: []compute.Library{}, Remote: jobLib}, + action: deployplan.Update, + }, + { + name: "declared libraries stay managed", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: jobLib, Remote: nil}, + action: deployplan.Update, + }, + { + // A per-library entry only exists when the config declares a list, so a missing New + // there is a removal to apply, not an unmanaged section. + name: "element removal stays managed", + path: "libraries[whl='/Workspace/job.whl']", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: nil, Remote: jobLib[0]}, + action: deployplan.Update, + }, + } + + r := &ResourceCluster{} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + change := tt.change + require.NoError(t, r.OverrideChangeDesc(t.Context(), structpath.MustParsePath(tt.path), &change, nil)) + assert.Equal(t, tt.action, change.Action) + assert.Equal(t, tt.reason, change.Reason) + }) + } +} From 50d2e131253773f3f834bd7574c1696b9e23280b Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Fri, 25 Sep 2026 12:37:15 +0000 Subject: [PATCH 10/12] Show unmanaged cluster libraries in libraries-scenarios The plan now reads the cluster's libraries without a section and skips them with reason `unmanaged`, so the step records the skipped change instead of asserting that no library read happens. Co-authored-by: Isaac --- .../clusters/libraries-scenarios/output.txt | 38 +++++++++++++++---- .../clusters/libraries-scenarios/script | 5 +-- .../clusters/libraries-scenarios/test.toml | 2 +- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt index 66cf394569c..6545c2d7f01 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt @@ -19,11 +19,21 @@ OK: cluster created } } -=== No libraries section: plan does not read the cluster's libraries, so six is not drift +=== No libraries section: six is skipped as unmanaged, not drift >>> plan_libs -{} - ->>> print_requests.py --get //libraries +{ + "libraries": { + "action": "skip", + "reason": "unmanaged", + "remote": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} === Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart >>> plan_libs @@ -147,18 +157,25 @@ OK: cluster created } } -=== Remove the libraries section: libraries become unmanaged, requests stays installed, no library calls +=== Remove the libraries section: libraries become unmanaged, requests stays installed, no install or uninstall >>> plan_libs { "libraries": { "action": "skip", - "reason": "remote_already_set", + "reason": "unmanaged", "old": [ { "pypi": { "package": "requests" } } + ], + "remote": [ + { + "pypi": { + "package": "requests" + } + } ] } } @@ -170,13 +187,20 @@ OK: cluster created { "libraries": { "action": "skip", - "reason": "remote_already_set", + "reason": "unmanaged", "old": [ { "pypi": { "package": "requests" } } + ], + "remote": [ + { + "pypi": { + "package": "requests" + } + } ] } } diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/script b/acceptance/bundle/resources/clusters/libraries-scenarios/script index f0b65a6a9c0..d8f15c122f5 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/script +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/script @@ -25,10 +25,9 @@ title "Out of band: a job run (or the UI) installs 'six' on the shared cluster" MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/install --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"six\"}}]}" > /dev/null trace print_requests.py //libraries/install -title "No libraries section: plan does not read the cluster's libraries, so six is not drift" +title "No libraries section: six is skipped as unmanaged, not drift" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs -trace print_requests.py --get //libraries title "Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart" update_file.py databricks.yml " num_workers: 1" " num_workers: 1 @@ -50,7 +49,7 @@ $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart -title "Remove the libraries section: libraries become unmanaged, requests stays installed, no library calls" +title "Remove the libraries section: libraries become unmanaged, requests stays installed, no install or uninstall" update_file.py databricks.yml " num_workers: 1 libraries: - pypi: diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml index a50e63513a8..217827a7954 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml @@ -1,4 +1,4 @@ -# Without a libraries section the cluster's libraries are unmanaged: they are not read, so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. No change restarts the cluster. +# Without a libraries section the cluster's libraries are unmanaged (skipped with reason `unmanaged`), so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. No change restarts the cluster. # Local only: the out-of-band library is injected via the Libraries API, deterministic locally but racy on cloud (the job-installed variant runs on cloud in interactive_cluster_declared_libs). RecordRequests = true From d7f8eab1628a05f9bbb6428af2461fc80aea12ce Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Mon, 28 Sep 2026 11:24:16 +0000 Subject: [PATCH 11/12] Remove cluster restart leftovers from cluster libraries The bundle no longer restarts clusters for library changes, so drop what only existed for that design: the `edited` gate that skipped waiting for installs when a cluster edit restarted the cluster, the restart reasoning in the DoUpdate and WaitAfterCreate comments, and the testserver's clusters/restart handler. waitForInstall now always runs after reconciling; it already returns early when the cluster is not running. Co-authored-by: Isaac --- bundle/direct/dresources/cluster.go | 18 ++++++------------ libs/testserver/clusters.go | 29 ----------------------------- libs/testserver/handlers.go | 4 ---- 3 files changed, 6 insertions(+), 45 deletions(-) diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index 9c971aee85f..7f1eb26dffc 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -243,8 +243,7 @@ func hasClusterSpecChanges(entry *PlanEntry) bool { } func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *ClusterState, entry *PlanEntry) (*ClusterRemote, error) { - edited := hasClusterSpecChanges(entry) - if edited { + if hasClusterSpecChanges(entry) { // Same retry as in TF provider logic // https://github.com/databricks/terraform-provider-databricks/blob/3eecd0f90cf99d7777e79a3d03c41f9b2aafb004/clusters/resource_cluster.go#L624 _, err := retries.Poll(ctx, clusterWaitTimeout, func() (*compute.WaitGetClusterRunning[struct{}], *retries.Err) { @@ -272,14 +271,10 @@ func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *Clust if err := r.reconcileLibraries(ctx, id, config.Libraries, entry); err != nil { return nil, err } - // We never restart the cluster for a library change: that would kill attached sessions - // and running work. Installs apply live on a running cluster; uninstalls are marked - // UNINSTALL_ON_RESTART and take effect at the cluster's next restart. - // A cluster edit restarts the cluster on its own, so only wait when there was no edit. - if !edited { - if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { - return nil, err - } + // Installs apply live on a running cluster. Uninstalls are marked UNINSTALL_ON_RESTART + // by the backend and take effect at the cluster's next restart; the bundle never restarts it. + if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { + return nil, err } } @@ -327,8 +322,7 @@ func (r *ResourceCluster) WaitAfterCreate(ctx context.Context, id string, config return nil, err } - // Install libraries once the cluster is running. A freshly-created cluster has no - // attached sessions, so the install applies live without a restart. + // Install libraries once the cluster is running: installs only progress on a running cluster. // TODO: Wait is supposed to be side effect free, but in this case moving it to // the create will cause a wait for libraries to be installed befor the cluster is installed. // this increases the risk of losing the cluster. This is a limitation diff --git a/libs/testserver/clusters.go b/libs/testserver/clusters.go index e24be06216d..e0a046031e6 100644 --- a/libs/testserver/clusters.go +++ b/libs/testserver/clusters.go @@ -244,35 +244,6 @@ func (s *FakeWorkspace) ClustersStart(req Request) any { return Response{} } -// ClustersRestart restarts a running cluster. It moves the cluster back to PENDING so the next -// ClustersGet transitions it to RUNNING, mirroring how a real restart cycles through states, and -// clears the venv cache like ClustersEdit (a restart rebuilds the library environment). -func (s *FakeWorkspace) ClustersRestart(req Request) any { - var request compute.RestartCluster - if err := json.Unmarshal(req.Body, &request); err != nil { - return Response{ - StatusCode: 400, - Body: fmt.Sprintf("request parsing error: %s", err), - } - } - defer s.LockUnlock()() - - cluster, ok := s.Clusters[request.ClusterId] - if !ok { - return Response{StatusCode: 404} - } - - cluster.State = compute.StatePending - s.Clusters[request.ClusterId] = cluster - - if env, ok := s.clusterVenvs[request.ClusterId]; ok { - os.RemoveAll(env.dir) - delete(s.clusterVenvs, request.ClusterId) - } - - return Response{} -} - func (s *FakeWorkspace) ClustersPermanentDelete(req Request) any { var request compute.PermanentDeleteCluster if err := json.Unmarshal(req.Body, &request); err != nil { diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 41750d6802d..a56e2dc4c0b 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -1030,10 +1030,6 @@ func AddDefaultHandlers(server *Server) { return req.Workspace.ClustersStart(req) }) - server.Handle("POST", "/api/2.1/clusters/restart", func(req Request) any { - return req.Workspace.ClustersRestart(req) - }) - server.Handle("POST", "/api/2.1/clusters/permanent-delete", func(req Request) any { return req.Workspace.ClustersPermanentDelete(req) }) From 30c009e97c0afc7109ecc4e3d037b9e6c81677bf Mon Sep 17 00:00:00 2001 From: Sankalp-Mittal Date: Mon, 28 Sep 2026 11:24:17 +0000 Subject: [PATCH 12/12] Drop restart assertions from cluster library tests Rename libraries-restart to libraries-update and check the install and uninstall requests instead of restart requests. Remove the //clusters/restart checks, the "!Restarting cluster" checks for a log line that no longer exists, and the "no restart" wording elsewhere. With the testserver restart route gone, an accidental restart call now fails the tests locally. Co-authored-by: Isaac --- .../output.txt | 4 +- .../interactive_cluster_declared_libs/script | 4 +- .../test.toml | 2 +- .../clusters/libraries-restart/output.txt | 36 ---------- .../clusters/libraries-scenarios/output.txt | 10 +-- .../clusters/libraries-scenarios/script | 10 +-- .../clusters/libraries-scenarios/test.toml | 2 +- .../libraries-stopped-cluster/output.txt | 8 +-- .../clusters/libraries-stopped-cluster/script | 12 ++-- .../databricks.yml.tmpl | 2 +- .../out.test.toml | 0 .../clusters/libraries-update/output.txt | 69 +++++++++++++++++++ .../script | 14 ++-- .../test.toml | 0 .../resources/clusters/libraries/output.txt | 4 +- .../resources/clusters/libraries/script | 4 +- 16 files changed, 107 insertions(+), 74 deletions(-) delete mode 100644 acceptance/bundle/resources/clusters/libraries-restart/output.txt rename acceptance/bundle/resources/clusters/{libraries-restart => libraries-update}/databricks.yml.tmpl (88%) rename acceptance/bundle/resources/clusters/{libraries-restart => libraries-update}/out.test.toml (100%) create mode 100644 acceptance/bundle/resources/clusters/libraries-update/output.txt rename acceptance/bundle/resources/clusters/{libraries-restart => libraries-update}/script (70%) rename acceptance/bundle/resources/clusters/{libraries-restart => libraries-update}/test.toml (100%) diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt index 52a6edb14c5..96612a33430 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt @@ -18,7 +18,7 @@ OK: job ran } } -=== Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests, no restart +=== Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests >>> plan_pypi_libs { "libraries[pypi='six;']": { @@ -46,7 +46,7 @@ OK: job ran OK: redeployed ->>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart +>>> print_requests.py //libraries/uninstall //libraries/install { "method": "POST", "path": "/api/2.0/libraries/uninstall", diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script index 1c1c7698bbd..d1eff7cc290 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script @@ -24,7 +24,7 @@ print_requests.py //libraries/install > /dev/null title "Plan: the job's out-of-band 'six' shows as a removal, the declared libraries are unchanged" trace plan_pypi_libs -title "Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests, no restart" +title "Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests" update_file.py databricks.yml " - pypi: package: urllib3" "" @@ -32,4 +32,4 @@ trace plan_pypi_libs $CLI bundle deploy &> LOG.deploy2 cat LOG.deploy2 | contains.py "Updated clusters.test_cluster" > /dev/null printf '\n%s\n' "OK: redeployed" -trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml index c3061b595bc..e816575e41b 100644 --- a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml @@ -1,7 +1,7 @@ # The cluster declares `requests` and `urllib3`; the wheel job's task targets the same cluster via # existing_cluster_id and installs the wheel and pypi `six` on it. So the cluster reads back # libraries it never declared and treats them as drift: removing `urllib3` uninstalls it and the -# job's libraries (marked UNINSTALL_ON_RESTART on cloud) without restarting the cluster. Cloud + CloudSlow and the venv/wheel harness are inherited from the parent. +# job's libraries (marked UNINSTALL_ON_RESTART on cloud). Cloud + CloudSlow and the venv/wheel harness are inherited from the parent. # Direct engine only (cluster libraries are a direct-engine feature). RecordRequests = true diff --git a/acceptance/bundle/resources/clusters/libraries-restart/output.txt b/acceptance/bundle/resources/clusters/libraries-restart/output.txt deleted file mode 100644 index 13f7de12da5..00000000000 --- a/acceptance/bundle/resources/clusters/libraries-restart/output.txt +++ /dev/null @@ -1,36 +0,0 @@ - -=== Install (create): libraries install on the fresh cluster with no restart ->>> print_requests.py //clusters/restart - -=== Update: adding a library does not restart the running cluster ->>> print_requests.py //clusters/restart - -=== Delete: emptying the libraries list uninstalls them without restarting the running cluster ->>> print_requests.py //libraries/uninstall //clusters/restart -{ - "method": "POST", - "path": "/api/2.0/libraries/uninstall", - "body": { - "cluster_id": "[UUID]", - "libraries": [ - { - "pypi": { - "package": "requests" - } - }, - { - "pypi": { - "package": "six" - } - } - ] - } -} - ->>> [CLI] bundle destroy --auto-approve -The following resources will be deleted: - delete resources.clusters.mycluster - -All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] - -Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt index 6545c2d7f01..c31dc73b484 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt @@ -35,7 +35,7 @@ OK: cluster created } } -=== Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart +=== Declare 'requests': plan installs it and uninstalls the out-of-band six >>> plan_libs { "libraries": { @@ -73,7 +73,7 @@ OK: cluster created } } ->>> print_requests.py //libraries/install //libraries/uninstall //clusters/restart +>>> print_requests.py //libraries/install //libraries/uninstall { "method": "POST", "path": "/api/2.0/libraries/uninstall", @@ -141,7 +141,7 @@ OK: cluster created } } ->>> print_requests.py //libraries/install //libraries/uninstall //clusters/restart +>>> print_requests.py //libraries/install //libraries/uninstall { "method": "POST", "path": "/api/2.0/libraries/install", @@ -180,7 +180,7 @@ OK: cluster created } } ->>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart +>>> print_requests.py //libraries/uninstall //libraries/install === No-op redeploy: libraries are unmanaged and nothing changes >>> plan_libs @@ -205,7 +205,7 @@ OK: cluster created } } ->>> print_requests.py //libraries/uninstall //libraries/install //clusters/restart +>>> print_requests.py //libraries/uninstall //libraries/install >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/script b/acceptance/bundle/resources/clusters/libraries-scenarios/script index d8f15c122f5..26e80df1b66 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/script +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/script @@ -29,7 +29,7 @@ title "No libraries section: six is skipped as unmanaged, not drift" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs -title "Declare 'requests': plan installs it and uninstalls the out-of-band six, no restart" +title "Declare 'requests': plan installs it and uninstalls the out-of-band six" update_file.py databricks.yml " num_workers: 1" " num_workers: 1 libraries: - pypi: @@ -38,7 +38,7 @@ $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart +trace print_requests.py //libraries/install //libraries/uninstall title "Drift: 'requests' is uninstalled out of band; plan reinstalls the declared library" MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/uninstall --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"requests\"}}]}" > /dev/null @@ -47,7 +47,7 @@ $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //libraries/install //libraries/uninstall //clusters/restart +trace print_requests.py //libraries/install //libraries/uninstall title "Remove the libraries section: libraries become unmanaged, requests stays installed, no install or uninstall" update_file.py databricks.yml " num_workers: 1 @@ -58,11 +58,11 @@ $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "1 unchanged" > /dev/null -trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart +trace print_requests.py //libraries/uninstall //libraries/install title "No-op redeploy: libraries are unmanaged and nothing changes" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan trace plan_libs $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy cat LOG.deploy | contains.py "1 unchanged" > /dev/null -trace print_requests.py //libraries/uninstall //libraries/install //clusters/restart +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml index 217827a7954..328df03eb91 100644 --- a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml @@ -1,4 +1,4 @@ -# Without a libraries section the cluster's libraries are unmanaged (skipped with reason `unmanaged`), so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. No change restarts the cluster. +# Without a libraries section the cluster's libraries are unmanaged (skipped with reason `unmanaged`), so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. # Local only: the out-of-band library is injected via the Libraries API, deterministic locally but racy on cloud (the job-installed variant runs on cloud in interactive_cluster_declared_libs). RecordRequests = true diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt index e67758ffdbd..d7913bf1bb0 100644 --- a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt @@ -1,9 +1,9 @@ -=== Deploy libraries on a started=false cluster: no restart -OK: created on stopped cluster, no restart +=== Deploy libraries on a started=false cluster +OK: created on stopped cluster -=== Change the libraries and redeploy the stopped cluster: no restart -OK: libraries changed on stopped cluster, no restart +=== Change the libraries and redeploy the stopped cluster +OK: libraries changed on stopped cluster >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script index 7bb1536c861..ec6fea46d5f 100644 --- a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script @@ -7,13 +7,13 @@ cleanup() { trap cleanup EXIT # Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. -title "Deploy libraries on a started=false cluster: no restart" +title "Deploy libraries on a started=false cluster" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy -cat LOG.deploy | contains.py "Created clusters.mycluster" "!Restarting cluster" > /dev/null -printf '\n%s\n' "OK: created on stopped cluster, no restart" +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: created on stopped cluster" -title "Change the libraries and redeploy the stopped cluster: no restart" +title "Change the libraries and redeploy the stopped cluster" update_file.py databricks.yml " - pypi: package: requests" " - pypi: package: requests @@ -21,5 +21,5 @@ update_file.py databricks.yml " - pypi: package: numpy" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy -cat LOG.redeploy | contains.py "Updated clusters.mycluster" "!Restarting cluster" > /dev/null -printf '\n%s\n' "OK: libraries changed on stopped cluster, no restart" +cat LOG.redeploy | contains.py "Updated clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: libraries changed on stopped cluster" diff --git a/acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl similarity index 88% rename from acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl rename to acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl index 3c9a4946638..60dbf56bd16 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/databricks.yml.tmpl +++ b/acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl @@ -1,5 +1,5 @@ bundle: - name: cluster-libraries-restart-$UNIQUE_NAME + name: cluster-libraries-update-$UNIQUE_NAME workspace: root_path: ~/.bundle/$UNIQUE_NAME diff --git a/acceptance/bundle/resources/clusters/libraries-restart/out.test.toml b/acceptance/bundle/resources/clusters/libraries-update/out.test.toml similarity index 100% rename from acceptance/bundle/resources/clusters/libraries-restart/out.test.toml rename to acceptance/bundle/resources/clusters/libraries-update/out.test.toml diff --git a/acceptance/bundle/resources/clusters/libraries-update/output.txt b/acceptance/bundle/resources/clusters/libraries-update/output.txt new file mode 100644 index 00000000000..64c9ac77476 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/output.txt @@ -0,0 +1,69 @@ + +=== Create: the declared library installs on the new cluster +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Update: adding a library installs the declared set on the running cluster +>>> print_requests.py //libraries/install //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} + +=== Delete: emptying the libraries list uninstalls them +>>> print_requests.py //libraries/uninstall //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-restart/script b/acceptance/bundle/resources/clusters/libraries-update/script similarity index 70% rename from acceptance/bundle/resources/clusters/libraries-restart/script rename to acceptance/bundle/resources/clusters/libraries-update/script index bfd5ab45ac0..9ee680a1e72 100644 --- a/acceptance/bundle/resources/clusters/libraries-restart/script +++ b/acceptance/bundle/resources/clusters/libraries-update/script @@ -6,14 +6,14 @@ cleanup() { } trap cleanup EXIT -# Deploy output goes to LOG (differs fake vs cloud); the empty restart requests are the proof. -title "Install (create): libraries install on the fresh cluster with no restart" +# Deploy output goes to LOG (differs fake vs cloud); the recorded library requests are the proof. +title "Create: the declared library installs on the new cluster" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.create cat LOG.create | contains.py "Created clusters.mycluster" > /dev/null -trace print_requests.py //clusters/restart +trace print_requests.py //libraries/install -title "Update: adding a library does not restart the running cluster" +title "Update: adding a library installs the declared set on the running cluster" update_file.py databricks.yml " - pypi: package: requests" " - pypi: package: requests @@ -22,10 +22,10 @@ update_file.py databricks.yml " - pypi: $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.update cat LOG.update | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //clusters/restart +trace print_requests.py //libraries/install //libraries/uninstall # An empty list keeps the libraries managed, so it uninstalls them; dropping the section would leave them unmanaged. -title "Delete: emptying the libraries list uninstalls them without restarting the running cluster" +title "Delete: emptying the libraries list uninstalls them" update_file.py databricks.yml " libraries: - pypi: package: requests @@ -36,4 +36,4 @@ update_file.py databricks.yml " libraries: $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.remove cat LOG.remove | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //libraries/uninstall //clusters/restart +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-restart/test.toml b/acceptance/bundle/resources/clusters/libraries-update/test.toml similarity index 100% rename from acceptance/bundle/resources/clusters/libraries-restart/test.toml rename to acceptance/bundle/resources/clusters/libraries-update/test.toml diff --git a/acceptance/bundle/resources/clusters/libraries/output.txt b/acceptance/bundle/resources/clusters/libraries/output.txt index b7fba0b4b3f..6e0dc533ca0 100644 --- a/acceptance/bundle/resources/clusters/libraries/output.txt +++ b/acceptance/bundle/resources/clusters/libraries/output.txt @@ -34,8 +34,8 @@ OK: cluster created with libraries } } -=== Removing the wheel and redeploying uninstalls it without restarting the running cluster ->>> print_requests.py //libraries/uninstall //clusters/restart +=== Removing the wheel and redeploying uninstalls it +>>> print_requests.py //libraries/uninstall { "method": "POST", "path": "/api/2.0/libraries/uninstall", diff --git a/acceptance/bundle/resources/clusters/libraries/script b/acceptance/bundle/resources/clusters/libraries/script index ef65e0bf5c1..ad202b5b699 100644 --- a/acceptance/bundle/resources/clusters/libraries/script +++ b/acceptance/bundle/resources/clusters/libraries/script @@ -21,9 +21,9 @@ printf '\n%s\n' "OK: cluster created with libraries" title "Libraries installed via the Libraries API (wheel rewritten to its uploaded path)" trace print_requests.py //libraries/install -title "Removing the wheel and redeploying uninstalls it without restarting the running cluster" +title "Removing the wheel and redeploying uninstalls it" update_file.py databricks.yml " - whl: ./dist/*.whl" "" $CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan $CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy cat LOG.redeploy | contains.py "Updated clusters.mycluster" > /dev/null -trace print_requests.py //libraries/uninstall //clusters/restart +trace print_requests.py //libraries/uninstall