Skip to content

Commit 2b37ce6

Browse files
Use best-effort history for all history opt-ins and remove DMS state mode
1 parent bd5923f commit 2b37ce6

47 files changed

Lines changed: 248 additions & 981 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎acceptance/bin/print_state.py‎

Lines changed: 6 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
#!/usr/bin/env python3
22
"""
3-
Print resources state from default target, and handle DMS (deployment metadata service) interactions.
3+
Print resources state from the default target, normalizing history metadata for comparisons.
44
55
Note, this intentionally has no logic on guessing what is the right state file (e.g. via DATABRICKS_BUNDLE_ENGINE),
66
the goal is to record all states that are available.
77
"""
88

99
import argparse
10-
import functools
1110
import glob
1211
import json
1312
import os
1413
import posixpath
1514
import subprocess
16-
from pathlib import Path
1715

1816
from nostamp import scrub
1917

@@ -60,11 +58,7 @@ def get_state_file(target, backup):
6058
return filtered[0] if filtered else result[0]
6159

6260

63-
# DMS (deployment metadata service) interaction helpers
64-
# https://go.databricks.com/dms-service
65-
6661
CLI = os.environ.get("CLI", "databricks")
67-
DEPLOYMENT_NODE_NAME = "resources.deployment.json" # Must match dms.DeploymentNodeName
6862

6963

7064
def run_json(cmd, allow_failure=False):
@@ -102,116 +96,20 @@ def get_remote_state_path(target):
10296
return run_json(args)["workspace"]["state_path"]
10397

10498

105-
@functools.cache
106-
def get_deployment_id(target):
107-
"""The recorded deployment's id, or None when nothing is recorded.
108-
109-
Cached and shared: both the resource listing and the version lookup need it, and resolving it
110-
costs a workspace round trip. No node means nothing has been recorded, the conclusion
111-
dms.resolveDeploymentID also draws from a 404 - the deployment is gone once the bundle is
112-
destroyed.
113-
"""
114-
state_path = get_remote_state_path(target)
115-
if not state_path:
116-
return None
117-
node = run_json([CLI, "workspace", "get-status", f"{state_path}/{DEPLOYMENT_NODE_NAME}"], allow_failure=True)
118-
if not node or not node.get("object_id"):
119-
return None
120-
return node["object_id"]
121-
122-
123-
@functools.cache
124-
def get_resources(target):
125-
"""Map every recorded resource key ("jobs.foo") to its {"id", "state"}.
126-
127-
File-history state is read locally. Legacy DMS state is read from the service,
128-
or is empty when no deployment has been recorded. Cached for repeated resource lookups.
129-
"""
130-
filename = get_state_file(target, False)
131-
if filename.endswith("resources.json") and os.path.exists(filename):
132-
data = json.loads(Path(filename).read_text())
133-
if "deployment_history_best_effort" in (data.get("features") or {}):
134-
# DMS can miss history updates. The file remains authoritative in this mode.
135-
return {
136-
key.removeprefix("resources."): {
137-
"id": entry.get("__id__"),
138-
"state": entry.get("state") or {},
139-
"depends_on": entry.get("depends_on") or [],
140-
}
141-
for key, entry in data.get("state", {}).items()
142-
}
143-
144-
deployment_id = get_deployment_id(target)
145-
if not deployment_id:
146-
return {}
147-
148-
result = {}
149-
# The service pages at 50 resources; the local fake returns everything at once.
150-
page_token = None
151-
while True:
152-
url = f"/api/2.0/bundle/deployments/{deployment_id}/resources"
153-
if page_token:
154-
url += f"?page_token={page_token}"
155-
listed = run_json([CLI, "api", "get", url])
156-
for resource in listed.get("resources") or []:
157-
# The service stores state as the opaque envelope the CLI wrote (dstate.RecordedState),
158-
# so unwrap it to the resource state itself.
159-
envelope = json.loads(resource["state"]) if resource.get("state") else {}
160-
result[resource["resource_key"]] = {
161-
"id": resource.get("resource_id"),
162-
"state": envelope.get("state") or {},
163-
"depends_on": envelope.get("depends_on") or [],
164-
}
165-
page_token = listed.get("next_page_token")
166-
if not page_token:
167-
return result
168-
169-
170-
def get_recorded_state(target):
171-
"""The recorded resources in the on-disk state file's `state` shape (resources.<key> ->
172-
{__id__, state, depends_on}), so a recording run prints the same shape as a non-recording one."""
173-
state = {}
174-
for key, value in sorted(get_resources(target).items()):
175-
entry = {"__id__": value["id"], "state": value["state"]}
176-
if value["depends_on"]:
177-
entry["depends_on"] = value["depends_on"]
178-
state[f"resources.{key}"] = entry
179-
return state
180-
181-
182-
def get_last_version_id(target):
183-
"""The version the service has recorded for this deployment, or None when nothing is recorded."""
184-
deployment_id = get_deployment_id(target)
185-
if not deployment_id:
186-
return None
187-
deployment = run_json([CLI, "api", "get", f"/api/2.0/bundle/deployments/{deployment_id}"])
188-
return (deployment or {}).get("last_version_id")
189-
190-
19199
def print_recorded_state(filename, target):
192100
"""Normalize history state for comparisons with ordinary file-backed deployments.
193101
194-
get_resources uses the file for best-effort history and the service for legacy DMS state.
102+
Resource state and serial always come from the file, even when DMS history is incomplete.
195103
"""
196104
data = json.loads(open(filename).read())
197105
# Recording stamps each resource payload with the deployment and version; drop it here so the
198106
# printed state matches a non-recording run without every caller piping through nostamp.
199-
data["state"] = scrub(get_recorded_state(target))
107+
data["state"] = scrub(data.get("state", {}))
200108

201-
# The file's serial is a copy of the DMS version to ensure outdated resource state is not read.
202-
# Rebuild in header order with the authoritative serial from the deployment.
203-
if "deployment_history_best_effort" in (data.get("features") or {}):
204-
serial = data.get("serial", 0)
205-
else:
206-
last_version_id = get_last_version_id(target)
207-
serial = int(last_version_id) if last_version_id else 0
109+
serial = data.get("serial", 0)
208110

209111
# Recording itself is not what these tests assert, so drop the feature that marks it.
210-
features = {
211-
k: v
212-
for k, v in (data.get("features") or {}).items()
213-
if k not in {"deployment_history", "deployment_history_best_effort"}
214-
}
112+
features = {k: v for k, v in (data.get("features") or {}).items() if k != "deployment_history_best_effort"}
215113

216114
rebuilt = {}
217115
for key in ("state_version", "cli_version", "lineage"):
@@ -233,7 +131,7 @@ def main():
233131
parser.add_argument(
234132
"--no-dms",
235133
action="store_true",
236-
help="Print resources.json as-is without fetching state from DMS. "
134+
help="Print resources.json as-is without normalizing history metadata. "
237135
"Use in bundle/dms tests to assert the file state and its feature markers.",
238136
)
239137
args = parser.parse_args()

‎acceptance/bin/read_id.py‎

Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,12 @@
1010

1111
import argparse
1212
import json
13-
import os
1413
import sys
1514
from pathlib import Path
1615

1716
sys.path.insert(0, str(Path(__file__).parent))
1817
from add_repl import add_repl, id_repl_name
19-
from print_state import get_resources, get_state_file
18+
from print_state import get_state_file
2019

2120

2221
def get_id_terraform(filename, name):
@@ -35,23 +34,6 @@ def get_id_terraform(filename, name):
3534
print(f"Cannot find resource with {name=}. Available: {available}", file=sys.stderr)
3635

3736

38-
def get_id_recorded(target, name):
39-
"""Find a recorded resource's id by its bare name ("foo"), scanning the resource list.
40-
41-
The GET resource API would be the direct lookup, but it needs the full resource key
42-
("jobs.foo"), and callers pass only the leaf name - matching how user-visible commands
43-
take a bare name ("bundle run my_job"), which DABs allows because it enforces name
44-
uniqueness across types. So list and match on the leaf instead. Switching to GET is a
45-
reasonable follow-up; it likely needs the service to key resources by name as well.
46-
"""
47-
resources = get_resources(target)
48-
for key, value in resources.items():
49-
if key.split(".")[1] == name:
50-
return value["id"]
51-
52-
print(f"Cannot find recorded resource with {name=}. Available: {list(resources)}", file=sys.stderr)
53-
54-
5537
def get_id_direct(filename, name):
5638
raw = open(filename).read()
5739
data = json.loads(raw)
@@ -71,14 +53,11 @@ def main():
7153
parser.add_argument("name")
7254
args = parser.parse_args()
7355

