bricksentry 0.1.30__tar.gz → 0.1.32__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.30 → bricksentry-0.1.32}/CHANGELOG.md +21 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/PKG-INFO +9 -3
- {bricksentry-0.1.30 → bricksentry-0.1.32}/README.md +8 -2
- bricksentry-0.1.32/deploy/databricks-app/requirements.txt +1 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/pyproject.toml +1 -1
- {bricksentry-0.1.30 → bricksentry-0.1.32}/server.json +2 -2
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/__init__.py +1 -1
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/assess.py +16 -6
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/backends/base.py +36 -1
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/backends/databricks_backend.py +19 -0
- bricksentry-0.1.32/src/bricksentry/cleanup.py +78 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/cli.py +52 -1
- bricksentry-0.1.32/src/bricksentry/governed.py +57 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/history.py +8 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/job.py +30 -4
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/netguard.py +5 -2
- bricksentry-0.1.32/src/bricksentry/preview.py +218 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/databricks_template_schema.json +2 -2
- bricksentry-0.1.32/tests/test_0131.py +192 -0
- bricksentry-0.1.32/tests/test_0132.py +118 -0
- bricksentry-0.1.30/deploy/databricks-app/requirements.txt +0 -1
- bricksentry-0.1.30/src/bricksentry/preview.py +0 -105
- {bricksentry-0.1.30 → bricksentry-0.1.32}/.gitignore +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/CONTRIBUTING.md +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/LICENSE +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/SECURITY.md +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/action.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/container/Dockerfile +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/databricks-app/README.md +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/databricks-app/app.yaml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/databricks-app/bricksentry.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/databricks-app/databricks.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/deploy/databricks-app/grants.sql +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_check_my_table.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_quickstart.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_validation.ipynb +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/bricksentry_validation.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/github-workflow.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/databricks/policy.yml +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/examples/demo/agent_loop_demo.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/scripts/build_notebook.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/scripts/render_demo_image.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/__main__.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/agent_tools.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/agent_view.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/backends/__init__.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/backends/duckdb_backend.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/changes.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/config.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/demo.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/diff.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/explain.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/github.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/job_demo.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/lineage.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/mcp_server.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/measures.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/models.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/notify.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/policy.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/policy_templates.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/py.typed +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/report.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/src/bricksentry/validation.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/README.md +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/conftest.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0110.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0112.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0114.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0120.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0121.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0122.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0123.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0126.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0127.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0128.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0129.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_0130.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_018.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_019.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_assess_policy.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_check_notebook.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_databricks_and_uc.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_demo.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_diff.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_hr_notebook.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_notebook.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_notify_templates.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_preview_agents.py +0 -0
- {bricksentry-0.1.30 → bricksentry-0.1.32}/tests/test_sample_guard_and_store.py +0 -0
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.32 (2026-11-22)
|
|
4
|
+
|
|
5
|
+
Fixes from a scale, adversarial and platform-feature round on 0.1.31 on a Free Edition workspace. It found no safety problem: previews took 20–33 s on 1 million rows and 27–29 s on 10 million with exact counts; 8 operations at once on the same tables finished cleanly with unique clones; partitioned, liquid-clustered, identity-column and CHECK-constraint tables previewed correctly; hostile column names, forbidden words in values and 300-clause SQL were handled.
|
|
6
|
+
|
|
7
|
+
- **Columns named like keywords can be previewed.** A write touching a column named `` `drop` `` (or `alter`, `grant`…) was refused as a DROP. Quoted names are now names to the keyword check; the check that the SQL doesn't name the production table still reads inside them. An unclosed `` ` `` or `"` is refused, and `"..."` is read both with and without backslash escapes, as engines differ.
|
|
8
|
+
- **Tables with column masks or row filters get one clear message.** Databricks refuses shallow clones and time travel on them (`COLUMN_MASKS_FEATURE_NOT_SUPPORTED`, `ROW_LEVEL_SECURITY_FEATURE_NOT_SUPPORTED`), so neither `preview_write` nor `check-last-change` can work on them. bricksentry now checks for masks and filters first and says so, with what to do instead, before creating anything; it also recognises the engine's error if the check can't read them. It doesn't copy governed data into the sandbox to work around this, because the sandbox may be readable by more people than the table.
|
|
9
|
+
- README: measured timings on 1 and 10 million rows; sampling on serverless mainly lowers cost, not time; the masked-table limit.
|
|
10
|
+
|
|
11
|
+
## 0.1.31 (2026-11-22)
|
|
12
|
+
|
|
13
|
+
Fixes from two edge-case rounds on 0.1.30 on a Free Edition workspace: production was never changed in any scenario (writes to other tables, hidden statements, views, materialized views, column mapping and deletion vectors, `check-last-change` after OPTIMIZE, VACUUM, ALTER, RESTORE and overwrites, a write landing mid-check, Ctrl-C mid-run), and every rollback suggestion was confirmed by time travel.
|
|
14
|
+
|
|
15
|
+
- **A quoted value can no longer hide a second statement from `preview_write`.** The guard treated `--` or `/*` inside a quoted value as the start of a comment, so in `UPDATE t SET a = '--'; DROP TABLE other` it didn't see the `;` or the `DROP`. The guard now reads `'...'`, `"..."` and `` `...` `` the way the engine does, checks the SQL both ways where engines differ on backslashes, and refuses a quote or `/*` that is never closed. Found while fixing the next item; the live rounds didn't hit it. Upgrade if agents can call `preview_write`.
|
|
16
|
+
- **Comments before the statement are allowed.** `-- fix duplicates` above a MERGE was refused as "must start with INSERT, MERGE…". Agents often start with a comment.
|
|
17
|
+
- **`{{target}}` or the table name inside a quoted value stays data.** It was replaced with the clone's name (which failed safe as `needs_human`, but confusingly). Only the table position is rewritten now.
|
|
18
|
+
- **A webhook secret that can't be read no longer stops the job with a traceback.** The check still runs and prints its result, then one line says which secret couldn't be read and why, and the task fails (exit 2) so the broken alert gets fixed.
|
|
19
|
+
- **The outbound-URL guard blocks carrier-grade NAT addresses** (100.64.0.0/10), used inside some cloud networks.
|
|
20
|
+
- **New: `bricksentry cleanup`.** A run killed outright (process or cluster gone) can leave its clone behind. `cleanup` lists clones older than 6 hours and asks before dropping them; it only ever matches bricksentry's own clone names.
|
|
21
|
+
- When bricksentry creates the scratch schema because it didn't exist, it says so (and `preview_write` returns `created_schema`).
|
|
22
|
+
- README: comments and CTE writes in `preview_write`, full table names, and that the Python API's diffs include example rows while the agent tools don't.
|
|
23
|
+
|
|
3
24
|
## 0.1.30 (2026-11-18)
|
|
4
25
|
|
|
5
26
|
A patch from the first real use of bricksentry as an assistant's safety gate: an assistant built a Bronze/Silver/Gold HR pipeline, then changed the Gold logic only after `whats_downstream`, `rollback_plan`, `preview_write` and `safe_to_ship`. Verified on Databricks before release: the CTAS preview that failed now runs with exact counts, a CTAS reading the table it replaces works, nothing is left in the sandbox, production stays at its version, and the battery passed 15 of 15.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bricksentry
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.32
|
|
4
4
|
Summary: Change impact analysis and deployment guardrails for data changes on Databricks, for 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
|
|
@@ -203,7 +203,7 @@ bricksentry is listed in the [official MCP Registry](https://registry.modelconte
|
|
|
203
203
|
Designed for agents:
|
|
204
204
|
|
|
205
205
|
- **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
|
|
206
|
-
- **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements.
|
|
206
|
+
- **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements. Comments before the statement are fine, and so are columns named like keywords when quoted (`` `drop` ``). Write the target as its full name (`main.sales.orders`) or `{{target}}`; a table name or `{{target}}` inside a quoted value is left as data. A write wrapped in a CTE (`WITH ... INSERT`) is refused: put the CTE in the statement's `SELECT` instead.
|
|
207
207
|
- **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
|
|
208
208
|
- **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window. A full-table checksum guards the sample: if the sample shows no change but the tables differ, the diff re-runs on every row, so a one-row change can't slip through.
|
|
209
209
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
@@ -257,8 +257,11 @@ bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updat
|
|
|
257
257
|
bricksentry assess --from-git origin/main --pr 42 --format markdown --fail-on needs_human
|
|
258
258
|
bricksentry rollback main.sales.orders
|
|
259
259
|
bricksentry check-last-change main.sales.orders # the change a pipeline already made
|
|
260
|
+
bricksentry cleanup # drop clones left by a run that was killed
|
|
260
261
|
```
|
|
261
262
|
|
|
263
|
+
Every clone is dropped when its run ends, even on Ctrl-C; only a run that is killed outright can leave one behind. `cleanup` lists clones older than 6 hours in `sandbox_schema` (or `--scratch-schema`) and asks before dropping them. It only matches bricksentry's own clone names (`TABLE__preview_xxxxxxxx`, `bs_check_TABLE_vN_xxxxxxxx`), never your tables. If the scratch schema doesn't exist, bricksentry creates it and says so.
|
|
264
|
+
|
|
262
265
|
Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration errors.
|
|
263
266
|
|
|
264
267
|
**In GitHub Actions.** Build your PR's version of the pipeline into a per-PR schema (for example with a Databricks Asset Bundle `ci` target), then add:
|
|
@@ -367,6 +370,8 @@ print(a.tables[0].summary)
|
|
|
367
370
|
s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sales.orders")
|
|
368
371
|
```
|
|
369
372
|
|
|
373
|
+
The Python API is for people: unlike the agent tools and the MCP server, its diffs include example rows (before and after values), so you can see what changed. Don't hand its output to an agent that shouldn't see the data; use the agent tools for that.
|
|
374
|
+
|
|
370
375
|
## Configuration
|
|
371
376
|
|
|
372
377
|
```yaml
|
|
@@ -490,7 +495,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
|
|
|
490
495
|
|
|
491
496
|
## What a check costs
|
|
492
497
|
|
|
493
|
-
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
498
|
+
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. Measured on a Free Edition serverless warehouse with 0.1.31: a preview took 20–33 s on 1 million rows and 27–29 s on 10 million, `check-last-change` 27 s on 10 million. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. On serverless, sampling mainly lowers warehouse cost; the time is spent reading the tables either way. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
494
499
|
|
|
495
500
|
## Audit trail
|
|
496
501
|
|
|
@@ -526,6 +531,7 @@ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by i
|
|
|
526
531
|
## Known limits (v0.1.x)
|
|
527
532
|
|
|
528
533
|
- **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; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
|
|
534
|
+
- **Tables with column masks or row filters can't be checked.** Databricks refuses shallow clones and time travel on them, so `preview_write` and `check-last-change` stop with a message saying so. bricksentry won't copy governed data into the sandbox to get around it. Check the change on the table that feeds it, or on a dev copy without the mask or filter.
|
|
529
535
|
- **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
|
|
530
536
|
- **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
|
|
531
537
|
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.28 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
|
|
@@ -155,7 +155,7 @@ bricksentry is listed in the [official MCP Registry](https://registry.modelconte
|
|
|
155
155
|
Designed for agents:
|
|
156
156
|
|
|
157
157
|
- **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
|
|
158
|
-
- **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements.
|
|
158
|
+
- **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements. Comments before the statement are fine, and so are columns named like keywords when quoted (`` `drop` ``). Write the target as its full name (`main.sales.orders`) or `{{target}}`; a table name or `{{target}}` inside a quoted value is left as data. A write wrapped in a CTE (`WITH ... INSERT`) is refused: put the CTE in the statement's `SELECT` instead.
|
|
159
159
|
- **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
|
|
160
160
|
- **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window. A full-table checksum guards the sample: if the sample shows no change but the tables differ, the diff re-runs on every row, so a one-row change can't slip through.
|
|
161
161
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
@@ -209,8 +209,11 @@ bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updat
|
|
|
209
209
|
bricksentry assess --from-git origin/main --pr 42 --format markdown --fail-on needs_human
|
|
210
210
|
bricksentry rollback main.sales.orders
|
|
211
211
|
bricksentry check-last-change main.sales.orders # the change a pipeline already made
|
|
212
|
+
bricksentry cleanup # drop clones left by a run that was killed
|
|
212
213
|
```
|
|
213
214
|
|
|
215
|
+
Every clone is dropped when its run ends, even on Ctrl-C; only a run that is killed outright can leave one behind. `cleanup` lists clones older than 6 hours in `sandbox_schema` (or `--scratch-schema`) and asks before dropping them. It only matches bricksentry's own clone names (`TABLE__preview_xxxxxxxx`, `bs_check_TABLE_vN_xxxxxxxx`), never your tables. If the scratch schema doesn't exist, bricksentry creates it and says so.
|
|
216
|
+
|
|
214
217
|
Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration errors.
|
|
215
218
|
|
|
216
219
|
**In GitHub Actions.** Build your PR's version of the pipeline into a per-PR schema (for example with a Databricks Asset Bundle `ci` target), then add:
|
|
@@ -319,6 +322,8 @@ print(a.tables[0].summary)
|
|
|
319
322
|
s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sales.orders")
|
|
320
323
|
```
|
|
321
324
|
|
|
325
|
+
The Python API is for people: unlike the agent tools and the MCP server, its diffs include example rows (before and after values), so you can see what changed. Don't hand its output to an agent that shouldn't see the data; use the agent tools for that.
|
|
326
|
+
|
|
322
327
|
## Configuration
|
|
323
328
|
|
|
324
329
|
```yaml
|
|
@@ -442,7 +447,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
|
|
|
442
447
|
|
|
443
448
|
## What a check costs
|
|
444
449
|
|
|
445
|
-
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
450
|
+
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. Measured on a Free Edition serverless warehouse with 0.1.31: a preview took 20–33 s on 1 million rows and 27–29 s on 10 million, `check-last-change` 27 s on 10 million. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. On serverless, sampling mainly lowers warehouse cost; the time is spent reading the tables either way. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
446
451
|
|
|
447
452
|
## Audit trail
|
|
448
453
|
|
|
@@ -478,6 +483,7 @@ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by i
|
|
|
478
483
|
## Known limits (v0.1.x)
|
|
479
484
|
|
|
480
485
|
- **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; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
|
|
486
|
+
- **Tables with column masks or row filters can't be checked.** Databricks refuses shallow clones and time travel on them, so `preview_write` and `check-last-change` stop with a message saying so. bricksentry won't copy governed data into the sandbox to get around it. Check the change on the table that feeds it, or on a dev copy without the mask or filter.
|
|
481
487
|
- **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
|
|
482
488
|
- **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
|
|
483
489
|
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.28 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bricksentry[databricks,mcp]==0.1.32
|
|
@@ -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.32"
|
|
8
8
|
description = "Change impact analysis and deployment guardrails for data changes on Databricks, for 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"
|
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
10
|
"websiteUrl": "https://bricksentry.org",
|
|
11
|
-
"version": "0.1.
|
|
11
|
+
"version": "0.1.32",
|
|
12
12
|
"packages": [
|
|
13
13
|
{
|
|
14
14
|
"registryType": "pypi",
|
|
15
15
|
"identifier": "bricksentry-mcp",
|
|
16
|
-
"version": "0.1.
|
|
16
|
+
"version": "0.1.32",
|
|
17
17
|
"runtimeHint": "uvx",
|
|
18
18
|
"transport": {
|
|
19
19
|
"type": "stdio"
|
|
@@ -9,6 +9,7 @@ import uuid
|
|
|
9
9
|
from datetime import datetime, timezone
|
|
10
10
|
from typing import Any
|
|
11
11
|
|
|
12
|
+
from bricksentry import governed
|
|
12
13
|
from bricksentry.backends.base import Backend, make_backend
|
|
13
14
|
from bricksentry.config import Config
|
|
14
15
|
from bricksentry.diff import diff_tables
|
|
@@ -16,7 +17,7 @@ from bricksentry.explain import explain_columns, explain_diff, explain_impact
|
|
|
16
17
|
from bricksentry.lineage import LineageProvider, make_lineage
|
|
17
18
|
from bricksentry.models import Assessment, ImpactNode, TableAssessment, TableDiff, Verdict
|
|
18
19
|
from bricksentry.policy import ColumnContext, Policy
|
|
19
|
-
from bricksentry.preview import rewrite_for_preview, sandbox_name
|
|
20
|
+
from bricksentry.preview import rewrite_for_preview, sandbox_name, statement_head
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class Sentry:
|
|
@@ -210,12 +211,17 @@ class Sentry:
|
|
|
210
211
|
raise ValueError(f"No keys configured for {target}; pass keys=[...] to preview_write")
|
|
211
212
|
clone = sandbox_name(self.config.sandbox_schema, target)
|
|
212
213
|
rewritten = rewrite_for_preview(sql, target, clone, self.backend.quote)
|
|
214
|
+
what = governed.describe(self.backend, target)
|
|
215
|
+
if what:
|
|
216
|
+
raise ValueError(governed.preview_message(target, what))
|
|
213
217
|
schema = ".".join(clone.split(".")[:-1])
|
|
214
|
-
|
|
215
|
-
self.backend.ensure_schema(schema)
|
|
218
|
+
created = bool(schema and self.backend.ensure_schema(schema))
|
|
216
219
|
try:
|
|
217
220
|
self.backend.clone(target, clone)
|
|
218
221
|
except Exception as e:
|
|
222
|
+
what = governed.from_error(e)
|
|
223
|
+
if what:
|
|
224
|
+
raise ValueError(governed.preview_message(target, what)) from None
|
|
219
225
|
raise RuntimeError(
|
|
220
226
|
f"Could not clone {target} to preview the write: {_first_line(e)}. Check the table name "
|
|
221
227
|
f"and that you can create tables in {schema or 'the sandbox schema'}."
|
|
@@ -225,11 +231,13 @@ class Sentry:
|
|
|
225
231
|
# applies CLUSTER BY AUTO to new tables, which a clone can't take). The clone stays,
|
|
226
232
|
# for statements that read the target (CREATE OR REPLACE TABLE t AS SELECT ... FROM t).
|
|
227
233
|
result = clone
|
|
228
|
-
|
|
234
|
+
head = statement_head(rewritten)
|
|
235
|
+
lead = len(rewritten) - len(head)
|
|
236
|
+
m = _REPLACE_HEAD.match(head)
|
|
229
237
|
if m:
|
|
230
238
|
result = clone + "_out"
|
|
231
|
-
rewritten = rewritten[: m.start("name")] + ".".join(
|
|
232
|
-
self.backend.quote(p) for p in result.split(".")) + rewritten[m.end("name"):]
|
|
239
|
+
rewritten = rewritten[: lead + m.start("name")] + ".".join(
|
|
240
|
+
self.backend.quote(p) for p in result.split(".")) + rewritten[lead + m.end("name"):]
|
|
233
241
|
try:
|
|
234
242
|
try:
|
|
235
243
|
self.backend.execute(rewritten)
|
|
@@ -249,6 +257,8 @@ class Sentry:
|
|
|
249
257
|
pass
|
|
250
258
|
out = assessment.to_dict()
|
|
251
259
|
out["preview"] = {"sandbox_table": result if keep else None, "executed_sql": rewritten}
|
|
260
|
+
if created:
|
|
261
|
+
out["preview"]["created_schema"] = schema
|
|
252
262
|
return out
|
|
253
263
|
|
|
254
264
|
# --- alerts ---------------------------------------------------------------
|
|
@@ -4,9 +4,12 @@ session and stays cheap enough for an agent to call in a loop."""
|
|
|
4
4
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
|
+
import logging
|
|
7
8
|
from abc import ABC, abstractmethod
|
|
8
9
|
from typing import Any
|
|
9
10
|
|
|
11
|
+
log = logging.getLogger("bricksentry")
|
|
12
|
+
|
|
10
13
|
NUMERIC_PREFIXES = (
|
|
11
14
|
"tinyint", "smallint", "int", "bigint", "long", "short", "byte", "integer",
|
|
12
15
|
"float", "double", "real", "decimal", "numeric", "hugeint", "ubigint", "uinteger",
|
|
@@ -128,8 +131,40 @@ class Backend(ABC):
|
|
|
128
131
|
def drop(self, table: str) -> None:
|
|
129
132
|
self.execute(f"DROP TABLE IF EXISTS {self.qualified(table)}")
|
|
130
133
|
|
|
131
|
-
def
|
|
134
|
+
def schema_exists(self, schema: str) -> bool | None:
|
|
135
|
+
"""True / False, or None when the engine can't say (then nothing is reported)."""
|
|
136
|
+
*cat, name = schema.split(".")
|
|
137
|
+
where = f"lower(schema_name) = {self._lit(name.strip('`').lower())}"
|
|
138
|
+
if cat:
|
|
139
|
+
where += f" AND lower(catalog_name) = {self._lit(cat[0].strip('`').lower())}"
|
|
140
|
+
try:
|
|
141
|
+
return bool(self.query(f"SELECT 1 AS x FROM information_schema.schemata WHERE {where} LIMIT 1"))
|
|
142
|
+
except Exception:
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def _lit(v: str) -> str:
|
|
147
|
+
return "'" + v.replace("'", "''") + "'"
|
|
148
|
+
|
|
149
|
+
def ensure_schema(self, schema: str) -> bool:
|
|
150
|
+
"""Create the scratch schema if needed. Returns True when it was created, and says so:
|
|
151
|
+
a schema appearing out of nowhere should never be a surprise."""
|
|
152
|
+
existed = self.schema_exists(schema)
|
|
132
153
|
self.execute(f"CREATE SCHEMA IF NOT EXISTS {self.qualified(schema)}")
|
|
154
|
+
if existed is False:
|
|
155
|
+
log.warning("bricksentry: created scratch schema %s (it didn't exist). bricksentry only puts "
|
|
156
|
+
"temporary clones there; drop it when you no longer need it.", schema)
|
|
157
|
+
return True
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
def list_tables(self, schema: str) -> list[dict[str, Any]]:
|
|
161
|
+
"""Tables in ``schema``: [{"name": ..., "created": datetime | None}]."""
|
|
162
|
+
*cat, name = schema.split(".")
|
|
163
|
+
where = f"lower(table_schema) = {self._lit(name.strip('`').lower())}"
|
|
164
|
+
if cat:
|
|
165
|
+
where += f" AND lower(table_catalog) = {self._lit(cat[0].strip('`').lower())}"
|
|
166
|
+
rows = self.query(f"SELECT table_name FROM information_schema.tables WHERE {where}")
|
|
167
|
+
return [{"name": r["table_name"], "created": None} for r in rows]
|
|
133
168
|
|
|
134
169
|
def current_version(self, table: str) -> int | None:
|
|
135
170
|
return None
|
|
@@ -224,6 +224,25 @@ class DatabricksBackend(Backend):
|
|
|
224
224
|
e["row_filter"] = True
|
|
225
225
|
return out
|
|
226
226
|
|
|
227
|
+
def schema_exists(self, schema: str) -> bool | None:
|
|
228
|
+
parts = [p.strip("`") for p in schema.split(".")]
|
|
229
|
+
if len(parts) != 2:
|
|
230
|
+
return None
|
|
231
|
+
try:
|
|
232
|
+
rows = self.query(f"SELECT 1 AS x FROM {self.quote(parts[0])}.information_schema.schemata "
|
|
233
|
+
f"WHERE schema_name = {self._lit(parts[1].lower())} LIMIT 1")
|
|
234
|
+
except Exception: # no such catalog, no access: the CREATE that follows reports it
|
|
235
|
+
return None
|
|
236
|
+
return bool(rows)
|
|
237
|
+
|
|
238
|
+
def list_tables(self, schema: str) -> list[dict[str, Any]]:
|
|
239
|
+
parts = [p.strip("`") for p in schema.split(".")]
|
|
240
|
+
if len(parts) != 2:
|
|
241
|
+
raise ValueError(f"Give the scratch schema as catalog.schema, got {schema!r}")
|
|
242
|
+
rows = self.query(f"SELECT table_name, created FROM {self.quote(parts[0])}.information_schema.tables "
|
|
243
|
+
f"WHERE table_schema = {self._lit(parts[1].lower())}")
|
|
244
|
+
return [{"name": r["table_name"], "created": r.get("created")} for r in rows]
|
|
245
|
+
|
|
227
246
|
@staticmethod
|
|
228
247
|
def _lit(v: str) -> str:
|
|
229
248
|
return "'" + v.replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Find and drop clones that bricksentry left behind.
|
|
2
|
+
|
|
3
|
+
Every clone is dropped when its run ends, even on Ctrl-C. Only a run that is killed
|
|
4
|
+
outright (the process or the cluster dies) can leave one behind. Such a clone is inert,
|
|
5
|
+
but it takes a name in the scratch schema, so ``bricksentry cleanup`` lists and drops them.
|
|
6
|
+
|
|
7
|
+
It only ever touches tables whose names match bricksentry's own clone names exactly:
|
|
8
|
+
|
|
9
|
+
* ``<table>__preview_<8 hex>`` and ``..._out`` (preview_write)
|
|
10
|
+
* ``bs_check_<table>_v<version>_<8 hex>`` (check-last-change and the job)
|
|
11
|
+
|
|
12
|
+
so your own tables in the same schema are never matched.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
CLONE_PATTERNS = (
|
|
22
|
+
re.compile(r"^[A-Za-z0-9_\-]+__preview_[0-9a-f]{8}(?:_out)?$"),
|
|
23
|
+
re.compile(r"^bs_check_[A-Za-z0-9_]{1,40}_v\d+_[0-9a-f]{8}$"),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_clone_name(name: str) -> bool:
|
|
28
|
+
return any(p.match(name) for p in CLONE_PATTERNS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _age_hours(created: Any, now: datetime) -> float | None:
|
|
32
|
+
if created in (None, ""):
|
|
33
|
+
return None
|
|
34
|
+
if isinstance(created, (int, float)):
|
|
35
|
+
created = datetime.fromtimestamp(created / 1000 if created > 1e11 else created, timezone.utc)
|
|
36
|
+
elif isinstance(created, str):
|
|
37
|
+
try:
|
|
38
|
+
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
|
|
39
|
+
except ValueError:
|
|
40
|
+
return None
|
|
41
|
+
if not isinstance(created, datetime):
|
|
42
|
+
return None
|
|
43
|
+
if created.tzinfo is None:
|
|
44
|
+
created = created.replace(tzinfo=timezone.utc)
|
|
45
|
+
return (now - created).total_seconds() / 3600
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def find_leftovers(backend: Any, schema: str, older_than_hours: float = 6.0,
|
|
49
|
+
now: datetime | None = None) -> tuple[list[str], list[str]]:
|
|
50
|
+
"""Returns (clones old enough to drop, clones skipped because they are recent or their age is
|
|
51
|
+
unknown). A recent clone may belong to a run that is still going, so it is never dropped."""
|
|
52
|
+
now = now or datetime.now(timezone.utc)
|
|
53
|
+
drop, skip = [], []
|
|
54
|
+
for t in backend.list_tables(schema):
|
|
55
|
+
name = t["name"]
|
|
56
|
+
if not is_clone_name(name):
|
|
57
|
+
continue
|
|
58
|
+
age = _age_hours(t.get("created"), now)
|
|
59
|
+
if older_than_hours <= 0 or (age is not None and age >= older_than_hours):
|
|
60
|
+
drop.append(f"{schema}.{name}")
|
|
61
|
+
else:
|
|
62
|
+
skip.append(f"{schema}.{name}")
|
|
63
|
+
return sorted(drop), sorted(skip)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def drop_leftovers(backend: Any, tables: list[str]) -> list[tuple[str, str | None]]:
|
|
67
|
+
"""Drop each table; returns [(table, error or None)]."""
|
|
68
|
+
done = []
|
|
69
|
+
for t in tables:
|
|
70
|
+
if not is_clone_name(t.split(".")[-1]): # never trust a caller's list
|
|
71
|
+
done.append((t, "not a bricksentry clone name; skipped"))
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
backend.drop(t)
|
|
75
|
+
done.append((t, None))
|
|
76
|
+
except Exception as e:
|
|
77
|
+
done.append((t, (str(e).strip().splitlines() or [type(e).__name__])[0][:200]))
|
|
78
|
+
return done
|
|
@@ -246,7 +246,9 @@ def check_last_change(table, keys, version, since, sample_pct, allow_no_change,
|
|
|
246
246
|
click.echo(str(e), err=True)
|
|
247
247
|
sys.exit(0 if allow_no_change else 2)
|
|
248
248
|
except (NotImplementedError, ValueError, RuntimeError) as e:
|
|
249
|
-
|
|
249
|
+
err = click.ClickException(str(e))
|
|
250
|
+
err.exit_code = 2 # never 1, which means BLOCK
|
|
251
|
+
raise err from e
|
|
250
252
|
md = to_markdown(a)
|
|
251
253
|
if output:
|
|
252
254
|
Path(output).write_text(md)
|
|
@@ -448,6 +450,55 @@ def _run(cmd: click.Command, prog_name: str | None = None) -> None:
|
|
|
448
450
|
sys.exit(2)
|
|
449
451
|
|
|
450
452
|
|
|
453
|
+
@main.command()
|
|
454
|
+
@click.option("--scratch-schema", "schema", default=None,
|
|
455
|
+
help="catalog.schema to clean. Defaults to sandbox_schema in bricksentry.yml. Repeat the command "
|
|
456
|
+
"for the job's --scratch-schema if that is a different schema.")
|
|
457
|
+
@click.option("--older-than-hours", type=float, default=6.0, show_default=True,
|
|
458
|
+
help="Only drop clones at least this old, so a run that is still going keeps its clones. "
|
|
459
|
+
"0 drops every bricksentry clone, including ones whose age can't be read.")
|
|
460
|
+
@click.option("--yes", "-y", is_flag=True, help="Drop without asking.")
|
|
461
|
+
@config_opt
|
|
462
|
+
def cleanup(schema, older_than_hours, yes, config_path):
|
|
463
|
+
"""Drop clones left behind by runs that were killed outright.
|
|
464
|
+
|
|
465
|
+
Only tables named like bricksentry's own clones are matched (TABLE__preview_xxxxxxxx and
|
|
466
|
+
bs_check_TABLE_vN_xxxxxxxx). It lists them and asks before dropping anything.
|
|
467
|
+
"""
|
|
468
|
+
from bricksentry.cleanup import drop_leftovers, find_leftovers
|
|
469
|
+
|
|
470
|
+
s = _sentry(config_path)
|
|
471
|
+
schema = schema or s.config.sandbox_schema
|
|
472
|
+
drop, skip = find_leftovers(s.backend, schema, older_than_hours)
|
|
473
|
+
if skip:
|
|
474
|
+
click.echo(f"Keeping {len(skip)} recent clone(s) (younger than {older_than_hours:g}h, or age unknown; "
|
|
475
|
+
"use --older-than-hours 0 to include them):")
|
|
476
|
+
for t in skip:
|
|
477
|
+
click.echo(f" {t}")
|
|
478
|
+
if not drop:
|
|
479
|
+
click.echo(f"No leftover bricksentry clones to drop in {schema}.")
|
|
480
|
+
return
|
|
481
|
+
click.echo(f"Leftover bricksentry clone(s) in {schema}:")
|
|
482
|
+
for t in drop:
|
|
483
|
+
click.echo(f" {t}")
|
|
484
|
+
if not yes:
|
|
485
|
+
if not sys.stdin.isatty():
|
|
486
|
+
click.echo("Nothing dropped. Re-run with --yes to drop them.", err=True)
|
|
487
|
+
return
|
|
488
|
+
if not click.confirm(f"Drop these {len(drop)} table(s)?", default=False):
|
|
489
|
+
click.echo("Nothing dropped.")
|
|
490
|
+
return
|
|
491
|
+
failed = 0
|
|
492
|
+
for t, err in drop_leftovers(s.backend, drop):
|
|
493
|
+
if err:
|
|
494
|
+
failed += 1
|
|
495
|
+
click.echo(f" could not drop {t}: {err}", err=True)
|
|
496
|
+
else:
|
|
497
|
+
click.echo(f" dropped {t}")
|
|
498
|
+
if failed:
|
|
499
|
+
sys.exit(2)
|
|
500
|
+
|
|
501
|
+
|
|
451
502
|
def entry() -> None:
|
|
452
503
|
"""Console entry point: turn unexpected errors into a clean message and exit code 2."""
|
|
453
504
|
_run(main)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Tables with Unity Catalog column masks or row filters.
|
|
2
|
+
|
|
3
|
+
Databricks refuses both shallow clones and time travel (``VERSION AS OF``) on these tables
|
|
4
|
+
(``COLUMN_MASKS_FEATURE_NOT_SUPPORTED`` / ``ROW_LEVEL_SECURITY_FEATURE_NOT_SUPPORTED``).
|
|
5
|
+
So bricksentry can't preview a write on them (no clone) or compare two versions of them
|
|
6
|
+
(no time travel), and it says so up front, in one clear message, instead of failing in the
|
|
7
|
+
middle. It never copies governed data into the scratch schema as a workaround: the scratch
|
|
8
|
+
schema may be readable by more people than the table, which is what masks and filters
|
|
9
|
+
exist to prevent. And it never suggests removing the mask or filter.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
_CODES = ("COLUMN_MASKS_FEATURE_NOT_SUPPORTED", "ROW_LEVEL_SECURITY_FEATURE_NOT_SUPPORTED")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def describe(db: Any, table: str) -> str | None:
|
|
20
|
+
""""a column mask (on amount)", "a row filter", both, or None. None also when the
|
|
21
|
+
protections can't be read; the engine's own error is then recognised by ``from_error``."""
|
|
22
|
+
try:
|
|
23
|
+
p = (db.protections([table]) or {}).get(table) or {}
|
|
24
|
+
except Exception:
|
|
25
|
+
return None
|
|
26
|
+
parts = []
|
|
27
|
+
if p.get("masked"):
|
|
28
|
+
cols = ", ".join(sorted(p["masked"]))
|
|
29
|
+
parts.append(f"a column mask (on {cols})")
|
|
30
|
+
if p.get("row_filter"):
|
|
31
|
+
parts.append("a row filter")
|
|
32
|
+
return " and ".join(parts) or None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def from_error(e: BaseException) -> str | None:
|
|
36
|
+
text = str(e)
|
|
37
|
+
if _CODES[0] in text and _CODES[1] in text:
|
|
38
|
+
return "a column mask and a row filter"
|
|
39
|
+
if _CODES[0] in text:
|
|
40
|
+
return "a column mask"
|
|
41
|
+
if _CODES[1] in text:
|
|
42
|
+
return "a row filter"
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_message(table: str, what: str) -> str:
|
|
47
|
+
return (f"{table} has {what}. Databricks doesn't allow reading earlier versions of tables with column "
|
|
48
|
+
"masks or row filters (time travel and clones are refused), so check-last-change can't compare "
|
|
49
|
+
"versions of it. Check changes before they reach it instead: preview or assess the write on the "
|
|
50
|
+
"table that feeds it, or on a dev copy without the mask or filter.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def preview_message(table: str, what: str) -> str:
|
|
54
|
+
return (f"{table} has {what}. Databricks doesn't allow shallow clones of tables with column masks or row "
|
|
55
|
+
"filters, and bricksentry won't copy governed data into the sandbox, so this write can't be "
|
|
56
|
+
"previewed here. Preview it on a dev copy of the table without the mask or filter, or on the table "
|
|
57
|
+
"that feeds it.")
|
|
@@ -14,6 +14,8 @@ from dataclasses import dataclass, field
|
|
|
14
14
|
from datetime import datetime, timezone
|
|
15
15
|
from typing import TYPE_CHECKING, Any
|
|
16
16
|
|
|
17
|
+
from bricksentry import governed
|
|
18
|
+
|
|
17
19
|
if TYPE_CHECKING: # pragma: no cover
|
|
18
20
|
from bricksentry.assess import Sentry
|
|
19
21
|
from bricksentry.models import Assessment
|
|
@@ -253,6 +255,9 @@ def check_change(
|
|
|
253
255
|
if not _NAME.fullmatch(table):
|
|
254
256
|
raise ValueError(f"table must be schema.table or catalog.schema.table; got {table!r}")
|
|
255
257
|
|
|
258
|
+
what = governed.describe(db, table)
|
|
259
|
+
if what:
|
|
260
|
+
raise ValueError(governed.check_message(table, what))
|
|
256
261
|
history = _read_history(db, table, history_limit)
|
|
257
262
|
change = pick_change(table, history, version=version, since=since)
|
|
258
263
|
keys = keys or sentry.config.spec(table).keys or db.primary_key(table)
|
|
@@ -273,6 +278,9 @@ def check_change(
|
|
|
273
278
|
try:
|
|
274
279
|
db.clone_version(table, target, v)
|
|
275
280
|
except Exception as e:
|
|
281
|
+
what = governed.from_error(e)
|
|
282
|
+
if what:
|
|
283
|
+
raise ValueError(governed.check_message(table, what)) from None
|
|
276
284
|
raise RuntimeError(
|
|
277
285
|
f"Could not read version {v} of {table}: its files may have been removed by VACUUM, "
|
|
278
286
|
f"or you may lack CREATE TABLE on {scratch}. ({str(e).strip()[:300]})") from None
|
|
@@ -97,7 +97,26 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
97
97
|
return p
|
|
98
98
|
|
|
99
99
|
|
|
100
|
-
def
|
|
100
|
+
def _secret_or_problem(ref: str | None, flag: str, problems: list[str] | None):
|
|
101
|
+
"""Read a webhook secret. If it can't be read, the check still runs (an alert channel is
|
|
102
|
+
no reason to skip the safety check), and the problem is reported and fails the task."""
|
|
103
|
+
if not ref:
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
return read_secret(ref)
|
|
107
|
+
except SystemExit as e: # a malformed scope/key
|
|
108
|
+
msg = str(e)
|
|
109
|
+
except Exception as e:
|
|
110
|
+
first = (str(e).strip().splitlines() or [type(e).__name__])[0][:200]
|
|
111
|
+
msg = (f"{flag} {ref}: could not read the secret ({first}). Check that the secret scope and key exist "
|
|
112
|
+
"and that the job's run-as identity can READ the scope.")
|
|
113
|
+
if problems is None:
|
|
114
|
+
raise SystemExit(msg)
|
|
115
|
+
problems.append(msg + " No alert was sent on that channel.")
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def make_sentry(args: argparse.Namespace, backend: Any = None, problems: list[str] | None = None):
|
|
101
120
|
from bricksentry.assess import Sentry
|
|
102
121
|
from bricksentry.config import Config
|
|
103
122
|
|
|
@@ -115,7 +134,8 @@ def make_sentry(args: argparse.Namespace, backend: Any = None):
|
|
|
115
134
|
if args.scratch_schema:
|
|
116
135
|
cfg.sandbox_schema = args.scratch_schema
|
|
117
136
|
notify = dict(cfg.notify or {})
|
|
118
|
-
slack
|
|
137
|
+
slack = _secret_or_problem(args.slack_secret, "--slack-secret", problems)
|
|
138
|
+
teams = _secret_or_problem(args.teams_secret, "--teams-secret", problems)
|
|
119
139
|
if slack:
|
|
120
140
|
notify["slack_webhook"] = slack
|
|
121
141
|
if teams:
|
|
@@ -147,7 +167,10 @@ def run(argv: list[str] | None = None, backend: Any = None, out=print) -> int:
|
|
|
147
167
|
out("bricksentry: no tables to check.")
|
|
148
168
|
return 0
|
|
149
169
|
keys = parse_keys(args.key + [k for k in (args.keys or "").split(";") if k.strip()])
|
|
150
|
-
|
|
170
|
+
problems: list[str] = []
|
|
171
|
+
s = make_sentry(args, backend=backend, problems=problems)
|
|
172
|
+
for p in problems:
|
|
173
|
+
out(f"bricksentry: WARNING {p}")
|
|
151
174
|
worst: Verdict | None = None
|
|
152
175
|
errors = 0
|
|
153
176
|
for table in tables:
|
|
@@ -172,7 +195,10 @@ def run(argv: list[str] | None = None, backend: Any = None, out=print) -> int:
|
|
|
172
195
|
out(f" Undo: {t.rollback}")
|
|
173
196
|
for line in s.notify(a):
|
|
174
197
|
out(f" notify {line}")
|
|
175
|
-
if errors:
|
|
198
|
+
if errors or problems:
|
|
199
|
+
if problems and not errors:
|
|
200
|
+
out("bricksentry: the check ran, but the notification setup above is broken; failing this task so "
|
|
201
|
+
"it gets fixed.")
|
|
176
202
|
return 2
|
|
177
203
|
if worst is not None and args.fail_on != "never" and worst.rank >= Verdict(args.fail_on).rank:
|
|
178
204
|
out(f"bricksentry: verdict {worst.value} is at or above --fail-on {args.fail_on}; failing this task "
|