bricksentry 0.1.29__tar.gz → 0.1.31__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.29 → bricksentry-0.1.31}/CHANGELOG.md +20 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/PKG-INFO +30 -6
- {bricksentry-0.1.29 → bricksentry-0.1.31}/README.md +29 -5
- bricksentry-0.1.31/deploy/databricks-app/requirements.txt +1 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/pyproject.toml +1 -1
- {bricksentry-0.1.29 → bricksentry-0.1.31}/server.json +2 -2
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/__init__.py +1 -1
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/assess.py +30 -5
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/backends/base.py +36 -1
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/backends/databricks_backend.py +19 -0
- bricksentry-0.1.31/src/bricksentry/cleanup.py +78 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/cli.py +49 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/explain.py +7 -1
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/job.py +30 -4
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/netguard.py +5 -2
- bricksentry-0.1.31/src/bricksentry/preview.py +206 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/databricks_template_schema.json +2 -2
- bricksentry-0.1.31/tests/test_0130.py +52 -0
- bricksentry-0.1.31/tests/test_0131.py +192 -0
- bricksentry-0.1.29/deploy/databricks-app/requirements.txt +0 -1
- bricksentry-0.1.29/src/bricksentry/preview.py +0 -105
- {bricksentry-0.1.29 → bricksentry-0.1.31}/.gitignore +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/CONTRIBUTING.md +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/LICENSE +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/SECURITY.md +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/action.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/container/Dockerfile +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/databricks-app/README.md +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/databricks-app/app.yaml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/databricks-app/bricksentry.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/databricks-app/databricks.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/deploy/databricks-app/grants.sql +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_check_my_table.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_quickstart.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_validation.ipynb +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/bricksentry_validation.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/github-workflow.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/databricks/policy.yml +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/examples/demo/agent_loop_demo.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/scripts/build_notebook.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/scripts/render_demo_image.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/__main__.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/agent_tools.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/agent_view.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/backends/__init__.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/backends/duckdb_backend.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/changes.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/config.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/demo.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/diff.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/github.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/history.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/job_demo.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/lineage.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/mcp_server.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/measures.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/models.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/notify.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/policy.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/policy_templates.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/py.typed +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/report.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/src/bricksentry/validation.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/README.md +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/conftest.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0110.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0112.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0114.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0120.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0121.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0122.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0123.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0126.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0127.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0128.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_0129.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_018.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_019.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_assess_policy.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_check_notebook.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_databricks_and_uc.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_demo.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_diff.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_hr_notebook.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_notebook.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_notify_templates.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_preview_agents.py +0 -0
- {bricksentry-0.1.29 → bricksentry-0.1.31}/tests/test_sample_guard_and_store.py +0 -0
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.31 (2026-11-22)
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
- **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`.
|
|
8
|
+
- **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.
|
|
9
|
+
- **`{{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.
|
|
10
|
+
- **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.
|
|
11
|
+
- **The outbound-URL guard blocks carrier-grade NAT addresses** (100.64.0.0/10), used inside some cloud networks.
|
|
12
|
+
- **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.
|
|
13
|
+
- When bricksentry creates the scratch schema because it didn't exist, it says so (and `preview_write` returns `created_schema`).
|
|
14
|
+
- 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.
|
|
15
|
+
|
|
16
|
+
## 0.1.30 (2026-11-18)
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
- **`CREATE OR REPLACE TABLE` previews work on serverless.** The preview replaced the shallow clone itself, which serverless refuses (`CLUSTER BY AUTO is only supported on UC Managed tables`, because new tables get automatic clustering by default). The statement's result now goes into a fresh sandbox table, the clone stays for reading the target (`CREATE OR REPLACE TABLE t AS SELECT ... FROM t`), and both are dropped afterwards. Other writes still run on the clone. Found while an assistant built and changed an HR pipeline with bricksentry as its gate.
|
|
21
|
+
- Agent errors keep quoted text that has no letters or digits, such as Delta's list of characters a column name can't contain (` ,;{}()\n\t=`), so an agent can see it needs a column alias. Quoted values are still hidden.
|
|
22
|
+
|
|
3
23
|
## 0.1.29 (2026-11-17)
|
|
4
24
|
|
|
5
25
|
Closes the last known way around `agent_tables`, and bricksentry enters public beta. Verified on Databricks before release: every view and function attack refused (a view over a forbidden table, a view over that view, a function with and without a schema, a view as candidate), legitimate views, functions, MERGE, UPDATE and INSERT previews ran with exact counts, and the 15-scenario 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.31
|
|
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
|
|
@@ -46,15 +46,22 @@ Provides-Extra: mcp
|
|
|
46
46
|
Requires-Dist: mcp>=1.10; extra == 'mcp'
|
|
47
47
|
Description-Content-Type: text/markdown
|
|
48
48
|
|
|
49
|
-
#
|
|
49
|
+
# bricksentry
|
|
50
50
|
|
|
51
51
|
<!-- mcp-name: io.github.bricksentry/bricksentry -->
|
|
52
52
|
|
|
53
53
|
[](https://pypi.org/project/bricksentry/) [](https://pypi.org/project/bricksentry/) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](LICENSE) [](#project-status-public-beta)
|
|
54
54
|
|
|
55
|
-
***
|
|
55
|
+
***See what a data change does before it ships.***
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
A pipeline change or an AI agent's MERGE can look right, pass every test and still quietly duplicate or drop rows. bricksentry checks the data itself before the change reaches production: it compares the rows the change would produce with what's there now, shows what's downstream in Unity Catalog lineage, and gives a verdict from your own policy: **pass**, **needs a human**, or **block**.
|
|
58
|
+
|
|
59
|
+
- **Real data, not a guess.** Agent previews run the statement on a disposable shallow clone; PR checks compare the tables your branch built. Rows added, removed and changed, column by column, exact to the row.
|
|
60
|
+
- **Fails closed.** If something can't be verified (a failed diff, a masked column, a table rewritten mid-check), it asks a human. It never treats "couldn't check" as a pass.
|
|
61
|
+
- **Agents see counts, never values,** and only for the tables you allow, including tables reached through views and SQL functions.
|
|
62
|
+
- **Fits how you work:** a GitHub PR check, a Databricks job task, a CLI, Python, or an MCP server for AI agents (with token auth over the network). Rollback plans come with every verdict.
|
|
63
|
+
|
|
64
|
+
*Public beta: tested in [ten adversarial rounds](VALIDATION.md), with every finding fixed and published.*
|
|
58
65
|
|
|
59
66
|
**[Try it in 30 seconds](#1-try-it-in-30-seconds-on-your-laptop)** · **[Check every change on Databricks](#2-check-every-change-to-your-tables-on-databricks)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[Validated live: what we tested and found](VALIDATION.md)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
|
|
60
67
|
|
|
@@ -196,7 +203,7 @@ bricksentry is listed in the [official MCP Registry](https://registry.modelconte
|
|
|
196
203
|
Designed for agents:
|
|
197
204
|
|
|
198
205
|
- **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
|
|
199
|
-
- **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. 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.
|
|
200
207
|
- **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
|
|
201
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.
|
|
202
209
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
@@ -250,8 +257,11 @@ bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updat
|
|
|
250
257
|
bricksentry assess --from-git origin/main --pr 42 --format markdown --fail-on needs_human
|
|
251
258
|
bricksentry rollback main.sales.orders
|
|
252
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
|
|
253
261
|
```
|
|
254
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
|
+
|
|
255
265
|
Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration errors.
|
|
256
266
|
|
|
257
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:
|
|
@@ -360,6 +370,8 @@ print(a.tables[0].summary)
|
|
|
360
370
|
s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sales.orders")
|
|
361
371
|
```
|
|
362
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
|
+
|
|
363
375
|
## Configuration
|
|
364
376
|
|
|
365
377
|
```yaml
|
|
@@ -502,7 +514,19 @@ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by i
|
|
|
502
514
|
|
|
503
515
|
**What may still change before 1.0:** default policy rules, the wording of reasons and summaries, fields added to JSON output (fields aren't removed or renamed without a changelog note), and defaults such as whether `agent_tables` is required for agents.
|
|
504
516
|
|
|
505
|
-
**1.0
|
|
517
|
+
**Before 1.0**, these need proving in environments other than the author's:
|
|
518
|
+
|
|
519
|
+
| What | How it gets checked |
|
|
520
|
+
|---|---|
|
|
521
|
+
| Separate identities: an agent identity that isn't bricksentry's, and people exempt from column masks | A team with service principals runs the validation notebook under a second identity |
|
|
522
|
+
| Classic compute (clusters and classic SQL warehouses), including its query-plan format | A validation report from classic compute |
|
|
523
|
+
| AWS, Azure and GCP workspaces | Validation reports from at least two clouds |
|
|
524
|
+
| The added time of the query-plan check on each agent preview, with several agents at once | Measured live |
|
|
525
|
+
| Pull-request comments and `--from-git` on the current code | Re-run on a real repository |
|
|
526
|
+
| The MCP server over weeks: long runs and restarts | A team running it day to day |
|
|
527
|
+
| Count probing on listed tables (documented above) | Kept as documented, or an optional per-table limit if users ask for one |
|
|
528
|
+
|
|
529
|
+
**1.0** comes when those are done and two or three outside teams have run it on real pipelines for a month without a serious finding. If you'd like to be one of them, [open an issue](https://github.com/bricksentry/bricksentry/issues) or run the [validation notebook](examples/databricks/bricksentry_validation.py) and [share the report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml).
|
|
506
530
|
|
|
507
531
|
## Known limits (v0.1.x)
|
|
508
532
|
|
|
@@ -1,12 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bricksentry
|
|
2
2
|
|
|
3
3
|
<!-- mcp-name: io.github.bricksentry/bricksentry -->
|
|
4
4
|
|
|
5
5
|
[](https://pypi.org/project/bricksentry/) [](https://pypi.org/project/bricksentry/) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](LICENSE) [](#project-status-public-beta)
|
|
6
6
|
|
|
7
|
-
***
|
|
7
|
+
***See what a data change does before it ships.***
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
A pipeline change or an AI agent's MERGE can look right, pass every test and still quietly duplicate or drop rows. bricksentry checks the data itself before the change reaches production: it compares the rows the change would produce with what's there now, shows what's downstream in Unity Catalog lineage, and gives a verdict from your own policy: **pass**, **needs a human**, or **block**.
|
|
10
|
+
|
|
11
|
+
- **Real data, not a guess.** Agent previews run the statement on a disposable shallow clone; PR checks compare the tables your branch built. Rows added, removed and changed, column by column, exact to the row.
|
|
12
|
+
- **Fails closed.** If something can't be verified (a failed diff, a masked column, a table rewritten mid-check), it asks a human. It never treats "couldn't check" as a pass.
|
|
13
|
+
- **Agents see counts, never values,** and only for the tables you allow, including tables reached through views and SQL functions.
|
|
14
|
+
- **Fits how you work:** a GitHub PR check, a Databricks job task, a CLI, Python, or an MCP server for AI agents (with token auth over the network). Rollback plans come with every verdict.
|
|
15
|
+
|
|
16
|
+
*Public beta: tested in [ten adversarial rounds](VALIDATION.md), with every finding fixed and published.*
|
|
10
17
|
|
|
11
18
|
**[Try it in 30 seconds](#1-try-it-in-30-seconds-on-your-laptop)** · **[Check every change on Databricks](#2-check-every-change-to-your-tables-on-databricks)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[Validated live: what we tested and found](VALIDATION.md)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
|
|
12
19
|
|
|
@@ -148,7 +155,7 @@ bricksentry is listed in the [official MCP Registry](https://registry.modelconte
|
|
|
148
155
|
Designed for agents:
|
|
149
156
|
|
|
150
157
|
- **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
|
|
151
|
-
- **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. 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.
|
|
152
159
|
- **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
|
|
153
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.
|
|
154
161
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
@@ -202,8 +209,11 @@ bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updat
|
|
|
202
209
|
bricksentry assess --from-git origin/main --pr 42 --format markdown --fail-on needs_human
|
|
203
210
|
bricksentry rollback main.sales.orders
|
|
204
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
|
|
205
213
|
```
|
|
206
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
|
+
|
|
207
217
|
Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration errors.
|
|
208
218
|
|
|
209
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:
|
|
@@ -312,6 +322,8 @@ print(a.tables[0].summary)
|
|
|
312
322
|
s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sales.orders")
|
|
313
323
|
```
|
|
314
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
|
+
|
|
315
327
|
## Configuration
|
|
316
328
|
|
|
317
329
|
```yaml
|
|
@@ -454,7 +466,19 @@ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by i
|
|
|
454
466
|
|
|
455
467
|
**What may still change before 1.0:** default policy rules, the wording of reasons and summaries, fields added to JSON output (fields aren't removed or renamed without a changelog note), and defaults such as whether `agent_tables` is required for agents.
|
|
456
468
|
|
|
457
|
-
**1.0
|
|
469
|
+
**Before 1.0**, these need proving in environments other than the author's:
|
|
470
|
+
|
|
471
|
+
| What | How it gets checked |
|
|
472
|
+
|---|---|
|
|
473
|
+
| Separate identities: an agent identity that isn't bricksentry's, and people exempt from column masks | A team with service principals runs the validation notebook under a second identity |
|
|
474
|
+
| Classic compute (clusters and classic SQL warehouses), including its query-plan format | A validation report from classic compute |
|
|
475
|
+
| AWS, Azure and GCP workspaces | Validation reports from at least two clouds |
|
|
476
|
+
| The added time of the query-plan check on each agent preview, with several agents at once | Measured live |
|
|
477
|
+
| Pull-request comments and `--from-git` on the current code | Re-run on a real repository |
|
|
478
|
+
| The MCP server over weeks: long runs and restarts | A team running it day to day |
|
|
479
|
+
| Count probing on listed tables (documented above) | Kept as documented, or an optional per-table limit if users ask for one |
|
|
480
|
+
|
|
481
|
+
**1.0** comes when those are done and two or three outside teams have run it on real pipelines for a month without a serious finding. If you'd like to be one of them, [open an issue](https://github.com/bricksentry/bricksentry/issues) or run the [validation notebook](examples/databricks/bricksentry_validation.py) and [share the report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml).
|
|
458
482
|
|
|
459
483
|
## Known limits (v0.1.x)
|
|
460
484
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bricksentry[databricks,mcp]==0.1.31
|
|
@@ -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.31"
|
|
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.31",
|
|
12
12
|
"packages": [
|
|
13
13
|
{
|
|
14
14
|
"registryType": "pypi",
|
|
15
15
|
"identifier": "bricksentry-mcp",
|
|
16
|
-
"version": "0.1.
|
|
16
|
+
"version": "0.1.31",
|
|
17
17
|
"runtimeHint": "uvx",
|
|
18
18
|
"transport": {
|
|
19
19
|
"type": "stdio"
|
|
@@ -16,7 +16,7 @@ from bricksentry.explain import explain_columns, explain_diff, explain_impact
|
|
|
16
16
|
from bricksentry.lineage import LineageProvider, make_lineage
|
|
17
17
|
from bricksentry.models import Assessment, ImpactNode, TableAssessment, TableDiff, Verdict
|
|
18
18
|
from bricksentry.policy import ColumnContext, Policy
|
|
19
|
-
from bricksentry.preview import rewrite_for_preview, sandbox_name
|
|
19
|
+
from bricksentry.preview import rewrite_for_preview, sandbox_name, statement_head
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
class Sentry:
|
|
@@ -211,8 +211,7 @@ class Sentry:
|
|
|
211
211
|
clone = sandbox_name(self.config.sandbox_schema, target)
|
|
212
212
|
rewritten = rewrite_for_preview(sql, target, clone, self.backend.quote)
|
|
213
213
|
schema = ".".join(clone.split(".")[:-1])
|
|
214
|
-
|
|
215
|
-
self.backend.ensure_schema(schema)
|
|
214
|
+
created = bool(schema and self.backend.ensure_schema(schema))
|
|
216
215
|
try:
|
|
217
216
|
self.backend.clone(target, clone)
|
|
218
217
|
except Exception as e:
|
|
@@ -220,6 +219,18 @@ class Sentry:
|
|
|
220
219
|
f"Could not clone {target} to preview the write: {_first_line(e)}. Check the table name "
|
|
221
220
|
f"and that you can create tables in {schema or 'the sandbox schema'}."
|
|
222
221
|
) from None
|
|
222
|
+
# CREATE OR REPLACE TABLE writes its result into a fresh sandbox table rather than
|
|
223
|
+
# replacing the clone: some engines refuse to replace a shallow clone (serverless
|
|
224
|
+
# applies CLUSTER BY AUTO to new tables, which a clone can't take). The clone stays,
|
|
225
|
+
# for statements that read the target (CREATE OR REPLACE TABLE t AS SELECT ... FROM t).
|
|
226
|
+
result = clone
|
|
227
|
+
head = statement_head(rewritten)
|
|
228
|
+
lead = len(rewritten) - len(head)
|
|
229
|
+
m = _REPLACE_HEAD.match(head)
|
|
230
|
+
if m:
|
|
231
|
+
result = clone + "_out"
|
|
232
|
+
rewritten = rewritten[: lead + m.start("name")] + ".".join(
|
|
233
|
+
self.backend.quote(p) for p in result.split(".")) + rewritten[lead + m.end("name"):]
|
|
223
234
|
try:
|
|
224
235
|
try:
|
|
225
236
|
self.backend.execute(rewritten)
|
|
@@ -227,13 +238,20 @@ class Sentry:
|
|
|
227
238
|
raise RuntimeError(
|
|
228
239
|
f"The statement failed on the preview clone, so production was not touched: {_first_line(e)}"
|
|
229
240
|
) from None
|
|
230
|
-
diff = self.diff(target,
|
|
241
|
+
diff = self.diff(target, result, keys=keys, table=target)
|
|
231
242
|
assessment = self.assess([target], diffs={target: diff})
|
|
232
243
|
finally:
|
|
233
244
|
if not keep:
|
|
234
245
|
self.backend.drop(clone)
|
|
246
|
+
if result != clone:
|
|
247
|
+
try:
|
|
248
|
+
self.backend.drop(result)
|
|
249
|
+
except Exception:
|
|
250
|
+
pass
|
|
235
251
|
out = assessment.to_dict()
|
|
236
|
-
out["preview"] = {"sandbox_table":
|
|
252
|
+
out["preview"] = {"sandbox_table": result if keep else None, "executed_sql": rewritten}
|
|
253
|
+
if created:
|
|
254
|
+
out["preview"]["created_schema"] = schema
|
|
237
255
|
return out
|
|
238
256
|
|
|
239
257
|
# --- alerts ---------------------------------------------------------------
|
|
@@ -309,6 +327,13 @@ def changed_columns(diff: TableDiff | None) -> list[str]:
|
|
|
309
327
|
return list(dict.fromkeys(out))
|
|
310
328
|
|
|
311
329
|
|
|
330
|
+
_REPLACE_HEAD = re.compile(
|
|
331
|
+
r"^\s*(?:CREATE\s+OR\s+REPLACE\s+TABLE|REPLACE\s+TABLE)\s+(?P<name>(?:`[^`]+`|\"[^\"]+\"|[\w\-]+)"
|
|
332
|
+
r"(?:\.(?:`[^`]+`|\"[^\"]+\"|[\w\-]+))*)",
|
|
333
|
+
re.IGNORECASE,
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
312
337
|
def _first_line(e: BaseException) -> str:
|
|
313
338
|
"""The useful part of an engine error: its first line, trimmed."""
|
|
314
339
|
text = str(e).strip()
|
|
@@ -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
|
|
@@ -448,6 +448,55 @@ def _run(cmd: click.Command, prog_name: str | None = None) -> None:
|
|
|
448
448
|
sys.exit(2)
|
|
449
449
|
|
|
450
450
|
|
|
451
|
+
@main.command()
|
|
452
|
+
@click.option("--scratch-schema", "schema", default=None,
|
|
453
|
+
help="catalog.schema to clean. Defaults to sandbox_schema in bricksentry.yml. Repeat the command "
|
|
454
|
+
"for the job's --scratch-schema if that is a different schema.")
|
|
455
|
+
@click.option("--older-than-hours", type=float, default=6.0, show_default=True,
|
|
456
|
+
help="Only drop clones at least this old, so a run that is still going keeps its clones. "
|
|
457
|
+
"0 drops every bricksentry clone, including ones whose age can't be read.")
|
|
458
|
+
@click.option("--yes", "-y", is_flag=True, help="Drop without asking.")
|
|
459
|
+
@config_opt
|
|
460
|
+
def cleanup(schema, older_than_hours, yes, config_path):
|
|
461
|
+
"""Drop clones left behind by runs that were killed outright.
|
|
462
|
+
|
|
463
|
+
Only tables named like bricksentry's own clones are matched (TABLE__preview_xxxxxxxx and
|
|
464
|
+
bs_check_TABLE_vN_xxxxxxxx). It lists them and asks before dropping anything.
|
|
465
|
+
"""
|
|
466
|
+
from bricksentry.cleanup import drop_leftovers, find_leftovers
|
|
467
|
+
|
|
468
|
+
s = _sentry(config_path)
|
|
469
|
+
schema = schema or s.config.sandbox_schema
|
|
470
|
+
drop, skip = find_leftovers(s.backend, schema, older_than_hours)
|
|
471
|
+
if skip:
|
|
472
|
+
click.echo(f"Keeping {len(skip)} recent clone(s) (younger than {older_than_hours:g}h, or age unknown; "
|
|
473
|
+
"use --older-than-hours 0 to include them):")
|
|
474
|
+
for t in skip:
|
|
475
|
+
click.echo(f" {t}")
|
|
476
|
+
if not drop:
|
|
477
|
+
click.echo(f"No leftover bricksentry clones to drop in {schema}.")
|
|
478
|
+
return
|
|
479
|
+
click.echo(f"Leftover bricksentry clone(s) in {schema}:")
|
|
480
|
+
for t in drop:
|
|
481
|
+
click.echo(f" {t}")
|
|
482
|
+
if not yes:
|
|
483
|
+
if not sys.stdin.isatty():
|
|
484
|
+
click.echo("Nothing dropped. Re-run with --yes to drop them.", err=True)
|
|
485
|
+
return
|
|
486
|
+
if not click.confirm(f"Drop these {len(drop)} table(s)?", default=False):
|
|
487
|
+
click.echo("Nothing dropped.")
|
|
488
|
+
return
|
|
489
|
+
failed = 0
|
|
490
|
+
for t, err in drop_leftovers(s.backend, drop):
|
|
491
|
+
if err:
|
|
492
|
+
failed += 1
|
|
493
|
+
click.echo(f" could not drop {t}: {err}", err=True)
|
|
494
|
+
else:
|
|
495
|
+
click.echo(f" dropped {t}")
|
|
496
|
+
if failed:
|
|
497
|
+
sys.exit(2)
|
|
498
|
+
|
|
499
|
+
|
|
451
500
|
def entry() -> None:
|
|
452
501
|
"""Console entry point: turn unexpected errors into a clean message and exit code 2."""
|
|
453
502
|
_run(main)
|
|
@@ -134,4 +134,10 @@ def redact_values(text: str) -> str:
|
|
|
134
134
|
or DuckDB's ``Casting value "1975308.64"``: engines quote data values in single or
|
|
135
135
|
double quotes. Backticked names stay. Some type names in double quotes go too.
|
|
136
136
|
Apostrophes inside words ("can't") aren't quotes and stay."""
|
|
137
|
-
|
|
137
|
+
def hide(m: re.Match) -> str:
|
|
138
|
+
inner = re.sub(r"\\[ntr]", " ", m.group(0)[1:-1]) # escapes like \n count as punctuation
|
|
139
|
+
# Punctuation and whitespace only (e.g. Delta's list of characters a column name
|
|
140
|
+
# can't contain) isn't data and tells the agent how to fix the statement.
|
|
141
|
+
return m.group(0) if inner and not any(ch.isalnum() for ch in inner) else "'…'"
|
|
142
|
+
|
|
143
|
+
return _QUOTED.sub(hide, text)
|
|
@@ -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 "
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
The URLs come from your own config or CI environment, but a mistyped or malicious value could
|
|
4
4
|
still point at an internal service. So outbound requests must use https, must not target
|
|
5
|
-
loopback, private, link-local or other non-public addresses, and never follow redirects.
|
|
5
|
+
loopback, private, link-local, carrier-grade NAT (100.64.0.0/10) or other non-public addresses, and never follow redirects.
|
|
6
6
|
|
|
7
7
|
Set ``BRICKSENTRY_ALLOW_PRIVATE_URLS=1`` when a legitimate target is on a private network
|
|
8
8
|
(for example GitHub Enterprise Server or a webhook relay inside your VPC).
|
|
@@ -17,6 +17,7 @@ import urllib.request
|
|
|
17
17
|
from urllib.parse import urlsplit
|
|
18
18
|
|
|
19
19
|
ALLOW_PRIVATE_ENV = "BRICKSENTRY_ALLOW_PRIVATE_URLS"
|
|
20
|
+
_SHARED_V4 = ipaddress.ip_network("100.64.0.0/10")
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class UnsafeURLError(ValueError):
|
|
@@ -31,8 +32,10 @@ def _is_public(ip: str) -> bool:
|
|
|
31
32
|
addr = ipaddress.ip_address(ip.split("%", 1)[0])
|
|
32
33
|
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped:
|
|
33
34
|
addr = addr.ipv4_mapped
|
|
35
|
+
if addr.version == 4 and addr in _SHARED_V4: # carrier-grade NAT, used inside some cloud networks
|
|
36
|
+
return False
|
|
34
37
|
return not (addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved
|
|
35
|
-
or addr.is_multicast or addr.is_unspecified)
|
|
38
|
+
or addr.is_multicast or addr.is_unspecified) and addr.is_global
|
|
36
39
|
|
|
37
40
|
|
|
38
41
|
def check_url(url: str, what: str = "URL") -> None:
|