74-
if os.environ.get("DATABRICKS_BUNDLE_DEPLOYMENT_HISTORY") == "true":
75-
id = get_id_recorded(args.target, args.name)
56+
filename = get_state_file(args.target, args.backup)
57+
if filename.endswith(".tfstate"):
58+
id = get_id_terraform(filename, args.name)
7659
else:
77-
filename = get_state_file(args.target, args.backup)
78-
if filename.endswith(".tfstate"):
79-
id = get_id_terraform(filename, args.name)
80-
else:
81-
id = get_id_direct(filename, args.name)
60+
id = get_id_direct(filename, args.name)
8261

8362
if id:
8463
print(id)

‎acceptance/bin/read_state.py‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import sys
1111

1212
sys.path.insert(0, os.path.dirname(__file__))
13-
from print_state import get_resources
1413

1514

1615
def print_resource_direct(group, name, *attrs):
@@ -35,21 +34,4 @@ def print_resource_direct(group, name, *attrs):
3534
print(group, name, " ".join(values))
3635

3736

38-
def print_resource_recorded(group, name, *attrs):
39-
result = get_resources(None).get(f"{group}.{name}")
40-
if result is None:
41-
# Recorded state lives in deployment history, not on disk, so name that rather than a
42-
# file (the Repl normalizes it to match the file-based variants).
43-
print(f"State not found for {group}.{name} in deployment history")
44-
return
45-
46-
state = dict(result["state"])
47-
state.setdefault("id", result["id"])
48-
values = [f"{x}={state.get(x)!r}" for x in attrs]
49-
print(group, name, " ".join(values))
50-
51-
52-
if os.environ.get("DATABRICKS_BUNDLE_DEPLOYMENT_HISTORY") == "true":
53-
print_resource_recorded(*sys.argv[1:])
54-
else:
55-
print_resource_direct(*sys.argv[1:])
37+
print_resource_direct(*sys.argv[1:])

‎acceptance/bin/replace_ids.py‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@
55

66
import argparse
77
import json
8-
import os
98
import sys
109
from pathlib import Path
1110

1211
sys.path.insert(0, str(Path(__file__).parent))
1312
from add_repl import add_repl, id_repl_name
14-
from print_state import get_resources, get_state_file
13+
from print_state import get_state_file
1514

1615

1716
def iter_ids_terraform(filename):
@@ -27,12 +26,6 @@ def iter_ids_terraform(filename):
2726
yield r_name, id
2827

2928

30-
def iter_ids_recorded(target):
31-
for key, value in get_resources(target).items():
32-
if value["id"]:
33-
yield key.split(".")[1], value["id"]
34-
35-
3629
def iter_ids_direct(filename):
3730
raw = open(filename).read()
3831
data = json.loads(raw)
@@ -51,14 +44,11 @@ def main():
5144
parser.add_argument("--backup", action="store_true")
5245
args = parser.parse_args()
5346

54-
if os.environ.get("DATABRICKS_BUNDLE_DEPLOYMENT_HISTORY") == "true":
55-
it = iter_ids_recorded(args.target)
47+
filename = get_state_file(args.target, args.backup)
48+
if filename.endswith(".tfstate"):
49+
it = iter_ids_terraform(filename)
5650
else:
57-
filename = get_state_file(args.target, args.backup)
58-
if filename.endswith(".tfstate"):
59-
it = iter_ids_terraform(filename)
60-
else:
61-
it = iter_ids_direct(filename)
51+
it = iter_ids_direct(filename)
6252

6353
for name, id in it:
6454
add_repl(id, id_repl_name(name))

‎acceptance/bundle/dms/depends-on/output.txt‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
>>> [CLI] bundle plan -o json
44
{
55
"plan_version": [PLAN_VERSION],
6-
"cli_version": "[CLI_VERSION]"
6+
"cli_version": "[CLI_VERSION]",
7+
"features": {
8+
"deployment_history_best_effort": {}
9+
}
710
}
811

912
>>> [CLI] bundle plan

