bricksentry 0.1.8__tar.gz → 0.1.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {bricksentry-0.1.8 → bricksentry-0.1.9}/CHANGELOG.md +6 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/PKG-INFO +16 -5
- {bricksentry-0.1.8 → bricksentry-0.1.9}/README.md +15 -4
- bricksentry-0.1.9/examples/databricks/bricksentry_check_my_table.ipynb +311 -0
- bricksentry-0.1.9/examples/databricks/bricksentry_check_my_table.py +233 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/pyproject.toml +1 -1
- {bricksentry-0.1.8 → bricksentry-0.1.9}/scripts/build_notebook.py +12 -7
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/__init__.py +1 -1
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/assess.py +16 -4
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/policy.py +10 -2
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/policy_templates.py +5 -0
- bricksentry-0.1.9/tests/test_019.py +57 -0
- bricksentry-0.1.9/tests/test_check_notebook.py +153 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/.gitignore +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/CONTRIBUTING.md +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/LICENSE +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/SECURITY.md +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/action.yml +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/databricks/bricksentry.yml +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/databricks/bricksentry_quickstart.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/databricks/github-workflow.yml +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/databricks/policy.yml +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/examples/demo/agent_loop_demo.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/packages/bricksentry-mcp/LICENSE +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/packages/bricksentry-mcp/README.md +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/packages/bricksentry-mcp/src/bricksentry_mcp/__init__.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/agent_tools.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/backends/__init__.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/backends/base.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/backends/databricks_backend.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/backends/duckdb_backend.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/changes.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/cli.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/config.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/demo.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/diff.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/explain.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/github.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/lineage.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/mcp_server.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/measures.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/models.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/notify.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/preview.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/py.typed +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/src/bricksentry/report.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/conftest.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_018.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_assess_policy.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_databricks_and_uc.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_demo.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_diff.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_notebook.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_notify_templates.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_preview_agents.py +0 -0
- {bricksentry-0.1.8 → bricksentry-0.1.9}/tests/test_sample_guard_and_store.py +0 -0
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.9 (2026-11-11)
|
|
4
|
+
|
|
5
|
+
- New notebook: **what did my last pipeline run do?** Point it at a Delta table; it finds the latest data change in the table's history, compares it with the version before using two shallow clones, and shows the verdict, rules, blast radius and the `RESTORE` command. Read-only on your table. Import from `examples/databricks/bricksentry_check_my_table.py`.
|
|
6
|
+
- New issue form, "What bricksentry found", for sharing what a check caught, missed or got wrong. The notebook prefills it without table or column names.
|
|
7
|
+
- Fix: when the lineage lookup failed (for example no `SELECT` on `system.access.table_lineage`), the verdict said "diff could not run" and was raised to `needs_human`, although the diff had run. Now it adds a `lineage-unavailable` hit with a one-line reason and the summary says the blast radius is unknown. It is a `warn` in the default and finance policies and `needs_human` in strict, agent-safe, pii and certified. New policy condition: `lineage_error`.
|
|
8
|
+
|
|
3
9
|
## 0.1.8 (2026-11-11)
|
|
4
10
|
|
|
5
11
|
From the first real Slack alert sent from a Databricks workspace:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bricksentry
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.9
|
|
4
4
|
Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
|
|
5
5
|
Project-URL: Homepage, https://bricksentry.org
|
|
6
6
|
Project-URL: Documentation, https://bricksentry.org/docs
|
|
@@ -74,6 +74,17 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
|
|
|
74
74
|
|
|
75
75
|
## Run it in your Databricks workspace
|
|
76
76
|
|
|
77
|
+
### What did your last pipeline run do? (10 minutes, read-only)
|
|
78
|
+
|
|
79
|
+
> **Check-my-table notebook:** in your workspace, go to **Workspace → Import → URL** and paste
|
|
80
|
+
> `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_check_my_table.py`
|
|
81
|
+
|
|
82
|
+
Point the [check-my-table notebook](examples/databricks/bricksentry_check_my_table.py) at a Delta table your pipeline writes to. It finds the latest data change in the table's history (a WRITE, MERGE, UPDATE or DELETE), compares it with the version before, and shows the verdict a reviewer would have seen before that change shipped: rows added, removed and changed, duplicate keys, totals that moved, what depends on the table, and the `RESTORE` command to undo it. Your table is only read; the comparison uses two shallow clones in a scratch schema, dropped at the end.
|
|
83
|
+
|
|
84
|
+
If it shows you something, please [share what it found](https://github.com/bricksentry/bricksentry/issues/new?template=it_caught_this.yml) (no table names needed). Real results decide what gets built next.
|
|
85
|
+
|
|
86
|
+
### Guided tour on demo data
|
|
87
|
+
|
|
77
88
|
> **Databricks quickstart notebook:** in your workspace, go to **Workspace → Import → URL** and paste
|
|
78
89
|
> `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py`
|
|
79
90
|
|
|
@@ -194,7 +205,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
|
|
|
194
205
|
Or use the bundled GitHub Action, which also writes the report to the job summary:
|
|
195
206
|
|
|
196
207
|
```yaml
|
|
197
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
208
|
+
- uses: bricksentry/bricksentry@v0.1.9
|
|
198
209
|
with:
|
|
199
210
|
config: bricksentry.yml
|
|
200
211
|
fail-on: needs_human
|
|
@@ -219,7 +230,7 @@ jobs:
|
|
|
219
230
|
fetch-depth: 0
|
|
220
231
|
# Build this PR's version of your pipeline into a per-PR schema first,
|
|
221
232
|
# for example: databricks bundle deploy -t ci && databricks bundle run -t ci
|
|
222
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
233
|
+
- uses: bricksentry/bricksentry@v0.1.9
|
|
223
234
|
with:
|
|
224
235
|
config: bricksentry.yml
|
|
225
236
|
fail-on: needs_human
|
|
@@ -343,7 +354,7 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
|
|
|
343
354
|
|
|
344
355
|
### Policy conditions
|
|
345
356
|
|
|
346
|
-
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
|
|
357
|
+
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error` · `lineage_error`
|
|
347
358
|
|
|
348
359
|
All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
|
|
349
360
|
|
|
@@ -351,7 +362,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
|
|
|
351
362
|
|
|
352
363
|
- `CAN USE` on a SQL warehouse.
|
|
353
364
|
- `SELECT` on the tables you assess and their candidates.
|
|
354
|
-
- `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without
|
|
365
|
+
- `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing.
|
|
355
366
|
- `CREATE TABLE` on `sandbox_schema`, for `preview_write`.
|
|
356
367
|
|
|
357
368
|
## Known limits (v0.1.x)
|
|
@@ -27,6 +27,17 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
|
|
|
27
27
|
|
|
28
28
|
## Run it in your Databricks workspace
|
|
29
29
|
|
|
30
|
+
### What did your last pipeline run do? (10 minutes, read-only)
|
|
31
|
+
|
|
32
|
+
> **Check-my-table notebook:** in your workspace, go to **Workspace → Import → URL** and paste
|
|
33
|
+
> `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_check_my_table.py`
|
|
34
|
+
|
|
35
|
+
Point the [check-my-table notebook](examples/databricks/bricksentry_check_my_table.py) at a Delta table your pipeline writes to. It finds the latest data change in the table's history (a WRITE, MERGE, UPDATE or DELETE), compares it with the version before, and shows the verdict a reviewer would have seen before that change shipped: rows added, removed and changed, duplicate keys, totals that moved, what depends on the table, and the `RESTORE` command to undo it. Your table is only read; the comparison uses two shallow clones in a scratch schema, dropped at the end.
|
|
36
|
+
|
|
37
|
+
If it shows you something, please [share what it found](https://github.com/bricksentry/bricksentry/issues/new?template=it_caught_this.yml) (no table names needed). Real results decide what gets built next.
|
|
38
|
+
|
|
39
|
+
### Guided tour on demo data
|
|
40
|
+
|
|
30
41
|
> **Databricks quickstart notebook:** in your workspace, go to **Workspace → Import → URL** and paste
|
|
31
42
|
> `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py`
|
|
32
43
|
|
|
@@ -147,7 +158,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
|
|
|
147
158
|
Or use the bundled GitHub Action, which also writes the report to the job summary:
|
|
148
159
|
|
|
149
160
|
```yaml
|
|
150
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
161
|
+
- uses: bricksentry/bricksentry@v0.1.9
|
|
151
162
|
with:
|
|
152
163
|
config: bricksentry.yml
|
|
153
164
|
fail-on: needs_human
|
|
@@ -172,7 +183,7 @@ jobs:
|
|
|
172
183
|
fetch-depth: 0
|
|
173
184
|
# Build this PR's version of your pipeline into a per-PR schema first,
|
|
174
185
|
# for example: databricks bundle deploy -t ci && databricks bundle run -t ci
|
|
175
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
186
|
+
- uses: bricksentry/bricksentry@v0.1.9
|
|
176
187
|
with:
|
|
177
188
|
config: bricksentry.yml
|
|
178
189
|
fail-on: needs_human
|
|
@@ -296,7 +307,7 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
|
|
|
296
307
|
|
|
297
308
|
### Policy conditions
|
|
298
309
|
|
|
299
|
-
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
|
|
310
|
+
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error` · `lineage_error`
|
|
300
311
|
|
|
301
312
|
All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
|
|
302
313
|
|
|
@@ -304,7 +315,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
|
|
|
304
315
|
|
|
305
316
|
- `CAN USE` on a SQL warehouse.
|
|
306
317
|
- `SELECT` on the tables you assess and their candidates.
|
|
307
|
-
- `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without
|
|
318
|
+
- `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing.
|
|
308
319
|
- `CREATE TABLE` on `sandbox_schema`, for `preview_write`.
|
|
309
320
|
|
|
310
321
|
## Known limits (v0.1.x)
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
{
|
|
2
|
+
"cells": [
|
|
3
|
+
{
|
|
4
|
+
"cell_type": "markdown",
|
|
5
|
+
"metadata": {},
|
|
6
|
+
"source": [
|
|
7
|
+
"# What did my last pipeline run do? Check one of your tables with bricksentry\n",
|
|
8
|
+
"\n",
|
|
9
|
+
"**10 minutes, on your real data, without changing it.** Pick a Delta table that a pipeline writes to.\n",
|
|
10
|
+
"bricksentry finds its most recent data change in the Delta history (a WRITE, MERGE, UPDATE or DELETE) and shows\n",
|
|
11
|
+
"what a reviewer would have seen *before* that change shipped:\n",
|
|
12
|
+
"\n",
|
|
13
|
+
"- rows added, removed and changed, duplicate or NULL keys, schema changes, and totals that moved\n",
|
|
14
|
+
"- what depends on the table (Unity Catalog lineage), with owners and tags such as `certified` or `pii`\n",
|
|
15
|
+
"- a verdict from a policy (`pass`, `warn`, `needs_human` or `block`), and the `RESTORE` command to undo it\n",
|
|
16
|
+
"\n",
|
|
17
|
+
"**How it stays safe:** your table is only read. To compare two versions, the notebook makes two *shallow clones*\n",
|
|
18
|
+
"(metadata only, no data copied) in a scratch schema you choose, and drops them at the end.\n",
|
|
19
|
+
"\n",
|
|
20
|
+
"**You need:** a SQL warehouse you can use, `SELECT` on the table, `CREATE TABLE` on the scratch schema, and for the\n",
|
|
21
|
+
"blast radius `SELECT` on `system.access.table_lineage`. The table's history must still be there (not removed by `VACUUM`).\n",
|
|
22
|
+
"\n",
|
|
23
|
+
"If it shows you something useful, or something wrong, please [tell us](https://github.com/bricksentry/bricksentry/issues/new?template=it_caught_this.yml).\n",
|
|
24
|
+
"Docs: [bricksentry.org](https://bricksentry.org)"
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"cell_type": "code",
|
|
29
|
+
"execution_count": null,
|
|
30
|
+
"metadata": {},
|
|
31
|
+
"outputs": [],
|
|
32
|
+
"source": [
|
|
33
|
+
"%pip install --quiet --upgrade \"bricksentry[databricks]\""
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"cell_type": "code",
|
|
38
|
+
"execution_count": null,
|
|
39
|
+
"metadata": {},
|
|
40
|
+
"outputs": [],
|
|
41
|
+
"source": [
|
|
42
|
+
"dbutils.library.restartPython()"
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"cell_type": "markdown",
|
|
47
|
+
"metadata": {},
|
|
48
|
+
"source": [
|
|
49
|
+
"## Settings\n",
|
|
50
|
+
"Fill in the widgets at the top, then run all cells.\n",
|
|
51
|
+
"- **table:** `catalog.schema.table`, a Delta table your pipeline writes to.\n",
|
|
52
|
+
"- **keys:** the column(s) that identify a row, comma-separated (e.g. `order_id` or `customer_id, day`). Leave empty to use the table's primary key if it has one.\n",
|
|
53
|
+
"- **warehouse_id:** SQL Warehouses → your warehouse → Connection details.\n",
|
|
54
|
+
"- **scratch_schema:** `catalog.schema` for the two temporary clones. It is created if missing.\n",
|
|
55
|
+
"- **version:** leave empty to check the latest data change, or enter a table version number to check that one.\n",
|
|
56
|
+
"- **policy:** the rule set for the verdict (`default`, `strict`, `finance`, `pii`, `certified`, `agent-safe`).\n",
|
|
57
|
+
"- **sample_pct:** leave empty for a full comparison; on very large tables try `10` (a full-table checksum still catches any change the sample misses)."
|
|
58
|
+
]
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"cell_type": "code",
|
|
62
|
+
"execution_count": null,
|
|
63
|
+
"metadata": {},
|
|
64
|
+
"outputs": [],
|
|
65
|
+
"source": [
|
|
66
|
+
"import re\n",
|
|
67
|
+
"\n",
|
|
68
|
+
"dbutils.widgets.text(\"table\", \"\")\n",
|
|
69
|
+
"dbutils.widgets.text(\"keys\", \"\")\n",
|
|
70
|
+
"dbutils.widgets.text(\"warehouse_id\", \"\")\n",
|
|
71
|
+
"dbutils.widgets.text(\"scratch_schema\", \"main.bricksentry_scratch\")\n",
|
|
72
|
+
"dbutils.widgets.text(\"version\", \"\")\n",
|
|
73
|
+
"dbutils.widgets.dropdown(\"policy\", \"default\", [\"default\", \"strict\", \"finance\", \"pii\", \"certified\", \"agent-safe\"])\n",
|
|
74
|
+
"dbutils.widgets.text(\"sample_pct\", \"\")\n",
|
|
75
|
+
"\n",
|
|
76
|
+
"TABLE = dbutils.widgets.get(\"table\").strip()\n",
|
|
77
|
+
"KEYS = [k.strip() for k in dbutils.widgets.get(\"keys\").split(\",\") if k.strip()]\n",
|
|
78
|
+
"WAREHOUSE_ID = dbutils.widgets.get(\"warehouse_id\").strip()\n",
|
|
79
|
+
"SCRATCH = dbutils.widgets.get(\"scratch_schema\").strip()\n",
|
|
80
|
+
"VERSION = dbutils.widgets.get(\"version\").strip()\n",
|
|
81
|
+
"POLICY = dbutils.widgets.get(\"policy\")\n",
|
|
82
|
+
"SAMPLE = dbutils.widgets.get(\"sample_pct\").strip()\n",
|
|
83
|
+
"\n",
|
|
84
|
+
"NAME = r\"[A-Za-z0-9_]+\"\n",
|
|
85
|
+
"if not re.fullmatch(rf\"{NAME}\\.{NAME}\\.{NAME}\", TABLE):\n",
|
|
86
|
+
" raise ValueError(f\"Set the 'table' widget to catalog.schema.table (letters, digits, underscores); got {TABLE!r}\")\n",
|
|
87
|
+
"if not re.fullmatch(rf\"{NAME}\\.{NAME}\", SCRATCH):\n",
|
|
88
|
+
" raise ValueError(f\"Set 'scratch_schema' to catalog.schema; got {SCRATCH!r}\")\n",
|
|
89
|
+
"if not re.fullmatch(r\"[A-Za-z0-9]+\", WAREHOUSE_ID):\n",
|
|
90
|
+
" raise ValueError(\"Set the 'warehouse_id' widget to your SQL warehouse ID (SQL Warehouses → Connection details).\")\n",
|
|
91
|
+
"if VERSION and not VERSION.isdigit():\n",
|
|
92
|
+
" raise ValueError(f\"'version' must be a number or empty; got {VERSION!r}\")\n",
|
|
93
|
+
"SAMPLE_PCT = float(SAMPLE) if SAMPLE else None\n",
|
|
94
|
+
"\n",
|
|
95
|
+
"import bricksentry\n",
|
|
96
|
+
"from bricksentry import Config, Sentry\n",
|
|
97
|
+
"\n",
|
|
98
|
+
"sentry = Sentry(Config.from_dict({\n",
|
|
99
|
+
" \"backend\": {\"type\": \"databricks\", \"warehouse_id\": WAREHOUSE_ID},\n",
|
|
100
|
+
" \"sandbox_schema\": SCRATCH,\n",
|
|
101
|
+
" \"assessment_store\": False,\n",
|
|
102
|
+
" \"lineage\": {\"type\": \"databricks\", \"depth\": 3, \"lookback_days\": 90},\n",
|
|
103
|
+
" \"policy\": f\"builtin:{POLICY}\",\n",
|
|
104
|
+
"}))\n",
|
|
105
|
+
"db = sentry.backend\n",
|
|
106
|
+
"print(f\"bricksentry {bricksentry.__version__} · checking {TABLE} · policy {POLICY}\")"
|
|
107
|
+
]
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"cell_type": "markdown",
|
|
111
|
+
"metadata": {},
|
|
112
|
+
"source": [
|
|
113
|
+
"## 1. Recent history of the table\n",
|
|
114
|
+
"The last 15 versions from `DESCRIBE HISTORY`. bricksentry checks the most recent one that changed data,\n",
|
|
115
|
+
"comparing it with the version just before it."
|
|
116
|
+
]
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
"cell_type": "code",
|
|
120
|
+
"execution_count": null,
|
|
121
|
+
"metadata": {},
|
|
122
|
+
"outputs": [],
|
|
123
|
+
"source": [
|
|
124
|
+
"DATA_OPS = (\"WRITE\", \"MERGE\", \"UPDATE\", \"DELETE\", \"TRUNCATE\", \"STREAMING UPDATE\",\n",
|
|
125
|
+
" \"CREATE OR REPLACE TABLE AS SELECT\", \"REPLACE TABLE AS SELECT\", \"COPY INTO\")\n",
|
|
126
|
+
"\n",
|
|
127
|
+
"history = db.query(f\"DESCRIBE HISTORY {db.qualified(TABLE)} LIMIT 15\")\n",
|
|
128
|
+
"for h in history:\n",
|
|
129
|
+
" metrics = str(h.get(\"operationMetrics\") or \"\")\n",
|
|
130
|
+
" print(f\"v{h['version']:<6} {str(h.get('timestamp'))[:19]} {h.get('operation', ''):<34} {metrics[:90]}\")\n",
|
|
131
|
+
"\n",
|
|
132
|
+
"if VERSION:\n",
|
|
133
|
+
" CHECK = int(VERSION)\n",
|
|
134
|
+
"else:\n",
|
|
135
|
+
" changes = [h for h in history if str(h.get(\"operation\", \"\")).upper() in DATA_OPS and int(h[\"version\"]) > 0]\n",
|
|
136
|
+
" if not changes:\n",
|
|
137
|
+
" raise ValueError(\"No data change found in the last 15 versions. Enter a version number in the 'version' widget.\")\n",
|
|
138
|
+
" CHECK = int(changes[0][\"version\"])\n",
|
|
139
|
+
"if CHECK < 1:\n",
|
|
140
|
+
" raise ValueError(\"Version 0 is the table's creation; there is nothing before it to compare with.\")\n",
|
|
141
|
+
"op = next((h.get(\"operation\") for h in history if int(h[\"version\"]) == CHECK), \"?\")\n",
|
|
142
|
+
"print(f\"\\nChecking version {CHECK} ({op}) against version {CHECK - 1}.\")"
|
|
143
|
+
]
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
"cell_type": "markdown",
|
|
147
|
+
"metadata": {},
|
|
148
|
+
"source": [
|
|
149
|
+
"## 2. Keys\n",
|
|
150
|
+
"Rows are matched by key. If you left `keys` empty, the table's primary key constraint is used."
|
|
151
|
+
]
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
"cell_type": "code",
|
|
155
|
+
"execution_count": null,
|
|
156
|
+
"metadata": {},
|
|
157
|
+
"outputs": [],
|
|
158
|
+
"source": [
|
|
159
|
+
"if not KEYS:\n",
|
|
160
|
+
" cat, sch, tbl = TABLE.split(\".\")\n",
|
|
161
|
+
" try:\n",
|
|
162
|
+
" rows = db.query(f\"\"\"\n",
|
|
163
|
+
" SELECT k.column_name\n",
|
|
164
|
+
" FROM {db.quote(cat)}.information_schema.table_constraints c\n",
|
|
165
|
+
" JOIN {db.quote(cat)}.information_schema.key_column_usage k\n",
|
|
166
|
+
" ON k.constraint_catalog = c.constraint_catalog\n",
|
|
167
|
+
" AND k.constraint_schema = c.constraint_schema\n",
|
|
168
|
+
" AND k.constraint_name = c.constraint_name\n",
|
|
169
|
+
" WHERE c.constraint_type = 'PRIMARY KEY'\n",
|
|
170
|
+
" AND c.table_schema = '{sch}' AND c.table_name = '{tbl}'\n",
|
|
171
|
+
" ORDER BY k.ordinal_position\"\"\")\n",
|
|
172
|
+
" KEYS = [r[\"column_name\"] for r in rows]\n",
|
|
173
|
+
" except Exception as e:\n",
|
|
174
|
+
" print(\"Could not read the primary key:\", str(e)[:200])\n",
|
|
175
|
+
"if not KEYS:\n",
|
|
176
|
+
" raise ValueError(\"No primary key found. Enter the key column(s) in the 'keys' widget and run again.\")\n",
|
|
177
|
+
"print(\"Keys:\", \", \".join(KEYS))"
|
|
178
|
+
]
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
"cell_type": "markdown",
|
|
182
|
+
"metadata": {},
|
|
183
|
+
"source": [
|
|
184
|
+
"## 3. Compare the two versions and get the verdict"
|
|
185
|
+
]
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
"cell_type": "code",
|
|
189
|
+
"execution_count": null,
|
|
190
|
+
"metadata": {},
|
|
191
|
+
"outputs": [],
|
|
192
|
+
"source": [
|
|
193
|
+
"short = re.sub(r\"[^A-Za-z0-9_]\", \"_\", TABLE.split(\".\")[-1])[:40]\n",
|
|
194
|
+
"BASE = f\"{SCRATCH}.bs_check_{short}_v{CHECK - 1}\"\n",
|
|
195
|
+
"CAND = f\"{SCRATCH}.bs_check_{short}_v{CHECK}\"\n",
|
|
196
|
+
"\n",
|
|
197
|
+
"db.ensure_schema(SCRATCH)\n",
|
|
198
|
+
"assessment = None\n",
|
|
199
|
+
"try:\n",
|
|
200
|
+
" for target, v in ((BASE, CHECK - 1), (CAND, CHECK)):\n",
|
|
201
|
+
" try:\n",
|
|
202
|
+
" db.execute(f\"CREATE OR REPLACE TABLE {db.qualified(target)} \"\n",
|
|
203
|
+
" f\"SHALLOW CLONE {db.qualified(TABLE)} VERSION AS OF {v}\")\n",
|
|
204
|
+
" except Exception as e:\n",
|
|
205
|
+
" raise RuntimeError(\n",
|
|
206
|
+
" f\"Could not read version {v} of {TABLE}. Its files may have been removed by VACUUM, \"\n",
|
|
207
|
+
" f\"or you may lack CREATE TABLE on {SCRATCH}. Details: {str(e)[:300]}\") from None\n",
|
|
208
|
+
" diff = sentry.diff(BASE, CAND, keys=KEYS, table=TABLE, sample_pct=SAMPLE_PCT)\n",
|
|
209
|
+
" assessment = sentry.assess([TABLE], diffs={TABLE: diff})\n",
|
|
210
|
+
"finally:\n",
|
|
211
|
+
" for t in (BASE, CAND):\n",
|
|
212
|
+
" try:\n",
|
|
213
|
+
" db.drop(t)\n",
|
|
214
|
+
" except Exception as e:\n",
|
|
215
|
+
" print(\"Could not drop\", t, str(e)[:120])\n",
|
|
216
|
+
"\n",
|
|
217
|
+
"t = assessment.tables[0]\n",
|
|
218
|
+
"UNDO = f\"RESTORE TABLE {db.qualified(TABLE)} TO VERSION AS OF {CHECK - 1}\"\n",
|
|
219
|
+
"t.rollback = UNDO # the change already happened: undoing it means going back to the version before it\n",
|
|
220
|
+
"print(f\"VERDICT: {assessment.verdict.value.upper()} (risk {assessment.verdict.risk_tier})\\n\")\n",
|
|
221
|
+
"print(t.summary, \"\\n\")\n",
|
|
222
|
+
"for h in assessment.hits:\n",
|
|
223
|
+
" print(f\" [{h.verdict.value}] {h.rule}: {h.reason}\")\n",
|
|
224
|
+
"if assessment.notify:\n",
|
|
225
|
+
" print(\"\\nWould ask for review from:\", \", \".join(assessment.notify))\n",
|
|
226
|
+
"print(f\"\\nTo undo version {CHECK}: {UNDO}\")"
|
|
227
|
+
]
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
"cell_type": "markdown",
|
|
231
|
+
"metadata": {},
|
|
232
|
+
"source": [
|
|
233
|
+
"### The pull-request comment a reviewer would have seen"
|
|
234
|
+
]
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
"cell_type": "code",
|
|
238
|
+
"execution_count": null,
|
|
239
|
+
"metadata": {},
|
|
240
|
+
"outputs": [],
|
|
241
|
+
"source": [
|
|
242
|
+
"from bricksentry.report import to_markdown\n",
|
|
243
|
+
"\n",
|
|
244
|
+
"report = to_markdown(assessment)\n",
|
|
245
|
+
"try:\n",
|
|
246
|
+
" from IPython.display import Markdown, display\n",
|
|
247
|
+
" display(Markdown(report))\n",
|
|
248
|
+
"except Exception:\n",
|
|
249
|
+
" print(report)"
|
|
250
|
+
]
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
"cell_type": "markdown",
|
|
254
|
+
"metadata": {},
|
|
255
|
+
"source": [
|
|
256
|
+
"## 4. Tell us what it found (optional, 1 minute)\n",
|
|
257
|
+
"Did it catch something, miss something, or get it wrong? The link below opens a short GitHub form with the\n",
|
|
258
|
+
"verdict and rules filled in. **No table or column names are included**; add only what you're happy to share."
|
|
259
|
+
]
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
"cell_type": "code",
|
|
263
|
+
"execution_count": null,
|
|
264
|
+
"metadata": {},
|
|
265
|
+
"outputs": [],
|
|
266
|
+
"source": [
|
|
267
|
+
"from urllib.parse import urlencode\n",
|
|
268
|
+
"\n",
|
|
269
|
+
"rules = \"; \".join(sorted({f\"{h.rule} ({h.verdict.value})\" for h in assessment.hits})) or \"none\"\n",
|
|
270
|
+
"d = t.diff\n",
|
|
271
|
+
"facts = (f\"rows {d.base_rows:,} -> {d.candidate_rows:,}; added {d.added_rows:,}, removed {d.removed_rows:,}, \"\n",
|
|
272
|
+
" f\"changed {d.changed_rows:,}; downstream assets {len(t.downstream)}\") if d else \"diff unavailable\"\n",
|
|
273
|
+
"params = {\n",
|
|
274
|
+
" \"template\": \"it_caught_this.yml\",\n",
|
|
275
|
+
" \"title\": f\"[check] {assessment.verdict.value} on a {op} change\",\n",
|
|
276
|
+
" \"verdict\": assessment.verdict.value,\n",
|
|
277
|
+
" \"rules\": rules,\n",
|
|
278
|
+
" \"facts\": f\"Operation: {op}\\n{facts}\",\n",
|
|
279
|
+
" \"version\": bricksentry.__version__,\n",
|
|
280
|
+
"}\n",
|
|
281
|
+
"print(\"Share what it found:\\nhttps://github.com/bricksentry/bricksentry/issues/new?\" + urlencode(params))"
|
|
282
|
+
]
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
"cell_type": "markdown",
|
|
286
|
+
"metadata": {},
|
|
287
|
+
"source": [
|
|
288
|
+
"## Next steps\n",
|
|
289
|
+
"- **Check every change before it ships:** run the same check in CI on pull requests. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).\n",
|
|
290
|
+
"- **Let AI agents check their own changes:** `uvx bricksentry-mcp`. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).\n",
|
|
291
|
+
"- **Get alerts:** set a Slack or Teams webhook and run `bricksentry test-alert`. See [bricksentry.org/docs/configuration](https://bricksentry.org/docs/configuration)."
|
|
292
|
+
]
|
|
293
|
+
}
|
|
294
|
+
],
|
|
295
|
+
"metadata": {
|
|
296
|
+
"kernelspec": {
|
|
297
|
+
"display_name": "Python 3",
|
|
298
|
+
"language": "python",
|
|
299
|
+
"name": "python3"
|
|
300
|
+
},
|
|
301
|
+
"language_info": {
|
|
302
|
+
"name": "python"
|
|
303
|
+
},
|
|
304
|
+
"application/vnd.databricks.v1+notebook": {
|
|
305
|
+
"notebookName": "bricksentry_check_my_table",
|
|
306
|
+
"language": "python"
|
|
307
|
+
}
|
|
308
|
+
},
|
|
309
|
+
"nbformat": 4,
|
|
310
|
+
"nbformat_minor": 5
|
|
311
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# Databricks notebook source
|
|
2
|
+
# MAGIC %md
|
|
3
|
+
# MAGIC # What did my last pipeline run do? Check one of your tables with bricksentry
|
|
4
|
+
# MAGIC
|
|
5
|
+
# MAGIC **10 minutes, on your real data, without changing it.** Pick a Delta table that a pipeline writes to.
|
|
6
|
+
# MAGIC bricksentry finds its most recent data change in the Delta history (a WRITE, MERGE, UPDATE or DELETE) and shows
|
|
7
|
+
# MAGIC what a reviewer would have seen *before* that change shipped:
|
|
8
|
+
# MAGIC
|
|
9
|
+
# MAGIC - rows added, removed and changed, duplicate or NULL keys, schema changes, and totals that moved
|
|
10
|
+
# MAGIC - what depends on the table (Unity Catalog lineage), with owners and tags such as `certified` or `pii`
|
|
11
|
+
# MAGIC - a verdict from a policy (`pass`, `warn`, `needs_human` or `block`), and the `RESTORE` command to undo it
|
|
12
|
+
# MAGIC
|
|
13
|
+
# MAGIC **How it stays safe:** your table is only read. To compare two versions, the notebook makes two *shallow clones*
|
|
14
|
+
# MAGIC (metadata only, no data copied) in a scratch schema you choose, and drops them at the end.
|
|
15
|
+
# MAGIC
|
|
16
|
+
# MAGIC **You need:** a SQL warehouse you can use, `SELECT` on the table, `CREATE TABLE` on the scratch schema, and for the
|
|
17
|
+
# MAGIC blast radius `SELECT` on `system.access.table_lineage`. The table's history must still be there (not removed by `VACUUM`).
|
|
18
|
+
# MAGIC
|
|
19
|
+
# MAGIC If it shows you something useful, or something wrong, please [tell us](https://github.com/bricksentry/bricksentry/issues/new?template=it_caught_this.yml).
|
|
20
|
+
# MAGIC Docs: [bricksentry.org](https://bricksentry.org)
|
|
21
|
+
|
|
22
|
+
# COMMAND ----------
|
|
23
|
+
|
|
24
|
+
# MAGIC %pip install --quiet --upgrade "bricksentry[databricks]"
|
|
25
|
+
|
|
26
|
+
# COMMAND ----------
|
|
27
|
+
|
|
28
|
+
dbutils.library.restartPython()
|
|
29
|
+
|
|
30
|
+
# COMMAND ----------
|
|
31
|
+
|
|
32
|
+
# MAGIC %md
|
|
33
|
+
# MAGIC ## Settings
|
|
34
|
+
# MAGIC Fill in the widgets at the top, then run all cells.
|
|
35
|
+
# MAGIC - **table:** `catalog.schema.table`, a Delta table your pipeline writes to.
|
|
36
|
+
# MAGIC - **keys:** the column(s) that identify a row, comma-separated (e.g. `order_id` or `customer_id, day`). Leave empty to use the table's primary key if it has one.
|
|
37
|
+
# MAGIC - **warehouse_id:** SQL Warehouses → your warehouse → Connection details.
|
|
38
|
+
# MAGIC - **scratch_schema:** `catalog.schema` for the two temporary clones. It is created if missing.
|
|
39
|
+
# MAGIC - **version:** leave empty to check the latest data change, or enter a table version number to check that one.
|
|
40
|
+
# MAGIC - **policy:** the rule set for the verdict (`default`, `strict`, `finance`, `pii`, `certified`, `agent-safe`).
|
|
41
|
+
# MAGIC - **sample_pct:** leave empty for a full comparison; on very large tables try `10` (a full-table checksum still catches any change the sample misses).
|
|
42
|
+
|
|
43
|
+
# COMMAND ----------
|
|
44
|
+
|
|
45
|
+
import re
|
|
46
|
+
|
|
47
|
+
dbutils.widgets.text("table", "")
|
|
48
|
+
dbutils.widgets.text("keys", "")
|
|
49
|
+
dbutils.widgets.text("warehouse_id", "")
|
|
50
|
+
dbutils.widgets.text("scratch_schema", "main.bricksentry_scratch")
|
|
51
|
+
dbutils.widgets.text("version", "")
|
|
52
|
+
dbutils.widgets.dropdown("policy", "default", ["default", "strict", "finance", "pii", "certified", "agent-safe"])
|
|
53
|
+
dbutils.widgets.text("sample_pct", "")
|
|
54
|
+
|
|
55
|
+
TABLE = dbutils.widgets.get("table").strip()
|
|
56
|
+
KEYS = [k.strip() for k in dbutils.widgets.get("keys").split(",") if k.strip()]
|
|
57
|
+
WAREHOUSE_ID = dbutils.widgets.get("warehouse_id").strip()
|
|
58
|
+
SCRATCH = dbutils.widgets.get("scratch_schema").strip()
|
|
59
|
+
VERSION = dbutils.widgets.get("version").strip()
|
|
60
|
+
POLICY = dbutils.widgets.get("policy")
|
|
61
|
+
SAMPLE = dbutils.widgets.get("sample_pct").strip()
|
|
62
|
+
|
|
63
|
+
NAME = r"[A-Za-z0-9_]+"
|
|
64
|
+
if not re.fullmatch(rf"{NAME}\.{NAME}\.{NAME}", TABLE):
|
|
65
|
+
raise ValueError(f"Set the 'table' widget to catalog.schema.table (letters, digits, underscores); got {TABLE!r}")
|
|
66
|
+
if not re.fullmatch(rf"{NAME}\.{NAME}", SCRATCH):
|
|
67
|
+
raise ValueError(f"Set 'scratch_schema' to catalog.schema; got {SCRATCH!r}")
|
|
68
|
+
if not re.fullmatch(r"[A-Za-z0-9]+", WAREHOUSE_ID):
|
|
69
|
+
raise ValueError("Set the 'warehouse_id' widget to your SQL warehouse ID (SQL Warehouses → Connection details).")
|
|
70
|
+
if VERSION and not VERSION.isdigit():
|
|
71
|
+
raise ValueError(f"'version' must be a number or empty; got {VERSION!r}")
|
|
72
|
+
SAMPLE_PCT = float(SAMPLE) if SAMPLE else None
|
|
73
|
+
|
|
74
|
+
import bricksentry
|
|
75
|
+
from bricksentry import Config, Sentry
|
|
76
|
+
|
|
77
|
+
sentry = Sentry(Config.from_dict({
|
|
78
|
+
"backend": {"type": "databricks", "warehouse_id": WAREHOUSE_ID},
|
|
79
|
+
"sandbox_schema": SCRATCH,
|
|
80
|
+
"assessment_store": False,
|
|
81
|
+
"lineage": {"type": "databricks", "depth": 3, "lookback_days": 90},
|
|
82
|
+
"policy": f"builtin:{POLICY}",
|
|
83
|
+
}))
|
|
84
|
+
db = sentry.backend
|
|
85
|
+
print(f"bricksentry {bricksentry.__version__} · checking {TABLE} · policy {POLICY}")
|
|
86
|
+
|
|
87
|
+
# COMMAND ----------
|
|
88
|
+
|
|
89
|
+
# MAGIC %md
|
|
90
|
+
# MAGIC ## 1. Recent history of the table
|
|
91
|
+
# MAGIC The last 15 versions from `DESCRIBE HISTORY`. bricksentry checks the most recent one that changed data,
|
|
92
|
+
# MAGIC comparing it with the version just before it.
|
|
93
|
+
|
|
94
|
+
# COMMAND ----------
|
|
95
|
+
|
|
96
|
+
DATA_OPS = ("WRITE", "MERGE", "UPDATE", "DELETE", "TRUNCATE", "STREAMING UPDATE",
|
|
97
|
+
"CREATE OR REPLACE TABLE AS SELECT", "REPLACE TABLE AS SELECT", "COPY INTO")
|
|
98
|
+
|
|
99
|
+
history = db.query(f"DESCRIBE HISTORY {db.qualified(TABLE)} LIMIT 15")
|
|
100
|
+
for h in history:
|
|
101
|
+
metrics = str(h.get("operationMetrics") or "")
|
|
102
|
+
print(f"v{h['version']:<6} {str(h.get('timestamp'))[:19]} {h.get('operation', ''):<34} {metrics[:90]}")
|
|
103
|
+
|
|
104
|
+
if VERSION:
|
|
105
|
+
CHECK = int(VERSION)
|
|
106
|
+
else:
|
|
107
|
+
changes = [h for h in history if str(h.get("operation", "")).upper() in DATA_OPS and int(h["version"]) > 0]
|
|
108
|
+
if not changes:
|
|
109
|
+
raise ValueError("No data change found in the last 15 versions. Enter a version number in the 'version' widget.")
|
|
110
|
+
CHECK = int(changes[0]["version"])
|
|
111
|
+
if CHECK < 1:
|
|
112
|
+
raise ValueError("Version 0 is the table's creation; there is nothing before it to compare with.")
|
|
113
|
+
op = next((h.get("operation") for h in history if int(h["version"]) == CHECK), "?")
|
|
114
|
+
print(f"\nChecking version {CHECK} ({op}) against version {CHECK - 1}.")
|
|
115
|
+
|
|
116
|
+
# COMMAND ----------
|
|
117
|
+
|
|
118
|
+
# MAGIC %md
|
|
119
|
+
# MAGIC ## 2. Keys
|
|
120
|
+
# MAGIC Rows are matched by key. If you left `keys` empty, the table's primary key constraint is used.
|
|
121
|
+
|
|
122
|
+
# COMMAND ----------
|
|
123
|
+
|
|
124
|
+
if not KEYS:
|
|
125
|
+
cat, sch, tbl = TABLE.split(".")
|
|
126
|
+
try:
|
|
127
|
+
rows = db.query(f"""
|
|
128
|
+
SELECT k.column_name
|
|
129
|
+
FROM {db.quote(cat)}.information_schema.table_constraints c
|
|
130
|
+
JOIN {db.quote(cat)}.information_schema.key_column_usage k
|
|
131
|
+
ON k.constraint_catalog = c.constraint_catalog
|
|
132
|
+
AND k.constraint_schema = c.constraint_schema
|
|
133
|
+
AND k.constraint_name = c.constraint_name
|
|
134
|
+
WHERE c.constraint_type = 'PRIMARY KEY'
|
|
135
|
+
AND c.table_schema = '{sch}' AND c.table_name = '{tbl}'
|
|
136
|
+
ORDER BY k.ordinal_position""")
|
|
137
|
+
KEYS = [r["column_name"] for r in rows]
|
|
138
|
+
except Exception as e:
|
|
139
|
+
print("Could not read the primary key:", str(e)[:200])
|
|
140
|
+
if not KEYS:
|
|
141
|
+
raise ValueError("No primary key found. Enter the key column(s) in the 'keys' widget and run again.")
|
|
142
|
+
print("Keys:", ", ".join(KEYS))
|
|
143
|
+
|
|
144
|
+
# COMMAND ----------
|
|
145
|
+
|
|
146
|
+
# MAGIC %md
|
|
147
|
+
# MAGIC ## 3. Compare the two versions and get the verdict
|
|
148
|
+
|
|
149
|
+
# COMMAND ----------
|
|
150
|
+
|
|
151
|
+
short = re.sub(r"[^A-Za-z0-9_]", "_", TABLE.split(".")[-1])[:40]
|
|
152
|
+
BASE = f"{SCRATCH}.bs_check_{short}_v{CHECK - 1}"
|
|
153
|
+
CAND = f"{SCRATCH}.bs_check_{short}_v{CHECK}"
|
|
154
|
+
|
|
155
|
+
db.ensure_schema(SCRATCH)
|
|
156
|
+
assessment = None
|
|
157
|
+
try:
|
|
158
|
+
for target, v in ((BASE, CHECK - 1), (CAND, CHECK)):
|
|
159
|
+
try:
|
|
160
|
+
db.execute(f"CREATE OR REPLACE TABLE {db.qualified(target)} "
|
|
161
|
+
f"SHALLOW CLONE {db.qualified(TABLE)} VERSION AS OF {v}")
|
|
162
|
+
except Exception as e:
|
|
163
|
+
raise RuntimeError(
|
|
164
|
+
f"Could not read version {v} of {TABLE}. Its files may have been removed by VACUUM, "
|
|
165
|
+
f"or you may lack CREATE TABLE on {SCRATCH}. Details: {str(e)[:300]}") from None
|
|
166
|
+
diff = sentry.diff(BASE, CAND, keys=KEYS, table=TABLE, sample_pct=SAMPLE_PCT)
|
|
167
|
+
assessment = sentry.assess([TABLE], diffs={TABLE: diff})
|
|
168
|
+
finally:
|
|
169
|
+
for t in (BASE, CAND):
|
|
170
|
+
try:
|
|
171
|
+
db.drop(t)
|
|
172
|
+
except Exception as e:
|
|
173
|
+
print("Could not drop", t, str(e)[:120])
|
|
174
|
+
|
|
175
|
+
t = assessment.tables[0]
|
|
176
|
+
UNDO = f"RESTORE TABLE {db.qualified(TABLE)} TO VERSION AS OF {CHECK - 1}"
|
|
177
|
+
t.rollback = UNDO # the change already happened: undoing it means going back to the version before it
|
|
178
|
+
print(f"VERDICT: {assessment.verdict.value.upper()} (risk {assessment.verdict.risk_tier})\n")
|
|
179
|
+
print(t.summary, "\n")
|
|
180
|
+
for h in assessment.hits:
|
|
181
|
+
print(f" [{h.verdict.value}] {h.rule}: {h.reason}")
|
|
182
|
+
if assessment.notify:
|
|
183
|
+
print("\nWould ask for review from:", ", ".join(assessment.notify))
|
|
184
|
+
print(f"\nTo undo version {CHECK}: {UNDO}")
|
|
185
|
+
|
|
186
|
+
# COMMAND ----------
|
|
187
|
+
|
|
188
|
+
# MAGIC %md
|
|
189
|
+
# MAGIC ### The pull-request comment a reviewer would have seen
|
|
190
|
+
|
|
191
|
+
# COMMAND ----------
|
|
192
|
+
|
|
193
|
+
from bricksentry.report import to_markdown
|
|
194
|
+
|
|
195
|
+
report = to_markdown(assessment)
|
|
196
|
+
try:
|
|
197
|
+
from IPython.display import Markdown, display
|
|
198
|
+
display(Markdown(report))
|
|
199
|
+
except Exception:
|
|
200
|
+
print(report)
|
|
201
|
+
|
|
202
|
+
# COMMAND ----------
|
|
203
|
+
|
|
204
|
+
# MAGIC %md
|
|
205
|
+
# MAGIC ## 4. Tell us what it found (optional, 1 minute)
|
|
206
|
+
# MAGIC Did it catch something, miss something, or get it wrong? The link below opens a short GitHub form with the
|
|
207
|
+
# MAGIC verdict and rules filled in. **No table or column names are included**; add only what you're happy to share.
|
|
208
|
+
|
|
209
|
+
# COMMAND ----------
|
|
210
|
+
|
|
211
|
+
from urllib.parse import urlencode
|
|
212
|
+
|
|
213
|
+
rules = "; ".join(sorted({f"{h.rule} ({h.verdict.value})" for h in assessment.hits})) or "none"
|
|
214
|
+
d = t.diff
|
|
215
|
+
facts = (f"rows {d.base_rows:,} -> {d.candidate_rows:,}; added {d.added_rows:,}, removed {d.removed_rows:,}, "
|
|
216
|
+
f"changed {d.changed_rows:,}; downstream assets {len(t.downstream)}") if d else "diff unavailable"
|
|
217
|
+
params = {
|
|
218
|
+
"template": "it_caught_this.yml",
|
|
219
|
+
"title": f"[check] {assessment.verdict.value} on a {op} change",
|
|
220
|
+
"verdict": assessment.verdict.value,
|
|
221
|
+
"rules": rules,
|
|
222
|
+
"facts": f"Operation: {op}\n{facts}",
|
|
223
|
+
"version": bricksentry.__version__,
|
|
224
|
+
}
|
|
225
|
+
print("Share what it found:\nhttps://github.com/bricksentry/bricksentry/issues/new?" + urlencode(params))
|
|
226
|
+
|
|
227
|
+
# COMMAND ----------
|
|
228
|
+
|
|
229
|
+
# MAGIC %md
|
|
230
|
+
# MAGIC ## Next steps
|
|
231
|
+
# MAGIC - **Check every change before it ships:** run the same check in CI on pull requests. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).
|
|
232
|
+
# MAGIC - **Let AI agents check their own changes:** `uvx bricksentry-mcp`. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).
|
|
233
|
+
# MAGIC - **Get alerts:** set a Slack or Teams webhook and run `bricksentry test-alert`. See [bricksentry.org/docs/configuration](https://bricksentry.org/docs/configuration).
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bricksentry"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.9"
|
|
8
8
|
description = "Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Build
|
|
1
|
+
"""Build the .ipynb copies of the Databricks source notebooks in examples/databricks.
|
|
2
2
|
|
|
3
3
|
python scripts/build_notebook.py
|
|
4
4
|
|
|
@@ -11,7 +11,11 @@ import json
|
|
|
11
11
|
from pathlib import Path
|
|
12
12
|
|
|
13
13
|
ROOT = Path(__file__).resolve().parents[1]
|
|
14
|
-
|
|
14
|
+
SOURCES = [
|
|
15
|
+
ROOT / "examples" / "databricks" / "bricksentry_quickstart.py",
|
|
16
|
+
ROOT / "examples" / "databricks" / "bricksentry_check_my_table.py",
|
|
17
|
+
]
|
|
18
|
+
SRC = SOURCES[0]
|
|
15
19
|
OUT = SRC.with_suffix(".ipynb")
|
|
16
20
|
|
|
17
21
|
|
|
@@ -43,13 +47,13 @@ def _code(lines: list[str]) -> dict:
|
|
|
43
47
|
return {"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": _src(lines)}
|
|
44
48
|
|
|
45
49
|
|
|
46
|
-
def build() -> dict:
|
|
50
|
+
def build(src: Path = SRC) -> dict:
|
|
47
51
|
return {
|
|
48
|
-
"cells": cells_from_source(
|
|
52
|
+
"cells": cells_from_source(src.read_text()),
|
|
49
53
|
"metadata": {
|
|
50
54
|
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
|
|
51
55
|
"language_info": {"name": "python"},
|
|
52
|
-
"application/vnd.databricks.v1+notebook": {"notebookName":
|
|
56
|
+
"application/vnd.databricks.v1+notebook": {"notebookName": src.stem, "language": "python"},
|
|
53
57
|
},
|
|
54
58
|
"nbformat": 4,
|
|
55
59
|
"nbformat_minor": 5,
|
|
@@ -57,5 +61,6 @@ def build() -> dict:
|
|
|
57
61
|
|
|
58
62
|
|
|
59
63
|
if __name__ == "__main__":
|
|
60
|
-
|
|
61
|
-
|
|
64
|
+
for src in SOURCES:
|
|
65
|
+
src.with_suffix(".ipynb").write_text(json.dumps(build(src), indent=1, ensure_ascii=False) + "\n")
|
|
66
|
+
print("wrote", src.with_suffix(".ipynb").relative_to(ROOT))
|
|
@@ -96,15 +96,21 @@ class Sentry:
|
|
|
96
96
|
diff = self.diff(table, cand, table=table)
|
|
97
97
|
except Exception as e: # report, don't crash: an agent needs a verdict
|
|
98
98
|
err = str(e)
|
|
99
|
+
lineage_err: str | None = None
|
|
99
100
|
try:
|
|
100
101
|
nodes = self.downstream(table)
|
|
101
|
-
except Exception as e:
|
|
102
|
+
except Exception as e: # e.g. no SELECT on system.access.table_lineage
|
|
102
103
|
nodes = []
|
|
103
|
-
|
|
104
|
+
lineage_err = _first_line(e)
|
|
104
105
|
owner, tags = self.lineage.owner_and_tags(table)
|
|
105
106
|
measures = self.config.spec(table).measures
|
|
106
|
-
verdict, hits = self.policy.evaluate(
|
|
107
|
-
|
|
107
|
+
verdict, hits = self.policy.evaluate(
|
|
108
|
+
table, diff, nodes, tags, diff_error=err, measures=measures, lineage_error=lineage_err
|
|
109
|
+
)
|
|
110
|
+
summary = (explain_diff(diff, measures) if diff else f"{table}: diff unavailable ({err}).") + " " + (
|
|
111
|
+
f"{table}: blast radius unknown, lineage lookup failed ({lineage_err})."
|
|
112
|
+
if lineage_err else explain_impact(table, nodes)
|
|
113
|
+
)
|
|
108
114
|
ta = TableAssessment(
|
|
109
115
|
table=table,
|
|
110
116
|
diff=diff,
|
|
@@ -204,3 +210,9 @@ class Sentry:
|
|
|
204
210
|
|
|
205
211
|
def get_diff(self, table: str) -> TableDiff | None:
|
|
206
212
|
return self._diffs.get(table)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _first_line(e: Exception, limit: int = 200) -> str:
|
|
216
|
+
"""A short, single-line error for verdict reasons and alerts."""
|
|
217
|
+
text = (str(e).strip().splitlines() or [type(e).__name__])[0]
|
|
218
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
@@ -44,6 +44,7 @@ DEFAULT_POLICY: dict[str, Any] = {
|
|
|
44
44
|
"notify_owners_on": "needs_human",
|
|
45
45
|
"rules": [
|
|
46
46
|
{"name": "diff-failed", "when": {"diff_error": True}, "then": "needs_human"},
|
|
47
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "warn"},
|
|
47
48
|
{"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
|
|
48
49
|
{"name": "null-keys", "when": {"null_keys": True}, "then": "warn"},
|
|
49
50
|
{"name": "dropped-column", "when": {"column_removed": True}, "then": "needs_human"},
|
|
@@ -63,7 +64,7 @@ KNOWN_CONDITIONS = {
|
|
|
63
64
|
"removed_pct_gt", "added_pct_gt", "changed_pct_gt", "row_count_change_pct_gt",
|
|
64
65
|
"row_count_drop_pct_gt", "column_removed", "column_type_changed", "column_added",
|
|
65
66
|
"duplicate_keys", "null_keys", "column", "sum_change_pct_gt", "null_increase_gt",
|
|
66
|
-
"any_change", "diff_error",
|
|
67
|
+
"any_change", "diff_error", "lineage_error",
|
|
67
68
|
}
|
|
68
69
|
|
|
69
70
|
|
|
@@ -91,10 +92,11 @@ class Policy:
|
|
|
91
92
|
tags: dict[str, str],
|
|
92
93
|
diff_error: str | None = None,
|
|
93
94
|
measures: list[str] | str | None = None,
|
|
95
|
+
lineage_error: str | None = None,
|
|
94
96
|
) -> tuple[Verdict, list[RuleHit]]:
|
|
95
97
|
hits: list[RuleHit] = []
|
|
96
98
|
for r in self.rules:
|
|
97
|
-
ok, reason = _match(r.get("when") or {}, table, diff, downstream, tags, diff_error, measures)
|
|
99
|
+
ok, reason = _match(r.get("when") or {}, table, diff, downstream, tags, diff_error, measures, lineage_error)
|
|
98
100
|
if ok:
|
|
99
101
|
hits.append(RuleHit(rule=r.get("name", "unnamed"), verdict=Verdict(r.get("then", "warn")), table=table, reason=reason))
|
|
100
102
|
verdict = Verdict.worst([self.default] + [h.verdict for h in hits])
|
|
@@ -121,6 +123,7 @@ def _match(
|
|
|
121
123
|
tags: dict[str, str],
|
|
122
124
|
diff_error: str | None,
|
|
123
125
|
measures: list[str] | str | None = None,
|
|
126
|
+
lineage_error: str | None = None,
|
|
124
127
|
) -> tuple[bool, str]:
|
|
125
128
|
reasons: list[str] = []
|
|
126
129
|
for cond, val in when.items():
|
|
@@ -131,6 +134,11 @@ def _match(
|
|
|
131
134
|
return False, ""
|
|
132
135
|
reasons.append(f"diff could not run: {diff_error}")
|
|
133
136
|
continue
|
|
137
|
+
if cond == "lineage_error":
|
|
138
|
+
if bool(lineage_error) != bool(val):
|
|
139
|
+
return False, ""
|
|
140
|
+
reasons.append(f"blast radius unknown, lineage lookup failed: {lineage_error}")
|
|
141
|
+
continue
|
|
134
142
|
if cond == "table":
|
|
135
143
|
if not fnmatch.fnmatch(table.lower(), str(val).lower()):
|
|
136
144
|
return False, ""
|
|
@@ -38,6 +38,7 @@ TEMPLATES: dict[str, dict[str, Any]] = {
|
|
|
38
38
|
"notify_owners_on": "warn",
|
|
39
39
|
"rules": [
|
|
40
40
|
{"name": "diff-failed", "when": {"diff_error": True}, "then": "block"},
|
|
41
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "needs_human"},
|
|
41
42
|
{"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
|
|
42
43
|
{"name": "null-keys", "when": {"null_keys": True}, "then": "needs_human"},
|
|
43
44
|
{"name": "dropped-column", "when": {"column_removed": True}, "then": "block"},
|
|
@@ -58,6 +59,7 @@ TEMPLATES: dict[str, dict[str, Any]] = {
|
|
|
58
59
|
"notify_owners_on": "needs_human",
|
|
59
60
|
"rules": [
|
|
60
61
|
{"name": "diff-failed", "when": {"diff_error": True}, "then": "block"},
|
|
62
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "needs_human"},
|
|
61
63
|
{"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
|
|
62
64
|
{"name": "dropped-column", "when": {"column_removed": True}, "then": "block"},
|
|
63
65
|
{"name": "null-keys", "when": {"null_keys": True}, "then": "needs_human"},
|
|
@@ -78,6 +80,7 @@ TEMPLATES: dict[str, dict[str, Any]] = {
|
|
|
78
80
|
"default": "pass",
|
|
79
81
|
"notify_owners_on": "needs_human",
|
|
80
82
|
"rules": _CORE + [
|
|
83
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "needs_human"},
|
|
81
84
|
{"name": "pii-table-changed", "when": {"tag": "pii", "any_change": True}, "then": "needs_human"},
|
|
82
85
|
{"name": "pii-new-column", "when": {"tag": "pii", "column_added": True}, "then": "needs_human"},
|
|
83
86
|
{"name": "pii-downstream", "when": {"downstream_tag": "pii", "any_change": True}, "then": "needs_human"},
|
|
@@ -91,6 +94,7 @@ TEMPLATES: dict[str, dict[str, Any]] = {
|
|
|
91
94
|
"default": "pass",
|
|
92
95
|
"notify_owners_on": "needs_human",
|
|
93
96
|
"rules": _CORE + [
|
|
97
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "needs_human"},
|
|
94
98
|
{"name": "certified-table-changed", "when": {"tag": "certified", "any_change": True}, "then": "needs_human"},
|
|
95
99
|
{"name": "certified-schema-change", "when": {"tag": "certified", "column_type_changed": True}, "then": "block"},
|
|
96
100
|
{"name": "certified-downstream", "when": {"downstream_tag": "certified", "any_change": True}, "then": "needs_human"},
|
|
@@ -105,6 +109,7 @@ TEMPLATES: dict[str, dict[str, Any]] = {
|
|
|
105
109
|
"default": "pass",
|
|
106
110
|
"notify_owners_on": "needs_human",
|
|
107
111
|
"rules": _CORE + [
|
|
112
|
+
{"name": "lineage-unavailable", "when": {"lineage_error": True}, "then": "warn"},
|
|
108
113
|
{"name": "numeric-total-moved", "when": {"sum_change_pct_gt": 0.5}, "then": "needs_human"},
|
|
109
114
|
{"name": "row-loss", "when": {"removed_pct_gt": 0.1}, "then": "needs_human"},
|
|
110
115
|
{"name": "row-count-drop", "when": {"row_count_drop_pct_gt": 0.1}, "then": "needs_human"},
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""0.1.9: a failed lineage lookup is reported as unknown blast radius, not as a failed diff."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from bricksentry import Config, Sentry
|
|
6
|
+
from bricksentry.policy import KNOWN_CONDITIONS
|
|
7
|
+
from bricksentry.policy_templates import TEMPLATES
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _broken_lineage(sentry, monkeypatch):
|
|
11
|
+
def boom(*a, **k):
|
|
12
|
+
raise PermissionError("PERMISSION_DENIED: User does not have SELECT on table system.access.table_lineage\n"
|
|
13
|
+
" at line 1\n very long stack")
|
|
14
|
+
monkeypatch.setattr(sentry.lineage, "downstream", boom)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _candidate(backend):
|
|
18
|
+
backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
|
|
19
|
+
backend.execute("UPDATE sales_ci.orders SET amount = amount + 1 WHERE order_id <= 5")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_lineage_failure_is_a_warning_not_a_diff_failure(sentry, backend, monkeypatch):
|
|
23
|
+
_candidate(backend)
|
|
24
|
+
_broken_lineage(sentry, monkeypatch)
|
|
25
|
+
a = sentry.assess(["sales.orders"])
|
|
26
|
+
rules = {h.rule: h for h in a.hits}
|
|
27
|
+
assert "diff-failed" not in rules
|
|
28
|
+
assert rules["lineage-unavailable"].verdict.value == "warn"
|
|
29
|
+
assert "PERMISSION_DENIED" in rules["lineage-unavailable"].reason
|
|
30
|
+
assert "\n" not in rules["lineage-unavailable"].reason # one line, no stack
|
|
31
|
+
assert a.verdict.value == "warn"
|
|
32
|
+
t = a.tables[0]
|
|
33
|
+
assert t.diff is not None and t.diff.changed_rows == 5 # the diff still ran
|
|
34
|
+
assert "blast radius unknown" in t.summary
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_strict_template_asks_a_human_when_lineage_is_unknown(backend, config, monkeypatch):
|
|
38
|
+
_candidate(backend)
|
|
39
|
+
cfg = Config.from_dict({"tables": {"sales.orders": {"keys": ["order_id"]}}, "policy": "builtin:strict",
|
|
40
|
+
"lineage": {"type": "static", "edges": {}}})
|
|
41
|
+
s = Sentry(cfg, backend=backend)
|
|
42
|
+
_broken_lineage(s, monkeypatch)
|
|
43
|
+
a = s.assess(["sales.orders"])
|
|
44
|
+
assert any(h.rule == "lineage-unavailable" and h.verdict.value == "needs_human" for h in a.hits)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_every_template_handles_lineage_errors():
|
|
48
|
+
assert "lineage_error" in KNOWN_CONDITIONS
|
|
49
|
+
for name, t in TEMPLATES.items():
|
|
50
|
+
conds = [r["when"] for r in t["policy"]["rules"]]
|
|
51
|
+
assert {"lineage_error": True} in conds, name
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_working_lineage_has_no_lineage_hit(sentry, backend):
|
|
55
|
+
_candidate(backend)
|
|
56
|
+
a = sentry.assess(["sales.orders"])
|
|
57
|
+
assert all(h.rule != "lineage-unavailable" for h in a.hits)
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Run the "check my table" Databricks notebook end to end on DuckDB.
|
|
2
|
+
|
|
3
|
+
Databricks-only statements (DESCRIBE HISTORY, SHALLOW CLONE ... VERSION AS OF, the
|
|
4
|
+
primary-key lookup) are answered by a small fake backend, so every Python line of the
|
|
5
|
+
notebook runs exactly as written.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
import types
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from urllib.parse import parse_qs, urlparse
|
|
16
|
+
|
|
17
|
+
import pytest
|
|
18
|
+
|
|
19
|
+
import bricksentry.assess as assess_mod
|
|
20
|
+
from bricksentry.backends.duckdb_backend import DuckDBBackend
|
|
21
|
+
|
|
22
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
23
|
+
NB = ROOT / "examples" / "databricks" / "bricksentry_check_my_table.py"
|
|
24
|
+
sys.path.insert(0, str(ROOT / "scripts"))
|
|
25
|
+
import build_notebook # noqa: E402
|
|
26
|
+
|
|
27
|
+
HISTORY = [
|
|
28
|
+
{"version": "3", "timestamp": "2026-11-11 10:00:00", "operation": "OPTIMIZE", "operationMetrics": "{}"},
|
|
29
|
+
{"version": "2", "timestamp": "2026-11-11 09:00:00", "operation": "MERGE", "operationMetrics": "{}"},
|
|
30
|
+
{"version": "1", "timestamp": "2026-11-10 09:00:00", "operation": "WRITE", "operationMetrics": "{}"},
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FakeDelta(DuckDBBackend):
|
|
35
|
+
def __init__(self):
|
|
36
|
+
super().__init__()
|
|
37
|
+
self.statements: list[str] = []
|
|
38
|
+
self.execute(
|
|
39
|
+
"""CREATE SCHEMA main_sales; CREATE SCHEMA main_scratch;
|
|
40
|
+
CREATE TABLE main_sales.v1 AS SELECT i AS order_id, i * 1.5 AS amount, 2000 + i % 20 AS order_year
|
|
41
|
+
FROM range(1, 5001) t(i);
|
|
42
|
+
CREATE TABLE main_sales.v2 AS SELECT * FROM main_sales.v1 WHERE order_id % 50 <> 0
|
|
43
|
+
UNION ALL SELECT * FROM main_sales.v1 WHERE order_id < 30;
|
|
44
|
+
CREATE TABLE main_sales.orders AS SELECT * FROM main_sales.v2;"""
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def qualified(self, table): # catalog.schema.table -> catalog_schema.table in DuckDB
|
|
48
|
+
p = table.split(".")
|
|
49
|
+
return table if len(p) < 3 else f"{p[0]}_{p[1]}.{p[2]}"
|
|
50
|
+
|
|
51
|
+
def ensure_schema(self, schema): # catalog.schema -> catalog_schema, created in __init__
|
|
52
|
+
assert schema == "main.scratch"
|
|
53
|
+
|
|
54
|
+
def query(self, sql):
|
|
55
|
+
if sql.startswith("DESCRIBE HISTORY"):
|
|
56
|
+
return HISTORY
|
|
57
|
+
if "information_schema.table_constraints" in sql:
|
|
58
|
+
return [{"column_name": "order_id"}]
|
|
59
|
+
return super().query(sql)
|
|
60
|
+
|
|
61
|
+
def execute(self, sql):
|
|
62
|
+
self.statements.append(sql)
|
|
63
|
+
m = re.match(r"CREATE OR REPLACE TABLE (\S+) SHALLOW CLONE (\S+) VERSION AS OF (\d+)", sql)
|
|
64
|
+
if m:
|
|
65
|
+
return super().execute(f"CREATE OR REPLACE TABLE {m.group(1)} AS SELECT * FROM main_sales.v{m.group(3)}")
|
|
66
|
+
return super().execute(sql)
|
|
67
|
+
|
|
68
|
+
def current_version(self, table):
|
|
69
|
+
return 3
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _code() -> str:
|
|
73
|
+
cells = build_notebook.build(NB)["cells"]
|
|
74
|
+
out = []
|
|
75
|
+
for c in cells:
|
|
76
|
+
src = "".join(c["source"])
|
|
77
|
+
if c["cell_type"] == "code" and not src.lstrip().startswith("%"):
|
|
78
|
+
out.append(src.replace("dbutils.library.restartPython()", ""))
|
|
79
|
+
return "\n\n".join(out)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.fixture
|
|
83
|
+
def run_notebook(monkeypatch, capsys):
|
|
84
|
+
def run(**widgets):
|
|
85
|
+
values = {"table": "main.sales.orders", "keys": "", "warehouse_id": "abc123",
|
|
86
|
+
"scratch_schema": "main.scratch", "version": "", "policy": "default", "sample_pct": ""}
|
|
87
|
+
values.update(widgets)
|
|
88
|
+
|
|
89
|
+
class Widgets:
|
|
90
|
+
def text(self, k, d):
|
|
91
|
+
values.setdefault(k, d)
|
|
92
|
+
|
|
93
|
+
def dropdown(self, k, d, opts):
|
|
94
|
+
assert values.get(k, d) in opts
|
|
95
|
+
values.setdefault(k, d)
|
|
96
|
+
|
|
97
|
+
def get(self, k):
|
|
98
|
+
return values[k]
|
|
99
|
+
|
|
100
|
+
fake = FakeDelta()
|
|
101
|
+
real_init = assess_mod.Sentry.__init__
|
|
102
|
+
monkeypatch.setattr(assess_mod.Sentry, "__init__",
|
|
103
|
+
lambda self, config=None, backend=None: real_init(self, config, backend=fake))
|
|
104
|
+
ns = {"dbutils": types.SimpleNamespace(widgets=Widgets()), "__name__": "__main__"}
|
|
105
|
+
exec(compile(_code(), str(NB), "exec"), ns)
|
|
106
|
+
return ns, fake, capsys.readouterr().out
|
|
107
|
+
return run
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_checks_the_latest_data_change_and_cleans_up(run_notebook):
|
|
111
|
+
ns, fake, out = run_notebook()
|
|
112
|
+
assert "Checking version 2 (MERGE) against version 1." in out # skips the OPTIMIZE
|
|
113
|
+
assert "Keys: order_id" in out # from the primary key
|
|
114
|
+
a = ns["assessment"]
|
|
115
|
+
assert a.verdict.value == "block"
|
|
116
|
+
rules = {h.rule for h in a.hits}
|
|
117
|
+
assert {"duplicate-keys", "row-loss"} <= rules
|
|
118
|
+
assert "diff-failed" not in rules # lineage failure is not a diff failure
|
|
119
|
+
assert "lineage-unavailable" in rules
|
|
120
|
+
assert "order_year" not in a.tables[0].summary # not a measure
|
|
121
|
+
assert "RESTORE TABLE main_sales.orders TO VERSION AS OF 1" in out
|
|
122
|
+
assert "VERSION AS OF 3" not in ns["report"] # the report undoes the change, not "now"
|
|
123
|
+
assert not fake.table_exists("main.scratch.bs_check_orders_v1") # clones dropped
|
|
124
|
+
assert not fake.table_exists("main.scratch.bs_check_orders_v2")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_share_link_prefills_the_form_without_names(run_notebook):
|
|
128
|
+
ns, _, out = run_notebook()
|
|
129
|
+
url = next(line for line in out.splitlines() if line.startswith("https://github.com/"))
|
|
130
|
+
q = parse_qs(urlparse(url).query)
|
|
131
|
+
assert q["template"] == ["it_caught_this.yml"]
|
|
132
|
+
assert q["verdict"] == ["block"]
|
|
133
|
+
form = (ROOT / ".github" / "ISSUE_TEMPLATE" / "it_caught_this.yml").read_text()
|
|
134
|
+
for field in ("verdict", "rules", "facts", "version"):
|
|
135
|
+
assert f"id: {field}" in form
|
|
136
|
+
assert "orders" not in url and "order_id" not in url and "amount" not in url
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_explicit_version_and_keys(run_notebook):
|
|
140
|
+
ns, _, out = run_notebook(version="2", keys="order_id")
|
|
141
|
+
assert "Checking version 2" in out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def test_bad_widget_values_fail_clearly(run_notebook):
|
|
145
|
+
with pytest.raises(ValueError, match="catalog.schema.table"):
|
|
146
|
+
run_notebook(table="orders")
|
|
147
|
+
with pytest.raises(ValueError, match="version"):
|
|
148
|
+
run_notebook(version="latest")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_ipynb_copy_is_up_to_date():
|
|
152
|
+
on_disk = json.loads(NB.with_suffix(".ipynb").read_text())
|
|
153
|
+
assert on_disk == json.loads(json.dumps(build_notebook.build(NB)))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{bricksentry-0.1.8 → bricksentry-0.1.9}/packages/bricksentry-mcp/src/bricksentry_mcp/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|