-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_databricks_pytest.py
More file actions
278 lines (235 loc) · 8.82 KB
/
Copy pathrun_databricks_pytest.py
File metadata and controls
278 lines (235 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""
Submit insurance-optimise pytest suite to Databricks serverless compute.
Uses the REST API directly — no cluster spec required.
"""
import base64
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
# ---------------------------------------------------------------------------
# Load credentials
# ---------------------------------------------------------------------------
env_path = os.path.expanduser("~/.config/burning-cost/databricks.env")
with open(env_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1)
os.environ[k.strip()] = v.strip()
api_base = os.environ["DATABRICKS_HOST"].rstrip("/")
token = os.environ["DATABRICKS_TOKEN"]
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
RUN_ID = uuid.uuid4().hex[:8]
WORKSPACE_FOLDER = "/Workspace/insurance-optimise"
NOTEBOOK_PATH = f"{WORKSPACE_FOLDER}/run_pytest"
# ---------------------------------------------------------------------------
# Read source files
# ---------------------------------------------------------------------------
BASE = "/home/ralph/repos/insurance-optimise"
def read_file(path: str) -> str:
with open(path, "r") as f:
return f.read()
src_files = {
"__init__.py": read_file(f"{BASE}/src/insurance_optimise/__init__.py"),
"result.py": read_file(f"{BASE}/src/insurance_optimise/result.py"),
"demand.py": read_file(f"{BASE}/src/insurance_optimise/demand.py"),
"constraints.py": read_file(f"{BASE}/src/insurance_optimise/constraints.py"),
"audit.py": read_file(f"{BASE}/src/insurance_optimise/audit.py"),
"optimiser.py": read_file(f"{BASE}/src/insurance_optimise/optimiser.py"),
"frontier.py": read_file(f"{BASE}/src/insurance_optimise/frontier.py"),
"scenarios.py": read_file(f"{BASE}/src/insurance_optimise/scenarios.py"),
}
test_files = {
"conftest.py": read_file(f"{BASE}/tests/conftest.py"),
"test_demand.py": read_file(f"{BASE}/tests/test_demand.py"),
"test_constraints.py": read_file(f"{BASE}/tests/test_constraints.py"),
"test_optimiser.py": read_file(f"{BASE}/tests/test_optimiser.py"),
"test_result.py": read_file(f"{BASE}/tests/test_result.py"),
"test_scenarios.py": read_file(f"{BASE}/tests/test_scenarios.py"),
"test_frontier.py": read_file(f"{BASE}/tests/test_frontier.py"),
"test_integration.py": read_file(f"{BASE}/tests/test_integration.py"),
}
all_files = {**src_files, **test_files}
src_file_names = set(src_files.keys())
files_json = json.dumps(all_files)
pyproject_content = """[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "insurance-optimise"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
"numpy>=1.24",
"polars>=0.20",
"scipy>=1.10",
]
[tool.hatch.build.targets.wheel]
packages = ["src/insurance_optimise"]
"""
pyproject_json = json.dumps(pyproject_content)
# ---------------------------------------------------------------------------
# Build notebook source
# ---------------------------------------------------------------------------
NOTEBOOK_SOURCE = f"""# Databricks notebook source
# MAGIC %pip install polars>=0.20 numpy>=1.24 scipy>=1.10 pytest>=7.0 hatchling --quiet
# COMMAND ----------
import json, os, sys, uuid, subprocess
pkg_id = uuid.uuid4().hex[:8]
pkg_dir = f"/tmp/insurance_optimise_{{pkg_id}}"
src_dir = f"{{pkg_dir}}/src/insurance_optimise"
tests_dir = f"{{pkg_dir}}/tests"
os.makedirs(src_dir, exist_ok=True)
os.makedirs(tests_dir, exist_ok=True)
FILES_JSON = {files_json!r}
PYPROJECT_JSON = {pyproject_json!r}
SRC_FILE_NAMES = {json.dumps(list(src_file_names))!r}
files_map = json.loads(FILES_JSON)
pyproject_src = json.loads(PYPROJECT_JSON)
src_names = set(json.loads(SRC_FILE_NAMES))
for name, content in files_map.items():
if name in src_names:
path = f"{{src_dir}}/{{name}}"
else:
path = f"{{tests_dir}}/{{name}}"
with open(path, "w") as f:
f.write(content)
with open(f"{{pkg_dir}}/pyproject.toml", "w") as f:
f.write(pyproject_src)
print(f"Written {{len(files_map) + 1}} files to {{pkg_dir}}")
# COMMAND ----------
r = subprocess.run(
[sys.executable, "-m", "pip", "install", "-e", pkg_dir, "--quiet"],
capture_output=True, text=True
)
if r.returncode != 0:
print("Install error:", r.stderr[:1000])
else:
print("insurance-optimise installed from", pkg_dir)
# COMMAND ----------
r = subprocess.run(
[sys.executable, "-m", "pytest", tests_dir, "-v", "--tb=short",
"--no-header", "-p", "no:cacheprovider"],
capture_output=True, text=True, cwd=pkg_dir
)
print(r.stdout[-8000:])
if r.stderr:
print("STDERR:", r.stderr[-1000:])
if r.returncode == 0:
print("\\n=== ALL TESTS PASSED ===")
try:
dbutils.notebook.exit("ALL TESTS PASSED")
except NameError:
pass
else:
msg = f"TESTS FAILED (exit {{r.returncode}})"
print(f"\\n=== {{msg}} ===")
try:
dbutils.notebook.exit(msg)
except NameError:
pass
"""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def api_call(method: str, endpoint: str, body: dict | None = None):
data = json.dumps(body).encode("utf-8") if body else None
req = urllib.request.Request(
f"{api_base}/{endpoint}",
data=data,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
err_body = e.read().decode()
raise RuntimeError(f"API {method} {endpoint} failed {e.code}: {err_body}")
# ---------------------------------------------------------------------------
# Ensure workspace folder exists
# ---------------------------------------------------------------------------
print(f"Creating workspace folder {WORKSPACE_FOLDER} ...")
try:
api_call("POST", "api/2.0/workspace/mkdirs", {"path": WORKSPACE_FOLDER})
print("Folder ready.")
except RuntimeError as exc:
print(f"mkdirs note: {exc}")
# ---------------------------------------------------------------------------
# Upload notebook
# ---------------------------------------------------------------------------
print(f"Uploading notebook to {NOTEBOOK_PATH} ...")
notebook_b64 = base64.b64encode(NOTEBOOK_SOURCE.encode("utf-8")).decode("ascii")
api_call("POST", "api/2.0/workspace/import", {
"path": NOTEBOOK_PATH,
"format": "SOURCE",
"language": "PYTHON",
"content": notebook_b64,
"overwrite": True,
})
print("Upload OK")
# ---------------------------------------------------------------------------
# Submit serverless run
# ---------------------------------------------------------------------------
print(f"Submitting serverless run {RUN_ID} ...")
submit_body = {
"run_name": f"insurance-optimise-pytest-{RUN_ID}",
"tasks": [
{
"task_key": "pytest",
"notebook_task": {
"notebook_path": NOTEBOOK_PATH,
"source": "WORKSPACE",
},
}
],
}
result = api_call("POST", "api/2.1/jobs/runs/submit", submit_body)
run_id = result["run_id"]
print(f"Run submitted: run_id={run_id}")
# ---------------------------------------------------------------------------
# Poll
# ---------------------------------------------------------------------------
print("Polling ...")
lc, rs = "PENDING", "-"
for i in range(120):
time.sleep(15)
run_state = api_call("GET", f"api/2.1/jobs/runs/get?run_id={run_id}")
lc = run_state.get("state", {}).get("life_cycle_state", "UNKNOWN")
rs = run_state.get("state", {}).get("result_state", "-")
print(f" [{i * 15}s] {lc} / {rs}")
if lc in ("TERMINATED", "SKIPPED", "INTERNAL_ERROR"):
break
print(f"\nFinal state: {lc} / {rs}")
# ---------------------------------------------------------------------------
# Fetch output
# ---------------------------------------------------------------------------
try:
output = api_call("GET", f"api/2.1/jobs/runs/get-output?run_id={run_id}")
notebook_result = output.get("notebook_output", {}).get("result", "")
error = output.get("error", "")
error_trace = output.get("error_trace", "")
logs = output.get("logs", "")
if notebook_result:
print(f"\nExit value: {notebook_result}")
if error:
print(f"Error: {error}")
if error_trace:
print(f"Trace:\n{error_trace[:3000]}")
if logs:
print(f"\nLogs:\n{logs[-8000:]}")
except Exception as e:
print(f"Could not fetch output: {e}")
if rs == "SUCCESS":
print("\n=== PASS: All tests completed on Databricks. ===")
sys.exit(0)
else:
print(f"\n=== FAIL: Run ended with state {rs}. ===")
sys.exit(1)