‎acceptance/bundle/dms/existing-state/output.txt‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ Resources: 1 created, 0 changed, 0 deleted, 0 unchanged
6363

6464
>>> print_requests.py --dms //api/2.0/bundle --oneline
6565
{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-existing-state-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default"}}}
66+
{"method": "POST", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions", "q": {"version_id": "2"}, "body": {"cli_version": "[CLI_VERSION]", "operations": [{"action_type": "OPERATION_ACTION_TYPE_DELETE", "resource_key": "jobs.one"}], "version_type": "VERSION_TYPE_DESTROY"}}
67+
{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions/2/operations/jobs.one", "q": {"update_mask": "state,error_message,status"}, "body": {"error_message": "", "sequence_id": 0, "status": "OPERATION_STATUS_SUCCEEDED"}}
68+
{"method": "POST", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions/2/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}}
69+
{"method": "DELETE", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]"}
70+
{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-existing-state-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default"}}}
6671
{"method": "POST", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "operations": [{"action_type": "OPERATION_ACTION_TYPE_CREATE", "resource_key": "jobs.one"}], "version_type": "VERSION_TYPE_DEPLOY"}}
6772
{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions/1/operations/jobs.one", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[ONE_ID]", "sequence_id": 0, "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[DEPLOYMENT_ID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"one\",\"queue\":{\"enabled\":true}}}", "status": "OPERATION_STATUS_SUCCEEDED"}}
6873
{"method": "POST", "path": "/api/2.0/bundle/deployments/[DEPLOYMENT_ID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}}
@@ -73,6 +78,6 @@ Resources: 1 created, 0 changed, 0 deleted, 0 unchanged
7378
{
7479
"state_version": 3,
7580
"features": {
76-
"deployment_history": {}
81+
"deployment_history_best_effort": {}
7782
}
7883
}

‎acceptance/bundle/dms/existing-state/script‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ musterr trace DATABRICKS_BUNDLE_DEPLOYMENT_HISTORY=true $CLI bundle deploy
1616

1717
title "A leftover local WAL with the wrong lineage is still refused"
1818
mkdir -p .databricks/bundle/default
19-
printf '{"lineage":"stale","serial":99,"state_version":2,"features":{"deployment_history":{}}}\n' > .databricks/bundle/default/resources.json.wal
19+
printf '{"lineage":"stale","serial":99,"state_version":2,"features":{"deployment_history_best_effort":{}}}\n' > .databricks/bundle/default/resources.json.wal
2020
musterr trace DATABRICKS_BUNDLE_DEPLOYMENT_HISTORY=true $CLI bundle deploy
2121

2222
title "Destroy clears the deployment. With nothing recorded remotely the bundle is treated as new, so recording can be enabled once the stale WAL is gone"

‎acceptance/bundle/dms/failed-recreate/output.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,4 +193,4 @@ Files: 2 uploaded, 0 deleted
193193
"state": {}
194194
}
195195

196-
=== Planning from DMS state alone creates the schema, which is what has to happen: it no longer exists
196+
=== Planning after pulling remote file state creates the schema, which is what has to happen: it no longer exists

‎acceptance/bundle/dms/failed-recreate/script‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ trace MSYS_NO_PATHCONV=1 $CLI bundle-deployments list-resources "deployments/${d
3434
title "The raw state after failed recreate shows no resource"
3535
trace print_state.py --no-dms
3636

37-
title "Planning from DMS state alone creates the schema, which is what has to happen: it no longer exists"
37+
title "Planning after pulling remote file state creates the schema, which is what has to happen: it no longer exists"
3838
rm -rf .databricks
3939
$CLI bundle plan &> LOG.plan_final
4040
# Ensure "$OUT_REQUESTS" is not left behind (RecordRequests creates it when running tests)

‎acceptance/bundle/dms/record-failure/output.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ Plan: 1 to add, 0 to change, 0 to delete, 0 unchanged
9797
"state": {}
9898
}
9999

100-
=== Redeploying from DMS state alone still creates the failed resource: it was never applied, so it must not be skipped as unchanged
100+
=== Redeploying after pulling remote file state still creates the failed resource: it was never applied, so it must not be skipped as unchanged
101101
>>> [CLI] bundle plan
102102
create jobs.doomed
103103

0 commit comments

Comments
 (0)