bricksentry 0.1.30__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.
Files changed (99) hide show
  1. {bricksentry-0.1.30 → bricksentry-0.1.31}/CHANGELOG.md +13 -0
  2. {bricksentry-0.1.30 → bricksentry-0.1.31}/PKG-INFO +7 -2
  3. {bricksentry-0.1.30 → bricksentry-0.1.31}/README.md +6 -1
  4. bricksentry-0.1.31/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.30 → bricksentry-0.1.31}/pyproject.toml +1 -1
  6. {bricksentry-0.1.30 → bricksentry-0.1.31}/server.json +2 -2
  7. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/__init__.py +1 -1
  8. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/assess.py +9 -6
  9. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/backends/base.py +36 -1
  10. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/backends/databricks_backend.py +19 -0
  11. bricksentry-0.1.31/src/bricksentry/cleanup.py +78 -0
  12. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/cli.py +49 -0
  13. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/job.py +30 -4
  14. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/netguard.py +5 -2
  15. bricksentry-0.1.31/src/bricksentry/preview.py +206 -0
  16. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/databricks_template_schema.json +2 -2
  17. bricksentry-0.1.31/tests/test_0131.py +192 -0
  18. bricksentry-0.1.30/deploy/databricks-app/requirements.txt +0 -1
  19. bricksentry-0.1.30/src/bricksentry/preview.py +0 -105
  20. {bricksentry-0.1.30 → bricksentry-0.1.31}/.gitignore +0 -0
  21. {bricksentry-0.1.30 → bricksentry-0.1.31}/CONTRIBUTING.md +0 -0
  22. {bricksentry-0.1.30 → bricksentry-0.1.31}/LICENSE +0 -0
  23. {bricksentry-0.1.30 → bricksentry-0.1.31}/SECURITY.md +0 -0
  24. {bricksentry-0.1.30 → bricksentry-0.1.31}/action.yml +0 -0
  25. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/container/Dockerfile +0 -0
  26. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/databricks-app/README.md +0 -0
  27. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/databricks-app/app.yaml +0 -0
  28. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/databricks-app/bricksentry.yml +0 -0
  29. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/databricks-app/databricks.yml +0 -0
  30. {bricksentry-0.1.30 → bricksentry-0.1.31}/deploy/databricks-app/grants.sql +0 -0
  31. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry.yml +0 -0
  32. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  33. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_check_my_table.py +0 -0
  34. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  35. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  36. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  37. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_quickstart.py +0 -0
  38. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_validation.ipynb +0 -0
  39. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/bricksentry_validation.py +0 -0
  40. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/github-workflow.yml +0 -0
  41. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/databricks/policy.yml +0 -0
  42. {bricksentry-0.1.30 → bricksentry-0.1.31}/examples/demo/agent_loop_demo.py +0 -0
  43. {bricksentry-0.1.30 → bricksentry-0.1.31}/scripts/build_notebook.py +0 -0
  44. {bricksentry-0.1.30 → bricksentry-0.1.31}/scripts/render_demo_image.py +0 -0
  45. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/__main__.py +0 -0
  46. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/agent_tools.py +0 -0
  47. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/agent_view.py +0 -0
  48. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/backends/__init__.py +0 -0
  49. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/backends/duckdb_backend.py +0 -0
  50. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/changes.py +0 -0
  51. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/config.py +0 -0
  52. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/demo.py +0 -0
  53. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/diff.py +0 -0
  54. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/explain.py +0 -0
  55. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/github.py +0 -0
  56. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/history.py +0 -0
  57. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/job_demo.py +0 -0
  58. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/lineage.py +0 -0
  59. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/mcp_server.py +0 -0
  60. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/measures.py +0 -0
  61. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/models.py +0 -0
  62. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/notify.py +0 -0
  63. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/policy.py +0 -0
  64. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/policy_templates.py +0 -0
  65. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/py.typed +0 -0
  66. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/report.py +0 -0
  67. {bricksentry-0.1.30 → bricksentry-0.1.31}/src/bricksentry/validation.py +0 -0
  68. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/README.md +0 -0
  69. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  70. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  71. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  72. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  73. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  74. {bricksentry-0.1.30 → bricksentry-0.1.31}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  75. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/conftest.py +0 -0
  76. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0110.py +0 -0
  77. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0112.py +0 -0
  78. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0114.py +0 -0
  79. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0120.py +0 -0
  80. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0121.py +0 -0
  81. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0122.py +0 -0
  82. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0123.py +0 -0
  83. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0126.py +0 -0
  84. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0127.py +0 -0
  85. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0128.py +0 -0
  86. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0129.py +0 -0
  87. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_0130.py +0 -0
  88. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_018.py +0 -0
  89. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_019.py +0 -0
  90. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_assess_policy.py +0 -0
  91. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_check_notebook.py +0 -0
  92. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_databricks_and_uc.py +0 -0
  93. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_demo.py +0 -0
  94. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_diff.py +0 -0
  95. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_hr_notebook.py +0 -0
  96. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_notebook.py +0 -0
  97. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_notify_templates.py +0 -0
  98. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_preview_agents.py +0 -0
  99. {bricksentry-0.1.30 → bricksentry-0.1.31}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,18 @@
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
+
3
16
  ## 0.1.30 (2026-11-18)
4
17
 
5
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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.30
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
@@ -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. 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
@@ -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. 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
@@ -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.30"
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.30",
11
+ "version": "0.1.31",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.30",
16
+ "version": "0.1.31",
17
17
  "runtimeHint": "uvx",
18
18
  "transport": {
19
19
  "type": "stdio"
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.30"
26
+ __version__ = "0.1.31"
@@ -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
- if schema:
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:
@@ -225,11 +224,13 @@ class Sentry:
225
224
  # applies CLUSTER BY AUTO to new tables, which a clone can't take). The clone stays,
226
225
  # for statements that read the target (CREATE OR REPLACE TABLE t AS SELECT ... FROM t).
227
226
  result = clone
228
- m = _REPLACE_HEAD.match(rewritten)
227
+ head = statement_head(rewritten)
228
+ lead = len(rewritten) - len(head)
229
+ m = _REPLACE_HEAD.match(head)
229
230
  if m:
230
231
  result = clone + "_out"
231
- rewritten = rewritten[: m.start("name")] + ".".join(
232
- self.backend.quote(p) for p in result.split(".")) + rewritten[m.end("name"):]
232
+ rewritten = rewritten[: lead + m.start("name")] + ".".join(
233
+ self.backend.quote(p) for p in result.split(".")) + rewritten[lead + m.end("name"):]
233
234
  try:
234
235
  try:
235
236
  self.backend.execute(rewritten)
@@ -249,6 +250,8 @@ class Sentry:
249
250
  pass
250
251
  out = assessment.to_dict()
251
252
  out["preview"] = {"sandbox_table": result if keep else None, "executed_sql": rewritten}
253
+ if created:
254
+ out["preview"]["created_schema"] = schema
252
255
  return out
253
256
 
254
257
  # --- 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 ensure_schema(self, schema: str) -> None:
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)
@@ -97,7 +97,26 @@ def build_parser() -> argparse.ArgumentParser:
97
97
  return p
98
98
 
99
99
 
100
- def make_sentry(args: argparse.Namespace, backend: Any = None):
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, teams = read_secret(args.slack_secret), read_secret(args.teams_secret)
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
- s = make_sentry(args, backend=backend)
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: