bricksentry 0.1.2__tar.gz → 0.1.3__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.
Files changed (44) hide show
  1. {bricksentry-0.1.2 → bricksentry-0.1.3}/CHANGELOG.md +5 -0
  2. {bricksentry-0.1.2 → bricksentry-0.1.3}/CONTRIBUTING.md +1 -1
  3. {bricksentry-0.1.2 → bricksentry-0.1.3}/PKG-INFO +16 -4
  4. {bricksentry-0.1.2 → bricksentry-0.1.3}/README.md +15 -3
  5. {bricksentry-0.1.2 → bricksentry-0.1.3}/examples/databricks/bricksentry.yml +2 -0
  6. bricksentry-0.1.3/examples/databricks/bricksentry_quickstart.ipynb +367 -0
  7. bricksentry-0.1.3/examples/databricks/bricksentry_quickstart.py +261 -0
  8. {bricksentry-0.1.2 → bricksentry-0.1.3}/pyproject.toml +2 -2
  9. bricksentry-0.1.3/scripts/build_notebook.py +61 -0
  10. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/__init__.py +1 -1
  11. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/lineage.py +28 -0
  12. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/test_databricks_and_uc.py +50 -1
  13. bricksentry-0.1.3/tests/test_notebook.py +45 -0
  14. {bricksentry-0.1.2 → bricksentry-0.1.3}/.gitignore +0 -0
  15. {bricksentry-0.1.2 → bricksentry-0.1.3}/LICENSE +0 -0
  16. {bricksentry-0.1.2 → bricksentry-0.1.3}/SECURITY.md +0 -0
  17. {bricksentry-0.1.2 → bricksentry-0.1.3}/action.yml +0 -0
  18. {bricksentry-0.1.2 → bricksentry-0.1.3}/examples/databricks/github-workflow.yml +0 -0
  19. {bricksentry-0.1.2 → bricksentry-0.1.3}/examples/databricks/policy.yml +0 -0
  20. {bricksentry-0.1.2 → bricksentry-0.1.3}/examples/demo/agent_loop_demo.py +0 -0
  21. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/agent_tools.py +0 -0
  22. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/assess.py +0 -0
  23. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/backends/__init__.py +0 -0
  24. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/backends/base.py +0 -0
  25. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/backends/databricks_backend.py +0 -0
  26. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/backends/duckdb_backend.py +0 -0
  27. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/changes.py +0 -0
  28. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/cli.py +0 -0
  29. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/config.py +0 -0
  30. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/demo.py +0 -0
  31. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/diff.py +0 -0
  32. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/explain.py +0 -0
  33. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/github.py +0 -0
  34. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/mcp_server.py +0 -0
  35. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/models.py +0 -0
  36. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/policy.py +0 -0
  37. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/preview.py +0 -0
  38. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/py.typed +0 -0
  39. {bricksentry-0.1.2 → bricksentry-0.1.3}/src/bricksentry/report.py +0 -0
  40. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/conftest.py +0 -0
  41. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/test_assess_policy.py +0 -0
  42. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/test_demo.py +0 -0
  43. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/test_diff.py +0 -0
  44. {bricksentry-0.1.2 → bricksentry-0.1.3}/tests/test_preview_agents.py +0 -0
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3 (2026-11-10)
4
+
5
+ - Blast radius no longer lists bricksentry's own `preview_write` clones, or tables that Unity Catalog lineage remembers but that no longer exist (when `information_schema` can confirm it). Before, every preview added a stale downstream entry. New lineage settings: `exclude` (name patterns, default `["*__preview_*"]`) and `exclude_dropped` (default true).
6
+ - Databricks quickstart notebook (`examples/databricks/bricksentry_quickstart.py`, plus an `.ipynb` copy) that runs the full loop on a demo table in your workspace.
7
+
3
8
  ## 0.1.2 (2026-11-10)
4
9
 
5
10
  - Fix: rows whose key is NULL are now matched null-safely. Before, each such row was counted as both added and removed (found on a real Databricks table with a NULL `state`).
@@ -19,7 +19,7 @@ pytest -q
19
19
  bricksentry demo
20
20
  ```
21
21
 
22
- The tests run against DuckDB, so you don't need a Databricks workspace. The Databricks backend is tested against a mocked SDK client; if your change touches it, please say in the pull request whether you also tried it on a real workspace.
22
+ The tests run against DuckDB, so you don't need a Databricks workspace. The automated tests use a mocked Databricks SDK client; if your change touches the Databricks backend, please say in the pull request whether you also tried it on a real workspace.
23
23
 
24
24
  ## Pull requests
25
25
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.2
3
+ Version: 0.1.3
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
@@ -62,6 +62,18 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
62
62
 
63
63
  ![bricksentry demo: an agent's change is previewed, blocked for duplicate keys, then routed to the table owners](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
64
64
 
65
+ ### Or run it in your Databricks workspace
66
+
67
+ The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
68
+
69
+ In Databricks: **Workspace → Import → URL**, and paste:
70
+
71
+ ```
72
+ https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py
73
+ ```
74
+
75
+ You need a SQL warehouse, `CREATE TABLE` on the schema you pick, and `SELECT` on `system.access.table_lineage` for the blast radius. A Jupyter copy is in [`bricksentry_quickstart.ipynb`](examples/databricks/bricksentry_quickstart.ipynb).
76
+
65
77
  ## What it does
66
78
 
67
79
  Before a change reaches production, bricksentry answers three questions, in a
@@ -179,7 +191,7 @@ backend: {type: databricks, warehouse_id: abc123} # auth: standard Databric
179
191
  sandbox_schema: main.bricksentry_sandbox
180
192
  candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
181
193
  sample_pct: 10
182
- lineage: {type: databricks, depth: 3, lookback_days: 90}
194
+ lineage: {type: databricks, depth: 3, lookback_days: 90} # also: exclude, exclude_dropped
183
195
  tables:
184
196
  main.sales.orders:
185
197
  keys: [order_id]
@@ -206,7 +218,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
206
218
  - **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping.
207
219
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
208
220
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
209
- - **The Databricks backend is tested against a mocked SDK.** Run it against a dev workspace before relying on it in CI.
221
+ - **Validated on one Databricks workspace so far** (serverless, November 2026): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. The automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
210
222
 
211
223
  ## Roadmap
212
224
 
@@ -218,4 +230,4 @@ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTIN
218
230
 
219
231
  ## License
220
232
 
221
- Apache-2.0. Created and maintained by Brahma.
233
+ Apache-2.0. Created and maintained by Brahma - Databricks Champion.
@@ -17,6 +17,18 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
17
17
 
18
18
  ![bricksentry demo: an agent's change is previewed, blocked for duplicate keys, then routed to the table owners](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
19
19
 
20
+ ### Or run it in your Databricks workspace
21
+
22
+ The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
23
+
24
+ In Databricks: **Workspace → Import → URL**, and paste:
25
+
26
+ ```
27
+ https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py
28
+ ```
29
+
30
+ You need a SQL warehouse, `CREATE TABLE` on the schema you pick, and `SELECT` on `system.access.table_lineage` for the blast radius. A Jupyter copy is in [`bricksentry_quickstart.ipynb`](examples/databricks/bricksentry_quickstart.ipynb).
31
+
20
32
  ## What it does
21
33
 
22
34
  Before a change reaches production, bricksentry answers three questions, in a
@@ -134,7 +146,7 @@ backend: {type: databricks, warehouse_id: abc123} # auth: standard Databric
134
146
  sandbox_schema: main.bricksentry_sandbox
135
147
  candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
136
148
  sample_pct: 10
137
- lineage: {type: databricks, depth: 3, lookback_days: 90}
149
+ lineage: {type: databricks, depth: 3, lookback_days: 90} # also: exclude, exclude_dropped
138
150
  tables:
139
151
  main.sales.orders:
140
152
  keys: [order_id]
@@ -161,7 +173,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
161
173
  - **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping.
162
174
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
163
175
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
164
- - **The Databricks backend is tested against a mocked SDK.** Run it against a dev workspace before relying on it in CI.
176
+ - **Validated on one Databricks workspace so far** (serverless, November 2026): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. The automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
165
177
 
166
178
  ## Roadmap
167
179
 
@@ -173,4 +185,4 @@ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTIN
173
185
 
174
186
  ## License
175
187
 
176
- Apache-2.0. Created and maintained by Brahma.
188
+ Apache-2.0. Created and maintained by Brahma - Databricks Champion.
@@ -18,6 +18,8 @@ lineage:
18
18
  type: databricks # reads system.access.table_lineage + information_schema
19
19
  depth: 3
20
20
  lookback_days: 90
21
+ # exclude: ["*__preview_*"] # name patterns left out of the blast radius (default: preview clones)
22
+ # exclude_dropped: true # hide tables lineage remembers but that no longer exist
21
23
 
22
24
  tables:
23
25
  main.sales.orders:
@@ -0,0 +1,367 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# bricksentry quickstart on Databricks\n",
8
+ "\n",
9
+ "**Know what a change does to your data before it ships.** This notebook walks through bricksentry's safety loop on a small demo table that it creates in a schema you choose:\n",
10
+ "\n",
11
+ "1. **Blast radius:** what depends on the table (from Unity Catalog lineage)\n",
12
+ "2. **Rollback plan:** the exact `RESTORE` command, from Delta history\n",
13
+ "3. **Safe preview:** run a DELETE on a disposable shallow clone, never on the real table\n",
14
+ "4. **Blocked change:** a candidate table with a join bug that duplicates rows\n",
15
+ "5. **Fixed change:** the corrected candidate, plus the pull-request comment a reviewer would see\n",
16
+ "6. **Your own table:** blast radius and rollback plan for a real table (read-only)\n",
17
+ "7. **Cleanup:** drops everything this notebook created\n",
18
+ "\n",
19
+ "**You need:** a Unity Catalog workspace, a SQL warehouse you can use, `CREATE TABLE` on the schema you pick, and (for the blast radius) `SELECT` on `system.access.table_lineage`.\n",
20
+ "Nothing here reads or changes your existing tables except the read-only checks in step 6.\n",
21
+ "\n",
22
+ "Docs: [bricksentry.org](https://bricksentry.org) · Source: [github.com/bricksentry/bricksentry](https://github.com/bricksentry/bricksentry)"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": [
31
+ "%pip install --quiet --upgrade \"bricksentry[databricks]\""
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": null,
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "dbutils.library.restartPython()"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "markdown",
45
+ "metadata": {},
46
+ "source": [
47
+ "## Settings\n",
48
+ "Fill in the widgets at the top of the notebook, then run the rest of the cells in order.\n",
49
+ "- **catalog / schema:** where the demo tables go. The schema is created if it doesn't exist.\n",
50
+ "- **warehouse_id:** the ID of a SQL warehouse (SQL Warehouses → your warehouse → Connection details). bricksentry runs all its checks as SQL on it."
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": null,
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "import re\n",
60
+ "\n",
61
+ "dbutils.widgets.text(\"catalog\", \"main\")\n",
62
+ "dbutils.widgets.text(\"schema\", \"bricksentry_demo\")\n",
63
+ "dbutils.widgets.text(\"warehouse_id\", \"\")\n",
64
+ "\n",
65
+ "CATALOG = dbutils.widgets.get(\"catalog\").strip()\n",
66
+ "SCHEMA = dbutils.widgets.get(\"schema\").strip()\n",
67
+ "WAREHOUSE_ID = dbutils.widgets.get(\"warehouse_id\").strip()\n",
68
+ "\n",
69
+ "for label, value in ((\"catalog\", CATALOG), (\"schema\", SCHEMA)):\n",
70
+ " if not re.fullmatch(r\"[A-Za-z0-9_]+\", value):\n",
71
+ " raise ValueError(f\"Set the '{label}' widget to a plain name (letters, digits, underscores); got {value!r}\")\n",
72
+ "if not re.fullmatch(r\"[A-Za-z0-9]+\", WAREHOUSE_ID):\n",
73
+ " raise ValueError(\"Set the 'warehouse_id' widget to your SQL warehouse ID (SQL Warehouses → Connection details).\")\n",
74
+ "\n",
75
+ "NS = f\"{CATALOG}.{SCHEMA}\"\n",
76
+ "ORDERS = f\"{NS}.bs_demo_orders\" # the \"production\" table\n",
77
+ "REVENUE = f\"{NS}.bs_demo_daily_revenue\" # a downstream table, tagged certified\n",
78
+ "CANDIDATE = f\"{NS}.bs_demo_orders_pr_42\" # what a pull request would build\n",
79
+ "\n",
80
+ "import bricksentry\n",
81
+ "from bricksentry import Config, Sentry, agent_tools\n",
82
+ "\n",
83
+ "sentry = Sentry(Config.from_dict({\n",
84
+ " \"backend\": {\"type\": \"databricks\", \"warehouse_id\": WAREHOUSE_ID},\n",
85
+ " \"sandbox_schema\": NS, # disposable preview clones go here\n",
86
+ " \"tables\": {ORDERS: {\"keys\": [\"order_id\"], \"segment_by\": [\"region\"]}},\n",
87
+ " \"lineage\": {\"type\": \"databricks\", \"depth\": 3, \"lookback_days\": 30},\n",
88
+ "}))\n",
89
+ "agent_tools.set_sentry(sentry) # the same tools an AI agent calls over MCP\n",
90
+ "run = sentry.backend.execute\n",
91
+ "print(f\"bricksentry {bricksentry.__version__} · demo tables in {NS} · warehouse {WAREHOUSE_ID}\")"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "metadata": {},
97
+ "source": [
98
+ "## Create the demo tables\n",
99
+ "A 20,000-row `bs_demo_orders` table, and a `bs_demo_daily_revenue` table built from it and tagged `certified`.\n",
100
+ "Building the second table from the first is what gives Unity Catalog a lineage edge to find in step 1."
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "run(f\"CREATE SCHEMA IF NOT EXISTS {NS}\")\n",
110
+ "run(f\"\"\"\n",
111
+ "CREATE OR REPLACE TABLE {ORDERS} AS\n",
112
+ "SELECT CAST(id AS BIGINT) AS order_id,\n",
113
+ " CASE id % 3 WHEN 0 THEN 'APAC' WHEN 1 THEN 'EMEA' ELSE 'AMER' END AS region,\n",
114
+ " CAST(round(20 + (id % 97) * 3.1, 2) AS DOUBLE) AS amount,\n",
115
+ " CASE WHEN id % 10 = 0 THEN 'refunded' ELSE 'paid' END AS status\n",
116
+ "FROM range(1, 20001)\n",
117
+ "\"\"\")\n",
118
+ "run(f\"\"\"\n",
119
+ "CREATE OR REPLACE TABLE {REVENUE} AS\n",
120
+ "SELECT region, CAST(sum(amount) AS DOUBLE) AS revenue\n",
121
+ "FROM {ORDERS}\n",
122
+ "GROUP BY region\n",
123
+ "\"\"\")\n",
124
+ "try:\n",
125
+ " run(f\"ALTER TABLE {REVENUE} SET TAGS ('certified' = 'true')\")\n",
126
+ " print(\"Tagged\", REVENUE, \"as certified.\")\n",
127
+ "except Exception as e:\n",
128
+ " print(\"Could not tag the downstream table (needs APPLY TAG); the certified rule won't fire.\", str(e)[:200])\n",
129
+ "\n",
130
+ "print(ORDERS, \"rows:\", sentry.backend.scalar(f\"SELECT COUNT(*) FROM {ORDERS}\"))"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "markdown",
135
+ "metadata": {},
136
+ "source": [
137
+ "## 1. Blast radius: what depends on `bs_demo_orders`?\n",
138
+ "`whats_downstream` walks `system.access.table_lineage` and attaches owners and tags from Unity Catalog.\n",
139
+ "Lineage is recorded when queries run and can take a few minutes to appear. If this comes back empty, carry on and re-run this cell later."
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": null,
145
+ "metadata": {},
146
+ "outputs": [],
147
+ "source": [
148
+ "ds = agent_tools.whats_downstream(ORDERS)\n",
149
+ "if \"error\" in ds:\n",
150
+ " print(\"Lineage lookup failed (do you have SELECT on system.access.table_lineage?):\", ds[\"error\"])\n",
151
+ "elif not ds[\"downstream\"]:\n",
152
+ " print(\"No downstream assets found yet. Lineage can take a few minutes to appear; re-run this cell later.\")\n",
153
+ "else:\n",
154
+ " for n in ds[\"downstream\"]:\n",
155
+ " tags = \", \".join(n[\"tags\"]) or \"-\"\n",
156
+ " print(f\"depth {n['depth']} {n['kind']:<10} {n['name']:<55} owner: {n['owner'] or '-'} tags: {tags}\")"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "## 2. Rollback plan\n",
164
+ "Captured *before* anything changes. This is the command that would undo a bad change to the table."
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "execution_count": null,
170
+ "metadata": {},
171
+ "outputs": [],
172
+ "source": [
173
+ "plan = agent_tools.rollback_plan(ORDERS)\n",
174
+ "print(plan[\"rollback_sql\"])"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "markdown",
179
+ "metadata": {},
180
+ "source": [
181
+ "## 3. Safe preview: what would this DELETE do?\n",
182
+ "`preview_write` runs the statement on a disposable **shallow clone** in your schema, diffs it against the real table, applies the policy, and drops the clone.\n",
183
+ "It accepts one INSERT, MERGE, UPDATE or DELETE and refuses DROP, TRUNCATE, ALTER and GRANT."
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "execution_count": null,
189
+ "metadata": {},
190
+ "outputs": [],
191
+ "source": [
192
+ "def show(result):\n",
193
+ " \"\"\"Print a verdict, its summary and the rules that fired.\"\"\"\n",
194
+ " if \"error\" in result:\n",
195
+ " print(\"ERROR:\", result[\"error\"])\n",
196
+ " return\n",
197
+ " print(f\"VERDICT: {result['verdict'].upper()} (risk {result['risk_tier']})\")\n",
198
+ " for t in result[\"tables\"]:\n",
199
+ " print(\" \", t[\"summary\"])\n",
200
+ " for h in result[\"rule_hits\"]:\n",
201
+ " print(f\" [{h['verdict']}] {h['rule']}: {h['reason']}\")\n",
202
+ "\n",
203
+ "\n",
204
+ "before = sentry.backend.scalar(f\"SELECT COUNT(*) FROM {ORDERS}\")\n",
205
+ "preview = agent_tools.preview_write(f\"DELETE FROM {ORDERS} WHERE status <> 'paid'\", ORDERS)\n",
206
+ "show(preview)\n",
207
+ "after = sentry.backend.scalar(f\"SELECT COUNT(*) FROM {ORDERS}\")\n",
208
+ "print(f\"\\nReal table rows before: {before:,} · after: {after:,} (the DELETE only ran on the clone)\")"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "markdown",
213
+ "metadata": {},
214
+ "source": [
215
+ "## 4. A pull request with a bug\n",
216
+ "Suppose a pull request applies an 8% APAC discount, but its join duplicates 40 orders.\n",
217
+ "In CI you'd build this into a per-PR schema; here we build it as `bs_demo_orders_pr_42` and assess it against the real table."
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "run(f\"\"\"\n",
227
+ "CREATE OR REPLACE TABLE {CANDIDATE} AS\n",
228
+ "SELECT o.order_id, o.region,\n",
229
+ " CASE WHEN o.region = 'APAC' THEN round(o.amount * 0.92, 2) ELSE o.amount END AS amount,\n",
230
+ " o.status\n",
231
+ "FROM {ORDERS} o\n",
232
+ "LEFT JOIN (SELECT * FROM VALUES (1), (1) AS dup(k)) dup ON o.order_id % 500 = 0\n",
233
+ "\"\"\")\n",
234
+ "buggy = agent_tools.assess_change([ORDERS], candidates={ORDERS: CANDIDATE})\n",
235
+ "show(buggy)\n",
236
+ "print(\"\\nnext_step:\", agent_tools.safe_to_ship(buggy[\"id\"])[\"next_step\"])"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "markdown",
241
+ "metadata": {},
242
+ "source": [
243
+ "## 5. The fixed pull request\n",
244
+ "Same discount, no duplicated rows. The verdict now depends only on how much changed and who depends on it.\n",
245
+ "If lineage from step 1 is visible, the certified downstream table makes it `needs_human`; otherwise the large change is a `warn`."
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": null,
251
+ "metadata": {},
252
+ "outputs": [],
253
+ "source": [
254
+ "run(f\"\"\"\n",
255
+ "CREATE OR REPLACE TABLE {CANDIDATE} AS\n",
256
+ "SELECT order_id, region,\n",
257
+ " CASE WHEN region = 'APAC' THEN round(amount * 0.92, 2) ELSE amount END AS amount,\n",
258
+ " status\n",
259
+ "FROM {ORDERS}\n",
260
+ "\"\"\")\n",
261
+ "fixed = agent_tools.assess_change([ORDERS], candidates={ORDERS: CANDIDATE})\n",
262
+ "show(fixed)\n",
263
+ "gate = agent_tools.safe_to_ship(fixed[\"id\"])\n",
264
+ "print(\"\\nsafe_to_ship:\", gate[\"safe_to_ship\"], \"\\nnext_step:\", gate[\"next_step\"])"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "markdown",
269
+ "metadata": {},
270
+ "source": [
271
+ "### The pull-request comment a reviewer would see"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "execution_count": null,
277
+ "metadata": {},
278
+ "outputs": [],
279
+ "source": [
280
+ "from bricksentry.report import to_markdown\n",
281
+ "\n",
282
+ "report = to_markdown(sentry.get_assessment(fixed[\"id\"]))\n",
283
+ "try:\n",
284
+ " from IPython.display import Markdown, display\n",
285
+ " display(Markdown(report))\n",
286
+ "except Exception:\n",
287
+ " print(report)"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "markdown",
292
+ "metadata": {},
293
+ "source": [
294
+ "## 6. Try it on one of your own tables (read-only)\n",
295
+ "Enter a full table name in the `my_table` widget and run the cell. It only reads lineage, Unity Catalog metadata and Delta history."
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "execution_count": null,
301
+ "metadata": {},
302
+ "outputs": [],
303
+ "source": [
304
+ "dbutils.widgets.text(\"my_table\", \"\")\n",
305
+ "MY_TABLE = dbutils.widgets.get(\"my_table\").strip()\n",
306
+ "\n",
307
+ "if not MY_TABLE:\n",
308
+ " print(\"Set the 'my_table' widget to catalog.schema.table, then re-run this cell.\")\n",
309
+ "else:\n",
310
+ " ds = agent_tools.whats_downstream(MY_TABLE)\n",
311
+ " if \"error\" in ds:\n",
312
+ " print(\"ERROR:\", ds[\"error\"])\n",
313
+ " else:\n",
314
+ " print(f\"{MY_TABLE}: owner {ds['owner'] or '-'}, tags {ds['tags'] or '-'}, {ds['count']} downstream asset(s)\")\n",
315
+ " for n in ds[\"downstream\"]:\n",
316
+ " print(f\" depth {n['depth']} {n['kind']:<10} {n['name']} owner: {n['owner'] or '-'}\")\n",
317
+ " print(\"\\nRollback plan:\", agent_tools.rollback_plan(MY_TABLE).get(\"rollback_sql\"))"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "markdown",
322
+ "metadata": {},
323
+ "source": [
324
+ "## 7. Cleanup\n",
325
+ "Drops the three demo tables. The schema is left in place in case it holds anything else."
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": null,
331
+ "metadata": {},
332
+ "outputs": [],
333
+ "source": [
334
+ "for t in (CANDIDATE, REVENUE, ORDERS):\n",
335
+ " run(f\"DROP TABLE IF EXISTS {t}\")\n",
336
+ " print(\"dropped\", t)\n",
337
+ "agent_tools.set_sentry(None)"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "metadata": {},
343
+ "source": [
344
+ "## Next steps\n",
345
+ "- **In CI:** `bricksentry init` writes `bricksentry.yml` and `policy.yml`; add `bricksentry assess --from-git origin/main --comment` to your pull-request workflow. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).\n",
346
+ "- **For AI agents:** `bricksentry mcp` exposes these same tools over MCP. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).\n",
347
+ "- **Feedback and bugs:** [github.com/bricksentry/bricksentry/issues](https://github.com/bricksentry/bricksentry/issues)"
348
+ ]
349
+ }
350
+ ],
351
+ "metadata": {
352
+ "kernelspec": {
353
+ "display_name": "Python 3",
354
+ "language": "python",
355
+ "name": "python3"
356
+ },
357
+ "language_info": {
358
+ "name": "python"
359
+ },
360
+ "application/vnd.databricks.v1+notebook": {
361
+ "notebookName": "bricksentry_quickstart",
362
+ "language": "python"
363
+ }
364
+ },
365
+ "nbformat": 4,
366
+ "nbformat_minor": 5
367
+ }
@@ -0,0 +1,261 @@
1
+ # Databricks notebook source
2
+ # MAGIC %md
3
+ # MAGIC # bricksentry quickstart on Databricks
4
+ # MAGIC
5
+ # MAGIC **Know what a change does to your data before it ships.** This notebook walks through bricksentry's safety loop on a small demo table that it creates in a schema you choose:
6
+ # MAGIC
7
+ # MAGIC 1. **Blast radius:** what depends on the table (from Unity Catalog lineage)
8
+ # MAGIC 2. **Rollback plan:** the exact `RESTORE` command, from Delta history
9
+ # MAGIC 3. **Safe preview:** run a DELETE on a disposable shallow clone, never on the real table
10
+ # MAGIC 4. **Blocked change:** a candidate table with a join bug that duplicates rows
11
+ # MAGIC 5. **Fixed change:** the corrected candidate, plus the pull-request comment a reviewer would see
12
+ # MAGIC 6. **Your own table:** blast radius and rollback plan for a real table (read-only)
13
+ # MAGIC 7. **Cleanup:** drops everything this notebook created
14
+ # MAGIC
15
+ # MAGIC **You need:** a Unity Catalog workspace, a SQL warehouse you can use, `CREATE TABLE` on the schema you pick, and (for the blast radius) `SELECT` on `system.access.table_lineage`.
16
+ # MAGIC Nothing here reads or changes your existing tables except the read-only checks in step 6.
17
+ # MAGIC
18
+ # MAGIC Docs: [bricksentry.org](https://bricksentry.org) · Source: [github.com/bricksentry/bricksentry](https://github.com/bricksentry/bricksentry)
19
+
20
+ # COMMAND ----------
21
+
22
+ # MAGIC %pip install --quiet --upgrade "bricksentry[databricks]"
23
+
24
+ # COMMAND ----------
25
+
26
+ dbutils.library.restartPython()
27
+
28
+ # COMMAND ----------
29
+
30
+ # MAGIC %md
31
+ # MAGIC ## Settings
32
+ # MAGIC Fill in the widgets at the top of the notebook, then run the rest of the cells in order.
33
+ # MAGIC - **catalog / schema:** where the demo tables go. The schema is created if it doesn't exist.
34
+ # MAGIC - **warehouse_id:** the ID of a SQL warehouse (SQL Warehouses → your warehouse → Connection details). bricksentry runs all its checks as SQL on it.
35
+
36
+ # COMMAND ----------
37
+
38
+ import re
39
+
40
+ dbutils.widgets.text("catalog", "main")
41
+ dbutils.widgets.text("schema", "bricksentry_demo")
42
+ dbutils.widgets.text("warehouse_id", "")
43
+
44
+ CATALOG = dbutils.widgets.get("catalog").strip()
45
+ SCHEMA = dbutils.widgets.get("schema").strip()
46
+ WAREHOUSE_ID = dbutils.widgets.get("warehouse_id").strip()
47
+
48
+ for label, value in (("catalog", CATALOG), ("schema", SCHEMA)):
49
+ if not re.fullmatch(r"[A-Za-z0-9_]+", value):
50
+ raise ValueError(f"Set the '{label}' widget to a plain name (letters, digits, underscores); got {value!r}")
51
+ if not re.fullmatch(r"[A-Za-z0-9]+", WAREHOUSE_ID):
52
+ raise ValueError("Set the 'warehouse_id' widget to your SQL warehouse ID (SQL Warehouses → Connection details).")
53
+
54
+ NS = f"{CATALOG}.{SCHEMA}"
55
+ ORDERS = f"{NS}.bs_demo_orders" # the "production" table
56
+ REVENUE = f"{NS}.bs_demo_daily_revenue" # a downstream table, tagged certified
57
+ CANDIDATE = f"{NS}.bs_demo_orders_pr_42" # what a pull request would build
58
+
59
+ import bricksentry
60
+ from bricksentry import Config, Sentry, agent_tools
61
+
62
+ sentry = Sentry(Config.from_dict({
63
+ "backend": {"type": "databricks", "warehouse_id": WAREHOUSE_ID},
64
+ "sandbox_schema": NS, # disposable preview clones go here
65
+ "tables": {ORDERS: {"keys": ["order_id"], "segment_by": ["region"]}},
66
+ "lineage": {"type": "databricks", "depth": 3, "lookback_days": 30},
67
+ }))
68
+ agent_tools.set_sentry(sentry) # the same tools an AI agent calls over MCP
69
+ run = sentry.backend.execute
70
+ print(f"bricksentry {bricksentry.__version__} · demo tables in {NS} · warehouse {WAREHOUSE_ID}")
71
+
72
+ # COMMAND ----------
73
+
74
+ # MAGIC %md
75
+ # MAGIC ## Create the demo tables
76
+ # MAGIC A 20,000-row `bs_demo_orders` table, and a `bs_demo_daily_revenue` table built from it and tagged `certified`.
77
+ # MAGIC Building the second table from the first is what gives Unity Catalog a lineage edge to find in step 1.
78
+
79
+ # COMMAND ----------
80
+
81
+ run(f"CREATE SCHEMA IF NOT EXISTS {NS}")
82
+ run(f"""
83
+ CREATE OR REPLACE TABLE {ORDERS} AS
84
+ SELECT CAST(id AS BIGINT) AS order_id,
85
+ CASE id % 3 WHEN 0 THEN 'APAC' WHEN 1 THEN 'EMEA' ELSE 'AMER' END AS region,
86
+ CAST(round(20 + (id % 97) * 3.1, 2) AS DOUBLE) AS amount,
87
+ CASE WHEN id % 10 = 0 THEN 'refunded' ELSE 'paid' END AS status
88
+ FROM range(1, 20001)
89
+ """)
90
+ run(f"""
91
+ CREATE OR REPLACE TABLE {REVENUE} AS
92
+ SELECT region, CAST(sum(amount) AS DOUBLE) AS revenue
93
+ FROM {ORDERS}
94
+ GROUP BY region
95
+ """)
96
+ try:
97
+ run(f"ALTER TABLE {REVENUE} SET TAGS ('certified' = 'true')")
98
+ print("Tagged", REVENUE, "as certified.")
99
+ except Exception as e:
100
+ print("Could not tag the downstream table (needs APPLY TAG); the certified rule won't fire.", str(e)[:200])
101
+
102
+ print(ORDERS, "rows:", sentry.backend.scalar(f"SELECT COUNT(*) FROM {ORDERS}"))
103
+
104
+ # COMMAND ----------
105
+
106
+ # MAGIC %md
107
+ # MAGIC ## 1. Blast radius: what depends on `bs_demo_orders`?
108
+ # MAGIC `whats_downstream` walks `system.access.table_lineage` and attaches owners and tags from Unity Catalog.
109
+ # MAGIC Lineage is recorded when queries run and can take a few minutes to appear. If this comes back empty, carry on and re-run this cell later.
110
+
111
+ # COMMAND ----------
112
+
113
+ ds = agent_tools.whats_downstream(ORDERS)
114
+ if "error" in ds:
115
+ print("Lineage lookup failed (do you have SELECT on system.access.table_lineage?):", ds["error"])
116
+ elif not ds["downstream"]:
117
+ print("No downstream assets found yet. Lineage can take a few minutes to appear; re-run this cell later.")
118
+ else:
119
+ for n in ds["downstream"]:
120
+ tags = ", ".join(n["tags"]) or "-"
121
+ print(f"depth {n['depth']} {n['kind']:<10} {n['name']:<55} owner: {n['owner'] or '-'} tags: {tags}")
122
+
123
+ # COMMAND ----------
124
+
125
+ # MAGIC %md
126
+ # MAGIC ## 2. Rollback plan
127
+ # MAGIC Captured *before* anything changes. This is the command that would undo a bad change to the table.
128
+
129
+ # COMMAND ----------
130
+
131
+ plan = agent_tools.rollback_plan(ORDERS)
132
+ print(plan["rollback_sql"])
133
+
134
+ # COMMAND ----------
135
+
136
+ # MAGIC %md
137
+ # MAGIC ## 3. Safe preview: what would this DELETE do?
138
+ # MAGIC `preview_write` runs the statement on a disposable **shallow clone** in your schema, diffs it against the real table, applies the policy, and drops the clone.
139
+ # MAGIC It accepts one INSERT, MERGE, UPDATE or DELETE and refuses DROP, TRUNCATE, ALTER and GRANT.
140
+
141
+ # COMMAND ----------
142
+
143
+ def show(result):
144
+ """Print a verdict, its summary and the rules that fired."""
145
+ if "error" in result:
146
+ print("ERROR:", result["error"])
147
+ return
148
+ print(f"VERDICT: {result['verdict'].upper()} (risk {result['risk_tier']})")
149
+ for t in result["tables"]:
150
+ print(" ", t["summary"])
151
+ for h in result["rule_hits"]:
152
+ print(f" [{h['verdict']}] {h['rule']}: {h['reason']}")
153
+
154
+
155
+ before = sentry.backend.scalar(f"SELECT COUNT(*) FROM {ORDERS}")
156
+ preview = agent_tools.preview_write(f"DELETE FROM {ORDERS} WHERE status <> 'paid'", ORDERS)
157
+ show(preview)
158
+ after = sentry.backend.scalar(f"SELECT COUNT(*) FROM {ORDERS}")
159
+ print(f"\nReal table rows before: {before:,} · after: {after:,} (the DELETE only ran on the clone)")
160
+
161
+ # COMMAND ----------
162
+
163
+ # MAGIC %md
164
+ # MAGIC ## 4. A pull request with a bug
165
+ # MAGIC Suppose a pull request applies an 8% APAC discount, but its join duplicates 40 orders.
166
+ # MAGIC In CI you'd build this into a per-PR schema; here we build it as `bs_demo_orders_pr_42` and assess it against the real table.
167
+
168
+ # COMMAND ----------
169
+
170
+ run(f"""
171
+ CREATE OR REPLACE TABLE {CANDIDATE} AS
172
+ SELECT o.order_id, o.region,
173
+ CASE WHEN o.region = 'APAC' THEN round(o.amount * 0.92, 2) ELSE o.amount END AS amount,
174
+ o.status
175
+ FROM {ORDERS} o
176
+ LEFT JOIN (SELECT * FROM VALUES (1), (1) AS dup(k)) dup ON o.order_id % 500 = 0
177
+ """)
178
+ buggy = agent_tools.assess_change([ORDERS], candidates={ORDERS: CANDIDATE})
179
+ show(buggy)
180
+ print("\nnext_step:", agent_tools.safe_to_ship(buggy["id"])["next_step"])
181
+
182
+ # COMMAND ----------
183
+
184
+ # MAGIC %md
185
+ # MAGIC ## 5. The fixed pull request
186
+ # MAGIC Same discount, no duplicated rows. The verdict now depends only on how much changed and who depends on it.
187
+ # MAGIC If lineage from step 1 is visible, the certified downstream table makes it `needs_human`; otherwise the large change is a `warn`.
188
+
189
+ # COMMAND ----------
190
+
191
+ run(f"""
192
+ CREATE OR REPLACE TABLE {CANDIDATE} AS
193
+ SELECT order_id, region,
194
+ CASE WHEN region = 'APAC' THEN round(amount * 0.92, 2) ELSE amount END AS amount,
195
+ status
196
+ FROM {ORDERS}
197
+ """)
198
+ fixed = agent_tools.assess_change([ORDERS], candidates={ORDERS: CANDIDATE})
199
+ show(fixed)
200
+ gate = agent_tools.safe_to_ship(fixed["id"])
201
+ print("\nsafe_to_ship:", gate["safe_to_ship"], "\nnext_step:", gate["next_step"])
202
+
203
+ # COMMAND ----------
204
+
205
+ # MAGIC %md
206
+ # MAGIC ### The pull-request comment a reviewer would see
207
+
208
+ # COMMAND ----------
209
+
210
+ from bricksentry.report import to_markdown
211
+
212
+ report = to_markdown(sentry.get_assessment(fixed["id"]))
213
+ try:
214
+ from IPython.display import Markdown, display
215
+ display(Markdown(report))
216
+ except Exception:
217
+ print(report)
218
+
219
+ # COMMAND ----------
220
+
221
+ # MAGIC %md
222
+ # MAGIC ## 6. Try it on one of your own tables (read-only)
223
+ # MAGIC Enter a full table name in the `my_table` widget and run the cell. It only reads lineage, Unity Catalog metadata and Delta history.
224
+
225
+ # COMMAND ----------
226
+
227
+ dbutils.widgets.text("my_table", "")
228
+ MY_TABLE = dbutils.widgets.get("my_table").strip()
229
+
230
+ if not MY_TABLE:
231
+ print("Set the 'my_table' widget to catalog.schema.table, then re-run this cell.")
232
+ else:
233
+ ds = agent_tools.whats_downstream(MY_TABLE)
234
+ if "error" in ds:
235
+ print("ERROR:", ds["error"])
236
+ else:
237
+ print(f"{MY_TABLE}: owner {ds['owner'] or '-'}, tags {ds['tags'] or '-'}, {ds['count']} downstream asset(s)")
238
+ for n in ds["downstream"]:
239
+ print(f" depth {n['depth']} {n['kind']:<10} {n['name']} owner: {n['owner'] or '-'}")
240
+ print("\nRollback plan:", agent_tools.rollback_plan(MY_TABLE).get("rollback_sql"))
241
+
242
+ # COMMAND ----------
243
+
244
+ # MAGIC %md
245
+ # MAGIC ## 7. Cleanup
246
+ # MAGIC Drops the three demo tables. The schema is left in place in case it holds anything else.
247
+
248
+ # COMMAND ----------
249
+
250
+ for t in (CANDIDATE, REVENUE, ORDERS):
251
+ run(f"DROP TABLE IF EXISTS {t}")
252
+ print("dropped", t)
253
+ agent_tools.set_sentry(None)
254
+
255
+ # COMMAND ----------
256
+
257
+ # MAGIC %md
258
+ # MAGIC ## Next steps
259
+ # MAGIC - **In CI:** `bricksentry init` writes `bricksentry.yml` and `policy.yml`; add `bricksentry assess --from-git origin/main --comment` to your pull-request workflow. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).
260
+ # MAGIC - **For AI agents:** `bricksentry mcp` exposes these same tools over MCP. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).
261
+ # MAGIC - **Feedback and bugs:** [github.com/bricksentry/bricksentry/issues](https://github.com/bricksentry/bricksentry/issues)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.2"
7
+ version = "0.1.3"
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"
@@ -51,7 +51,7 @@ Issues = "https://github.com/bricksentry/bricksentry/issues"
51
51
  Changelog = "https://github.com/bricksentry/bricksentry/blob/main/CHANGELOG.md"
52
52
 
53
53
  [tool.hatch.build.targets.sdist]
54
- include = ["src", "tests", "examples", "README.md", "LICENSE", "CHANGELOG.md", "CONTRIBUTING.md", "SECURITY.md", "action.yml"]
54
+ include = ["src", "tests", "examples", "scripts", "README.md", "LICENSE", "CHANGELOG.md", "CONTRIBUTING.md", "SECURITY.md", "action.yml"]
55
55
 
56
56
  [tool.hatch.build.targets.wheel]
57
57
  packages = ["src/bricksentry"]
@@ -0,0 +1,61 @@
1
+ """Build examples/databricks/bricksentry_quickstart.ipynb from the Databricks source notebook.
2
+
3
+ python scripts/build_notebook.py
4
+
5
+ The .py file is the source of truth; edit it, then rerun this script.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ SRC = ROOT / "examples" / "databricks" / "bricksentry_quickstart.py"
15
+ OUT = SRC.with_suffix(".ipynb")
16
+
17
+
18
+ def cells_from_source(text: str) -> list[dict]:
19
+ assert text.startswith("# Databricks notebook source"), "not a Databricks source notebook"
20
+ body = text.split("\n", 1)[1]
21
+ cells = []
22
+ for raw in body.split("# COMMAND ----------"):
23
+ lines = raw.strip("\n").splitlines()
24
+ if not lines:
25
+ continue
26
+ if all(l.startswith("# MAGIC") for l in lines):
27
+ stripped = [l[len("# MAGIC"):].removeprefix(" ") for l in lines]
28
+ if stripped[0].startswith("%md"):
29
+ md = stripped[1:]
30
+ cells.append({"cell_type": "markdown", "metadata": {}, "source": _src(md)})
31
+ else:
32
+ cells.append(_code(stripped))
33
+ else:
34
+ cells.append(_code(lines))
35
+ return cells
36
+
37
+
38
+ def _src(lines: list[str]) -> list[str]:
39
+ return [l + "\n" for l in lines[:-1]] + ([lines[-1]] if lines else [])
40
+
41
+
42
+ def _code(lines: list[str]) -> dict:
43
+ return {"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": _src(lines)}
44
+
45
+
46
+ def build() -> dict:
47
+ return {
48
+ "cells": cells_from_source(SRC.read_text()),
49
+ "metadata": {
50
+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
51
+ "language_info": {"name": "python"},
52
+ "application/vnd.databricks.v1+notebook": {"notebookName": "bricksentry_quickstart", "language": "python"},
53
+ },
54
+ "nbformat": 4,
55
+ "nbformat_minor": 5,
56
+ }
57
+
58
+
59
+ if __name__ == "__main__":
60
+ OUT.write_text(json.dumps(build(), indent=1, ensure_ascii=False) + "\n")
61
+ print("wrote", OUT.relative_to(ROOT))
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.2"
26
+ __version__ = "0.1.3"
@@ -9,6 +9,7 @@ Lakeflow pipelines, dashboards and SQL queries, not just SQL you can parse.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
+ import fnmatch
12
13
  from abc import ABC, abstractmethod
13
14
  from typing import Any
14
15
 
@@ -102,6 +103,11 @@ class UnityCatalogLineage(LineageProvider):
102
103
  Table owners come from ``information_schema.tables`` and tags from
103
104
  ``information_schema.table_tags``. All table names are configurable so the
104
105
  same code runs against copies of the system tables in tests.
106
+
107
+ Lineage history keeps tables that no longer exist, including bricksentry's own
108
+ ``preview_write`` clones. Those are left out of the blast radius: names matching
109
+ ``exclude_patterns`` always, and tables that ``information_schema`` reports as
110
+ gone (only when that lookup succeeds, so missing privileges never hide anything).
105
111
  """
106
112
 
107
113
  def __init__(
@@ -112,6 +118,8 @@ class UnityCatalogLineage(LineageProvider):
112
118
  tables_table: str = "system.information_schema.tables",
113
119
  tags_table: str = "system.information_schema.table_tags",
114
120
  max_nodes: int = 500,
121
+ exclude_patterns: list[str] | None = None,
122
+ exclude_dropped: bool = True,
115
123
  ):
116
124
  self.backend = backend
117
125
  self.lookback_days = lookback_days
@@ -119,7 +127,14 @@ class UnityCatalogLineage(LineageProvider):
119
127
  self.tables_table = tables_table
120
128
  self.tags_table = tags_table
121
129
  self.max_nodes = max_nodes
130
+ self.exclude_patterns = [p.lower() for p in (exclude_patterns if exclude_patterns is not None else DEFAULT_EXCLUDE)]
131
+ self.exclude_dropped = exclude_dropped
122
132
  self._meta_cache: dict[str, tuple[str | None, dict[str, str]]] = {}
133
+ self._exists: dict[str, bool] = {} # True / False when information_schema answered; absent if unknown
134
+
135
+ def _excluded(self, name: str) -> bool:
136
+ n = name.lower()
137
+ return any(fnmatch.fnmatch(n, p) for p in self.exclude_patterns)
123
138
 
124
139
  def downstream(self, table: str, depth: int = 3) -> list[ImpactNode]:
125
140
  out: list[ImpactNode] = []
@@ -142,6 +157,8 @@ class UnityCatalogLineage(LineageProvider):
142
157
  for r in rows:
143
158
  src = r.get("src")
144
159
  tgt = r.get("tgt")
160
+ if tgt and self._excluded(tgt):
161
+ continue # e.g. a preview_write clone: neither it nor the statement that made it is a dependent
145
162
  if tgt and tgt.lower() not in seen_tables:
146
163
  seen_tables.add(tgt.lower())
147
164
  nxt.append(tgt)
@@ -156,6 +173,8 @@ class UnityCatalogLineage(LineageProvider):
156
173
  frontier = nxt
157
174
  out = out[: self.max_nodes]
158
175
  self._attach_meta([n for n in out if n.kind == "table"])
176
+ if self.exclude_dropped:
177
+ out = [n for n in out if not (n.kind == "table" and self._exists.get(n.name.lower()) is False)]
159
178
  return out
160
179
 
161
180
  def owner_and_tags(self, table: str) -> tuple[str | None, dict[str, str]]:
@@ -179,11 +198,15 @@ class UnityCatalogLineage(LineageProvider):
179
198
  batch = names[i : i + 200]
180
199
  in_list = ", ".join(_lit(n.lower()) for n in batch)
181
200
  try:
201
+ found = set()
182
202
  for r in self.backend.query(
183
203
  f"SELECT {full} AS fqn, table_owner FROM {self.tables_table} WHERE {full} IN ({in_list})"
184
204
  ):
205
+ found.add(r["fqn"])
185
206
  _, tags = self._meta_cache[r["fqn"]]
186
207
  self._meta_cache[r["fqn"]] = (r.get("table_owner"), tags)
208
+ for n in batch:
209
+ self._exists[n.lower()] = n.lower() in found
187
210
  except Exception:
188
211
  pass # missing privileges on information_schema should not break the check
189
212
  try:
@@ -199,6 +222,9 @@ class UnityCatalogLineage(LineageProvider):
199
222
  pass
200
223
 
201
224
 
225
+ DEFAULT_EXCLUDE = ["*__preview_*"] # bricksentry's own preview_write clones
226
+
227
+
202
228
  def _lit(s: str) -> str:
203
229
  s = str(s)
204
230
  if any(ch in s for ch in "'\\\n\r;"):
@@ -220,5 +246,7 @@ def make_lineage(cfg: dict[str, Any] | None, backend: Backend) -> LineageProvide
220
246
  tables_table=cfg.get("tables_table", "system.information_schema.tables"),
221
247
  tags_table=cfg.get("tags_table", "system.information_schema.table_tags"),
222
248
  max_nodes=int(cfg.get("max_nodes", 500)),
249
+ exclude_patterns=cfg.get("exclude"),
250
+ exclude_dropped=bool(cfg.get("exclude_dropped", True)),
223
251
  )
224
252
  raise ValueError(f"Unknown lineage type {kind!r}")
@@ -57,7 +57,8 @@ def test_uc_lineage_walk(backend):
57
57
  )
58
58
  backend.execute(
59
59
  """CREATE TABLE sys.tables AS SELECT * FROM (VALUES
60
- ('main','sales','daily_revenue','finance-team')) t(table_catalog, table_schema, table_name, table_owner)"""
60
+ ('main','sales','daily_revenue','finance-team'),
61
+ ('main','finance','close','finance-team')) t(table_catalog, table_schema, table_name, table_owner)"""
61
62
  )
62
63
  backend.execute(
63
64
  """CREATE TABLE sys.table_tags AS SELECT * FROM (VALUES
@@ -75,3 +76,51 @@ def test_uc_lineage_walk(backend):
75
76
  assert not any("stale" in n.name for n in nodes) # outside lookback window
76
77
  rev = next(n for n in nodes if n.name == "main.sales.daily_revenue")
77
78
  assert rev.owner == "finance-team" and "certified" in rev.tags
79
+
80
+
81
+ def _lineage_fixture(backend, with_tables_table=True):
82
+ backend.execute("CREATE SCHEMA IF NOT EXISTS sys2")
83
+ backend.execute(
84
+ """
85
+ CREATE OR REPLACE TABLE sys2.table_lineage AS SELECT * FROM (VALUES
86
+ ('main.sales.orders', 'main.sales.daily_revenue', 'JOB', '111', current_date),
87
+ ('main.sales.orders', 'main.sales.orders__preview_ab12cd34', 'DBSQL_QUERY', 'q-clone', current_date),
88
+ ('main.sales.orders', 'main.tmp.bs_test_candidate', 'NOTEBOOK', '222', current_date),
89
+ ('main.tmp.bs_test_candidate', 'main.tmp.child_of_dropped', 'NOTEBOOK', '222', current_date)
90
+ ) t(source_table_full_name, target_table_full_name, entity_type, entity_id, event_date)
91
+ """
92
+ )
93
+ backend.execute(
94
+ """CREATE OR REPLACE TABLE sys2.tables AS SELECT * FROM (VALUES
95
+ ('main','sales','daily_revenue','finance-team'),
96
+ ('main','tmp','child_of_dropped','someone')) t(table_catalog, table_schema, table_name, table_owner)"""
97
+ )
98
+ backend.execute(
99
+ "CREATE OR REPLACE TABLE sys2.table_tags AS SELECT * FROM (VALUES ('x','x','x','x', NULL)) "
100
+ "t(catalog_name, schema_name, table_name, tag_name, tag_value)"
101
+ )
102
+ return UnityCatalogLineage(
103
+ backend,
104
+ lineage_table="sys2.table_lineage",
105
+ tables_table="sys2.tables" if with_tables_table else "sys2.no_such_table",
106
+ tags_table="sys2.table_tags",
107
+ )
108
+
109
+
110
+ def test_uc_lineage_skips_preview_clones_and_dropped_tables(backend):
111
+ nodes = _lineage_fixture(backend).downstream("main.sales.orders", depth=3)
112
+ names = {n.name for n in nodes}
113
+ assert "main.sales.daily_revenue" in names
114
+ assert not any("__preview_" in n for n in names) # bricksentry's own clones
115
+ assert "dbsql_query:q-clone" not in names # the statement that made the clone
116
+ assert "main.tmp.bs_test_candidate" not in names # dropped scratch table
117
+ assert "main.tmp.child_of_dropped" in names # but what it fed still exists
118
+ assert "job:111" in names
119
+
120
+
121
+ def test_uc_lineage_keeps_tables_when_existence_unknown(backend):
122
+ # Without access to information_schema, nothing is hidden (except preview clones).
123
+ nodes = _lineage_fixture(backend, with_tables_table=False).downstream("main.sales.orders", depth=3)
124
+ names = {n.name for n in nodes}
125
+ assert "main.tmp.bs_test_candidate" in names
126
+ assert not any("__preview_" in n for n in names)
@@ -0,0 +1,45 @@
1
+ """Keep the Databricks quickstart notebook valid: every code cell compiles,
2
+ it calls only agent tools that exist, and the .ipynb copy is up to date."""
3
+
4
+ import ast
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from bricksentry import agent_tools
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ sys.path.insert(0, str(ROOT / "scripts"))
13
+ import build_notebook # noqa: E402
14
+
15
+
16
+ def code_cells():
17
+ nb = build_notebook.build()
18
+ for c in nb["cells"]:
19
+ if c["cell_type"] == "code":
20
+ src = "".join(c["source"])
21
+ if not src.lstrip().startswith("%"):
22
+ yield src
23
+
24
+
25
+ def test_code_cells_compile():
26
+ cells = list(code_cells())
27
+ assert len(cells) >= 10
28
+ for src in cells:
29
+ ast.parse(src)
30
+
31
+
32
+ def test_uses_only_existing_agent_tools():
33
+ used = set()
34
+ for src in code_cells():
35
+ for node in ast.walk(ast.parse(src)):
36
+ if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "agent_tools":
37
+ used.add(node.attr)
38
+ assert used, "notebook should use agent_tools"
39
+ missing = {u for u in used if not hasattr(agent_tools, u)}
40
+ assert not missing, f"notebook calls missing agent tools: {missing}"
41
+
42
+
43
+ def test_ipynb_is_up_to_date():
44
+ on_disk = json.loads(build_notebook.OUT.read_text())
45
+ assert on_disk == json.loads(json.dumps(build_notebook.build())), "run: python scripts/build_notebook.py"
File without changes
File without changes
File without changes
File without changes