bricksentry 0.1.25__tar.gz → 0.1.26__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 (91) hide show
  1. {bricksentry-0.1.25 → bricksentry-0.1.26}/CHANGELOG.md +14 -0
  2. {bricksentry-0.1.25 → bricksentry-0.1.26}/PKG-INFO +4 -2
  3. {bricksentry-0.1.25 → bricksentry-0.1.26}/README.md +3 -1
  4. bricksentry-0.1.26/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_validation.ipynb +1 -1
  6. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_validation.py +1 -1
  7. {bricksentry-0.1.25 → bricksentry-0.1.26}/pyproject.toml +1 -1
  8. {bricksentry-0.1.25 → bricksentry-0.1.26}/server.json +2 -2
  9. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/__init__.py +1 -1
  10. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/agent_tools.py +17 -2
  11. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/assess.py +20 -2
  12. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/backends/base.py +17 -2
  13. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/config.py +13 -1
  14. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/diff.py +64 -16
  15. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/explain.py +5 -3
  16. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/history.py +39 -3
  17. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/models.py +7 -0
  18. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/policy.py +46 -14
  19. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/validation.py +26 -0
  20. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/databricks_template_schema.json +2 -2
  21. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0123.py +2 -2
  22. bricksentry-0.1.26/tests/test_0126.py +173 -0
  23. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_assess_policy.py +3 -4
  24. bricksentry-0.1.25/deploy/databricks-app/requirements.txt +0 -1
  25. {bricksentry-0.1.25 → bricksentry-0.1.26}/.gitignore +0 -0
  26. {bricksentry-0.1.25 → bricksentry-0.1.26}/CONTRIBUTING.md +0 -0
  27. {bricksentry-0.1.25 → bricksentry-0.1.26}/LICENSE +0 -0
  28. {bricksentry-0.1.25 → bricksentry-0.1.26}/SECURITY.md +0 -0
  29. {bricksentry-0.1.25 → bricksentry-0.1.26}/action.yml +0 -0
  30. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/container/Dockerfile +0 -0
  31. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/databricks-app/README.md +0 -0
  32. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/databricks-app/app.yaml +0 -0
  33. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/databricks-app/bricksentry.yml +0 -0
  34. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/databricks-app/databricks.yml +0 -0
  35. {bricksentry-0.1.25 → bricksentry-0.1.26}/deploy/databricks-app/grants.sql +0 -0
  36. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry.yml +0 -0
  37. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  38. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_check_my_table.py +0 -0
  39. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  40. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  41. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  42. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/bricksentry_quickstart.py +0 -0
  43. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/github-workflow.yml +0 -0
  44. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/databricks/policy.yml +0 -0
  45. {bricksentry-0.1.25 → bricksentry-0.1.26}/examples/demo/agent_loop_demo.py +0 -0
  46. {bricksentry-0.1.25 → bricksentry-0.1.26}/scripts/build_notebook.py +0 -0
  47. {bricksentry-0.1.25 → bricksentry-0.1.26}/scripts/render_demo_image.py +0 -0
  48. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/__main__.py +0 -0
  49. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/backends/__init__.py +0 -0
  50. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/backends/databricks_backend.py +0 -0
  51. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/backends/duckdb_backend.py +0 -0
  52. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/changes.py +0 -0
  53. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/cli.py +0 -0
  54. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/demo.py +0 -0
  55. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/github.py +0 -0
  56. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/job.py +0 -0
  57. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/job_demo.py +0 -0
  58. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/lineage.py +0 -0
  59. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/mcp_server.py +0 -0
  60. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/measures.py +0 -0
  61. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/netguard.py +0 -0
  62. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/notify.py +0 -0
  63. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/policy_templates.py +0 -0
  64. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/preview.py +0 -0
  65. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/py.typed +0 -0
  66. {bricksentry-0.1.25 → bricksentry-0.1.26}/src/bricksentry/report.py +0 -0
  67. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/README.md +0 -0
  68. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  69. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  70. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  71. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  72. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  73. {bricksentry-0.1.25 → bricksentry-0.1.26}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  74. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/conftest.py +0 -0
  75. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0110.py +0 -0
  76. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0112.py +0 -0
  77. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0114.py +0 -0
  78. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0120.py +0 -0
  79. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0121.py +0 -0
  80. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_0122.py +0 -0
  81. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_018.py +0 -0
  82. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_019.py +0 -0
  83. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_check_notebook.py +0 -0
  84. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_databricks_and_uc.py +0 -0
  85. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_demo.py +0 -0
  86. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_diff.py +0 -0
  87. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_hr_notebook.py +0 -0
  88. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_notebook.py +0 -0
  89. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_notify_templates.py +0 -0
  90. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_preview_agents.py +0 -0
  91. {bricksentry-0.1.25 → bricksentry-0.1.26}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.26 (2026-11-17)
4
+
5
+ Fixes for what two worst-case live tests of 0.1.25 on Databricks found. A pre-release check passed on two Databricks Free Edition workspaces (47 of 47 on the first), including the 12-scenario validation battery and before/after repros of every fix.
6
+
7
+ - **A changed copy of a duplicated key no longer shifts how the other copies pair.** 0.1.23 numbered the copies of a key by row hash and matched copy *n* with copy *n*, so one changed copy could move every copy after it: 2,000 rows sharing a NULL key with 2 real changes reported over a thousand changed rows (50,000 such rows: 36,563). Identical copies are now matched first; only the copies left over are paired. The same test now reports exactly 2 changed. New validation scenario `null_keys_changed`.
8
+ - **A total moving away from zero now fires `sum_change_pct_gt`.** A column whose total went from 0 to 5 had no percentage change, so the rule never matched. It now matches, with the reason "sum(col) 0 -> 5", and the plain-English explanation lists it under totals.
9
+ - **An overflowing exact total no longer loses the whole diff.** If a `DECIMAL(38)` total overflows, totals fall back to `DOUBLE` (or are skipped), the row counts and changes are still reported, and the diff notes it.
10
+ - **The rollback warning lists newer table changes that aren't data** (renamed columns, table properties, constraints): `RESTORE` undoes those too. Maintenance (OPTIMIZE, VACUUM, ANALYZE) is still ignored.
11
+ - **Clearer policy mistakes.** A verdict typo (`then: blok`) names the valid verdicts; verdicts are accepted in any case; `policy: strict` without `builtin:` says to write `builtin:strict`; a policy with no rules warns that every change will pass.
12
+ - **Behavior change: no-op pull requests to pii and certified-fed tables now pass.** The default rules `pii-table` and `certified-downstream` now have `any_change: true`, like `dashboard-downstream`: they fire on any added, removed or changed row, any schema change or new duplicate keys, but not when the candidate is identical to production (before, that got `needs_human` with nothing to review). A failed or missing diff still counts as a change, for every `any_change` rule. To require a review regardless, add a custom rule such as `{name: pii-review, when: {tag: pii}, then: needs_human}`. New validation scenario `pii_noop` (identical rebuild: pass; 1-row edit: needs_human). Found in a live test of 0.1.25.
13
+ - `preview_write` / `bricksentry preview` show one line when the clone or the statement fails ("The statement failed on the preview clone, so production was not touched: …") instead of the engine's full error. MCP tool errors keep only the first line.
14
+ - The MCP tools `whats_downstream` and `rollback_plan` report a mistyped or missing table as "Table … not found" instead of an empty downstream list (which read as "nothing is downstream") or advice to take a snapshot. Found in the pre-release check.
15
+ - A misspelled key under `backend:` in `bricksentry.yml` (say `path:` instead of `database:`) is rejected with the valid keys, instead of being ignored and connecting somewhere else. Found in the pre-release check.
16
+
3
17
  ## 0.1.25 (2026-11-16)
4
18
 
5
19
  - **Validation you can reproduce.** `VALIDATION.md` records every live test on Databricks with its numbers, the results that weren't perfect and the bugs each test found. `bricksentry.validation.run_validation()` and the new notebook `examples/databricks/bricksentry_validation.py` run the same ten risky changes on your own workspace in a scratch schema and drop everything afterwards. A new issue form, "Validation report", collects results from other setups.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.25
3
+ Version: 0.1.26
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
@@ -428,6 +428,8 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
428
428
 
429
429
  `table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `changed_column` (glob) · `changed_column_tag` · `downstream_column_tag` · `any_change` · `diff_error` · `lineage_error`
430
430
 
431
+ **The pii and certified gates skip changes that change nothing.** In the default policy, `pii-table` (the table is tagged `pii`) and `certified-downstream` (it feeds something tagged `certified`) fire only when the diff shows a change: rows added, removed or changed, a schema change or new duplicate keys. A rebuild identical to production passes. A failed or missing diff still counts as a possible change. To require a review of every pull request touching a PII table regardless, add a rule without `any_change`: `{name: pii-review, when: {tag: pii}, then: needs_human}`.
432
+
431
433
  **Column conditions** look only at the columns the change touched (changed values, new NULLs, dropped or retyped): `changed_column_tag: pii` matches when one of them is tagged `pii` in Unity Catalog, and `downstream_column_tag: certified` when one of them feeds a column tagged `certified`, following `system.access.column_lineage` up to `lineage.column_depth` hops (default 2; `0` turns it off). The default policy asks a human when a `pii` column changes; `strict`, `agent-safe` and `certified` also flag changes that feed certified columns.
432
434
 
433
435
  All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
@@ -461,7 +463,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
461
463
  - **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.
462
464
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
463
465
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
464
- - **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.23 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, one-to-one 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, and the job task blocking a bad MERGE inside a real Databricks job. 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.
466
+ - **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.26 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, one-to-one 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. 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.
465
467
 
466
468
  ## Roadmap
467
469
 
@@ -381,6 +381,8 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
381
381
 
382
382
  `table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `changed_column` (glob) · `changed_column_tag` · `downstream_column_tag` · `any_change` · `diff_error` · `lineage_error`
383
383
 
384
+ **The pii and certified gates skip changes that change nothing.** In the default policy, `pii-table` (the table is tagged `pii`) and `certified-downstream` (it feeds something tagged `certified`) fire only when the diff shows a change: rows added, removed or changed, a schema change or new duplicate keys. A rebuild identical to production passes. A failed or missing diff still counts as a possible change. To require a review of every pull request touching a PII table regardless, add a rule without `any_change`: `{name: pii-review, when: {tag: pii}, then: needs_human}`.
385
+
384
386
  **Column conditions** look only at the columns the change touched (changed values, new NULLs, dropped or retyped): `changed_column_tag: pii` matches when one of them is tagged `pii` in Unity Catalog, and `downstream_column_tag: certified` when one of them feeds a column tagged `certified`, following `system.access.column_lineage` up to `lineage.column_depth` hops (default 2; `0` turns it off). The default policy asks a human when a `pii` column changes; `strict`, `agent-safe` and `certified` also flag changes that feed certified columns.
385
387
 
386
388
  All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
@@ -414,7 +416,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
414
416
  - **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.
415
417
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
416
418
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
417
- - **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.23 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, one-to-one 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, and the job task blocking a bad MERGE inside a real Databricks job. 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.
419
+ - **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.26 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, one-to-one 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. 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.
418
420
 
419
421
  ## Roadmap
420
422
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.26
@@ -6,7 +6,7 @@
6
6
  "source": [
7
7
  "# Validate bricksentry on your own workspace\n",
8
8
  "\n",
9
- "**10 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
9
+ "**12 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
10
10
  "validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),\n",
11
11
  "so you can check the results yourself instead of taking our word for them.\n",
12
12
  "\n",
@@ -2,7 +2,7 @@
2
2
  # MAGIC %md
3
3
  # MAGIC # Validate bricksentry on your own workspace
4
4
  # MAGIC
5
- # MAGIC **10 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same
5
+ # MAGIC **12 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same
6
6
  # MAGIC validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),
7
7
  # MAGIC so you can check the results yourself instead of taking our word for them.
8
8
  # MAGIC
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.25"
7
+ version = "0.1.26"
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.25",
11
+ "version": "0.1.26",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.25",
16
+ "version": "0.1.26",
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.25"
26
+ __version__ = "0.1.26"
@@ -47,7 +47,11 @@ def _safe(fn):
47
47
  try:
48
48
  return fn(*args, **kwargs)
49
49
  except Exception as e:
50
- return {"error": f"{type(e).__name__}: {e}"}
50
+ text = str(e).strip()
51
+ line = text.splitlines()[0] if text else ""
52
+ if len(line) > 300:
53
+ line = line[:297] + "..."
54
+ return {"error": f"{type(e).__name__}: {line}"}
51
55
 
52
56
  return wrapper
53
57
 
@@ -79,6 +83,9 @@ def whats_downstream(
79
83
  s = get_sentry()
80
84
  nodes = s.downstream(table, depth)
81
85
  owner, tags = s.lineage.owner_and_tags(table)
86
+ if not nodes and not owner and not tags and not s.backend.table_exists(table):
87
+ # An empty answer for a mistyped name would read as "nothing is downstream".
88
+ raise LookupError(_not_found(table))
82
89
  out: dict[str, Any] = {
83
90
  "table": table,
84
91
  "owner": owner,
@@ -233,12 +240,20 @@ def rollback_plan(
233
240
  Returns {table, current_version, rollback_sql}, e.g. "RESTORE TABLE
234
241
  main.sales.orders TO VERSION AS OF 42", or {error}."""
235
242
  s = get_sentry()
243
+ version = s.backend.current_version(table)
244
+ if version is None and not s.backend.table_exists(table):
245
+ raise LookupError(_not_found(table))
236
246
  return {
237
247
  "table": table,
238
- "current_version": s.backend.current_version(table),
248
+ "current_version": version,
239
249
  "rollback_sql": s.rollback_plan(table),
240
250
  }
241
251
 
242
252
 
253
+ def _not_found(table: str) -> str:
254
+ return (f"Table {table} not found. Check the catalog, schema and table name (they must match "
255
+ "Unity Catalog exactly) and that you have SELECT on it.")
256
+
257
+
243
258
  TOOLS = [whats_downstream, assess_change, preview_write, explain_diff, safe_to_ship, rollback_plan]
244
259
  READ_ONLY = {"whats_downstream", "assess_change", "explain_diff", "safe_to_ship", "rollback_plan"}
@@ -212,9 +212,20 @@ class Sentry:
212
212
  schema = ".".join(clone.split(".")[:-1])
213
213
  if schema:
214
214
  self.backend.ensure_schema(schema)
215
- self.backend.clone(target, clone)
216
215
  try:
217
- self.backend.execute(rewritten)
216
+ self.backend.clone(target, clone)
217
+ except Exception as e:
218
+ raise RuntimeError(
219
+ f"Could not clone {target} to preview the write: {_first_line(e)}. Check the table name "
220
+ f"and that you can create tables in {schema or 'the sandbox schema'}."
221
+ ) from None
222
+ try:
223
+ try:
224
+ self.backend.execute(rewritten)
225
+ except Exception as e:
226
+ raise RuntimeError(
227
+ f"The statement failed on the preview clone, so production was not touched: {_first_line(e)}"
228
+ ) from None
218
229
  diff = self.diff(target, clone, keys=keys, table=target)
219
230
  assessment = self.assess([target], diffs={target: diff})
220
231
  finally:
@@ -295,3 +306,10 @@ def changed_columns(diff: TableDiff | None) -> list[str]:
295
306
  out.append(c.column)
296
307
  out += list(diff.schema.removed) + list(diff.schema.type_changed)
297
308
  return list(dict.fromkeys(out))
309
+
310
+
311
+ def _first_line(e: BaseException) -> str:
312
+ """The useful part of an engine error: its first line, trimmed."""
313
+ text = str(e).strip()
314
+ line = text.splitlines()[0] if text else type(e).__name__
315
+ return line if len(line) <= 300 else line[:297] + "..."
@@ -123,9 +123,24 @@ def make_backend(spec: dict[str, Any] | None) -> Backend:
123
123
  if kind == "duckdb":
124
124
  from bricksentry.backends.duckdb_backend import DuckDBBackend
125
125
 
126
- return DuckDBBackend(**spec)
126
+ return DuckDBBackend(**_known_keys(DuckDBBackend, kind, spec))
127
127
  if kind == "databricks":
128
128
  from bricksentry.backends.databricks_backend import DatabricksBackend
129
129
 
130
- return DatabricksBackend(**spec)
130
+ return DatabricksBackend(**_known_keys(DatabricksBackend, kind, spec))
131
131
  raise ValueError(f"Unknown backend type: {kind!r} (expected 'databricks' or 'duckdb')")
132
+
133
+
134
+
135
+ def _known_keys(cls: type, kind: str, spec: dict[str, Any]) -> dict[str, Any]:
136
+ """Reject misspelled `backend:` keys instead of silently ignoring them (a `path:`
137
+ meant as `database:` would quietly connect to an empty in-memory database)."""
138
+ import inspect
139
+
140
+ params = inspect.signature(cls.__init__).parameters
141
+ known = [n for n, p in params.items() if n != "self" and p.kind not in (p.VAR_KEYWORD, p.VAR_POSITIONAL)]
142
+ unknown = sorted(set(spec) - set(known))
143
+ if unknown:
144
+ raise ValueError(f"Unknown key(s) under backend: {', '.join(unknown)} for type {kind}. "
145
+ f"Valid keys: type, {', '.join(k for k in known if k != 'client' and k != 'connection')}.")
146
+ return spec
@@ -102,6 +102,18 @@ def _measures(v: Any) -> list[str] | str | None:
102
102
  return [str(x) for x in v]
103
103
 
104
104
 
105
+ def _load_policy_file(root: Path, name: str) -> dict[str, Any]:
106
+ path = root / name
107
+ if not path.exists():
108
+ from bricksentry.policy_templates import TEMPLATES
109
+
110
+ hint = ""
111
+ if name.strip().lower() in TEMPLATES:
112
+ hint = f" To use the built-in template, write `policy: builtin:{name.strip().lower()}`."
113
+ raise FileNotFoundError(f"Policy file {name!r} not found (looked for {path}).{hint}")
114
+ return yaml.safe_load(path.read_text()) or {}
115
+
116
+
105
117
  @dataclass
106
118
  class TableSpec:
107
119
  name: str
@@ -155,7 +167,7 @@ class Config:
155
167
 
156
168
  policy = get_template(policy.split(":", 1)[1])
157
169
  else:
158
- policy = yaml.safe_load((root / policy).read_text()) or {}
170
+ policy = _load_policy_file(root, policy)
159
171
  return cls(
160
172
  backend=data.get("backend") or {"type": "duckdb"},
161
173
  sandbox_schema=data.get("sandbox_schema", "bricksentry_sandbox"),
@@ -141,20 +141,47 @@ def _diff(
141
141
  notes: list[str] = []
142
142
  pair_copies = bool(dup_b or dup_c)
143
143
  if pair_copies:
144
- # Number the copies of each key and match copy n to copy n, so the join stays
145
- # one to one: an extra copy counts as added (or removed), not as a second match.
146
- # Ordering by a row hash pairs identical copies with each other.
147
- order = backend.row_hash([c for c in b_cols if c in c_cols and c not in schema.type_changed]) or kc
148
-
149
- def side(tbl: str, alias: str) -> str:
150
- return (f"{alias} AS (SELECT *, 1 AS {present}, ROW_NUMBER() OVER (PARTITION BY {kc} "
151
- f"ORDER BY {order}) AS {occ} FROM {backend.qualified(tbl)}{sample_where()})")
152
-
153
- ctes = f"WITH {side(base, 'b_src')}, {side(candidate, 'c_src')}"
154
144
  notes.append(
155
- "Some keys appear more than once, so copies of the same key were paired one to one "
156
- "(an extra copy counts as added or removed, not as another match)."
145
+ "Some keys appear more than once. Identical copies of a key were matched first, then the "
146
+ "remaining copies paired one to one (an extra copy counts as added or removed)."
157
147
  )
148
+ st = backend.string_type
149
+ hcols = [c for c in b_cols if c in c_cols and c not in schema.type_changed]
150
+ h = backend.row_hash(hcols) if hcols else None
151
+ if h is None: # no row hash: number the copies of each key in no particular order
152
+ def side(tbl: str, alias: str) -> str:
153
+ return (f"{alias} AS (SELECT *, 1 AS {present}, CAST(ROW_NUMBER() OVER (PARTITION BY {kc} "
154
+ f"ORDER BY {kc}) AS {st}) AS {occ} FROM {backend.qualified(tbl)}{sample_where()})")
155
+
156
+ ctes = f"WITH {side(base, 'b_src')}, {side(candidate, 'c_src')}"
157
+ else:
158
+ # Two steps, so one changed copy can't shift the pairing of the others:
159
+ # 1. identical copies match each other (same key, same row hash, numbered
160
+ # within that hash);
161
+ # 2. only the copies left over on each side are paired, by rank within the key.
162
+ hh, hn, hm = q("__bs_h"), q("__bs_hn"), q("__bs_m")
163
+
164
+ def hashed(tbl: str, alias: str) -> str:
165
+ return (f"{alias} AS (SELECT *, 1 AS {present}, {h} AS {hh}, ROW_NUMBER() OVER "
166
+ f"(PARTITION BY {kc}, {h} ORDER BY {kc}) AS {hn} FROM {backend.qualified(tbl)}{sample_where()})")
167
+
168
+ def marked(src: str, other: str, alias: str) -> str:
169
+ on = " AND ".join(f"o.{q(k)} IS NOT DISTINCT FROM s.{q(k)}" for k in keys)
170
+ return (f"{alias} AS (SELECT s.*, CASE WHEN o.{hh} IS NULL THEN 0 ELSE 1 END AS {hm} "
171
+ f"FROM {src} s LEFT JOIN (SELECT {kc}, {hh}, {hn} FROM {other}) o "
172
+ f"ON {on} AND o.{hh} = s.{hh} AND o.{hn} = s.{hn})")
173
+
174
+ def paired(src: str, alias: str) -> str:
175
+ return (f"{alias} AS (SELECT *, CASE WHEN {hm} = 1 "
176
+ f"THEN CONCAT('m', CAST({hh} AS {st}), '_', CAST({hn} AS {st})) "
177
+ f"ELSE CONCAT('u', CAST(ROW_NUMBER() OVER (PARTITION BY {kc}, {hm} ORDER BY {hh}) AS {st})) "
178
+ f"END AS {occ} FROM {src})")
179
+
180
+ ctes = ("WITH " + ", ".join([
181
+ hashed(base, "b_h"), hashed(candidate, "c_h"),
182
+ marked("b_h", "c_h", "b_m"), marked("c_h", "b_h", "c_m"),
183
+ paired("b_m", "b_src"), paired("c_m", "c_src"),
184
+ ]))
158
185
  else:
159
186
  ctes = raw_ctes
160
187
  # Null-safe key match: a NULL key in production matches a NULL key in the candidate.
@@ -189,17 +216,38 @@ def _diff(
189
216
  j = backend.query(join_sql)[0]
190
217
 
191
218
  # Row counts, nulls, numeric sums per side. Sums are exact for decimals and integers.
192
- def profile(tbl_cte: str, cols: dict[str, str]) -> dict:
219
+ def profile(tbl_cte: str, cols: dict[str, str], sums: str = "exact") -> dict:
193
220
  any_null_key = " OR ".join(f"{q(k)} IS NULL" for k in keys)
194
221
  parts = ["COUNT(*) AS n_rows", f"SUM(CASE WHEN {any_null_key} THEN 1 ELSE 0 END) AS null_keys"]
195
222
  for i, col in enumerate(common):
196
223
  parts.append(f"SUM(CASE WHEN {q(col)} IS NULL THEN 1 ELSE 0 END) AS nul_{i}")
197
224
  if backend.is_numeric(cols[col]):
198
- parts.append(f"{backend.exact_sum(q(col), cols[col])} AS sum_{i}")
225
+ if sums == "exact":
226
+ parts.append(f"{backend.exact_sum(q(col), cols[col])} AS sum_{i}")
227
+ elif sums == "double":
228
+ parts.append(f"SUM(CAST({q(col)} AS DOUBLE)) AS sum_{i}")
199
229
  return backend.query(f"{raw_ctes} SELECT {', '.join(parts)} FROM {tbl_cte}")[0]
200
230
 
201
- pb = profile("b_src", b_cols)
202
- pc = profile("c_src", c_cols)
231
+ def safe_profile(tbl_cte: str, cols: dict[str, str]) -> dict:
232
+ # An exact DECIMAL(38) total can overflow on huge values. Don't lose the whole
233
+ # diff over it: fall back to approximate totals, then to no totals.
234
+ try:
235
+ return profile(tbl_cte, cols)
236
+ except Exception as e:
237
+ first = str(e).strip().splitlines()[0][:200] if str(e).strip() else type(e).__name__
238
+ try:
239
+ r = profile(tbl_cte, cols, "double")
240
+ msg = ("Exact totals overflowed, so column totals are approximate (added as DOUBLE). "
241
+ f"Engine said: {first}")
242
+ except Exception:
243
+ r = profile(tbl_cte, cols, "none")
244
+ msg = f"Column totals could not be computed, so total-based rules can't fire. Engine said: {first}"
245
+ if msg not in notes:
246
+ notes.append(msg)
247
+ return r
248
+
249
+ pb = safe_profile("b_src", b_cols)
250
+ pc = safe_profile("c_src", c_cols)
203
251
 
204
252
  col_changes: list[ColumnChange] = []
205
253
  for i, col in enumerate(common):
@@ -49,12 +49,14 @@ def explain_diff(d: TableDiff, measures: list[str] | str | None = None) -> str:
49
49
 
50
50
  moved = [
51
51
  c for c in d.columns
52
- if c.sum_change_pct is not None and abs(c.sum_change_pct) >= 0.01
52
+ if (c.sum_moved_from_zero or (c.sum_change_pct is not None and abs(c.sum_change_pct) >= 0.01))
53
53
  and is_measure(c.column, d.keys, measures)
54
54
  ]
55
- moved.sort(key=lambda c: -abs(c.sum_change_pct or 0))
55
+ moved.sort(key=lambda c: (not c.sum_moved_from_zero, -abs(c.sum_change_pct or 0)))
56
56
  if moved:
57
- s += ". Totals: " + ", ".join(f"sum({c.column}) {c.sum_change_pct:+.2f}%" for c in moved[:3])
57
+ from bricksentry.policy import _sum_move
58
+
59
+ s += ". Totals: " + ", ".join(_sum_move(c) for c in moved[:3])
58
60
 
59
61
  nulls = [
60
62
  c for c in d.columns
@@ -25,6 +25,13 @@ DATA_OPS = frozenset({
25
25
  "COPY INTO", "RESTORE",
26
26
  })
27
27
 
28
+ # Maintenance that a RESTORE doesn't meaningfully undo. Anything else that isn't a data
29
+ # change (RENAME COLUMN, SET TBLPROPERTIES, ADD COLUMNS, constraints ...) is undone by a
30
+ # RESTORE too, so the rollback warning lists it.
31
+ MAINTENANCE_OPS = frozenset({
32
+ "OPTIMIZE", "VACUUM START", "VACUUM END", "ANALYZE", "COMPUTE STATISTICS", "FSCK", "REORG",
33
+ })
34
+
28
35
  _NAME = re.compile(r"[A-Za-z0-9_]+(\.[A-Za-z0-9_]+){1,2}")
29
36
 
30
37
 
@@ -44,6 +51,9 @@ class Change:
44
51
  versions: list[int] # every data-changing version folded into this check
45
52
  # Data changes committed after ``version``: restoring to ``base_version`` undoes them too.
46
53
  newer: list[dict[str, Any]] = field(default_factory=list)
54
+ # Table changes that aren't data (renamed columns, properties, constraints) after ``version``:
55
+ # a RESTORE undoes these too.
56
+ newer_other: list[dict[str, Any]] = field(default_factory=list)
47
57
 
48
58
  def to_dict(self) -> dict[str, Any]:
49
59
  return {
@@ -54,6 +64,7 @@ class Change:
54
64
  "timestamp": self.timestamp,
55
65
  "versions": self.versions,
56
66
  "newer_changes": self.newer,
67
+ "newer_table_changes": self.newer_other,
57
68
  }
58
69
 
59
70
 
@@ -72,10 +83,30 @@ def newer_data_changes(history: list[dict[str, Any]], version: int) -> list[dict
72
83
  return sorted(out, key=lambda h: h["version"])
73
84
 
74
85
 
86
+ def newer_table_changes(history: list[dict[str, Any]], version: int) -> list[dict[str, Any]]:
87
+ """Changes after ``version`` that aren't data or maintenance, oldest first: RENAME COLUMN,
88
+ SET TBLPROPERTIES, ADD COLUMNS, constraints... A RESTORE undoes these too."""
89
+ out = []
90
+ for h in history:
91
+ v = h.get("version")
92
+ op = str(h.get("operation") or "").strip().upper()
93
+ if v is None or int(v) <= version or is_data_op(op) or op in MAINTENANCE_OPS or not op:
94
+ continue
95
+ out.append({"version": int(v), "operation": str(h.get("operation")), "timestamp": str(h.get("timestamp") or "")})
96
+ return sorted(out, key=lambda h: h["version"])
97
+
98
+
75
99
  def rollback_warning(change: Change, max_listed: int = 3) -> str | None:
76
- """The warning to show next to the RESTORE when newer data changes exist, else None."""
100
+ """The warning to show next to the RESTORE when newer changes exist, else None."""
77
101
  if not change.newer:
78
- return None
102
+ if not change.newer_other:
103
+ return None
104
+ listed = ", ".join(f"v{h['version']} ({h['operation']})" for h in change.newer_other[-max_listed:][::-1])
105
+ more = len(change.newer_other) - max_listed
106
+ if more > 0:
107
+ listed += f" and {more} more"
108
+ return (f"Newer table changes exist: {listed}. Restoring to v{change.base_version} also undoes "
109
+ f"{'it' if len(change.newer_other) == 1 else 'them'}; re-apply after restoring, or fix forward instead.")
79
110
  listed = ", ".join(
80
111
  f"v{h['version']} ({h['operation']}{', ' + h['timestamp'] if h['timestamp'] else ''})"
81
112
  for h in change.newer[-max_listed:][::-1])
@@ -83,9 +114,13 @@ def rollback_warning(change: Change, max_listed: int = 3) -> str | None:
83
114
  if more > 0:
84
115
  listed += f" and {more} more"
85
116
  n = len(change.newer)
86
- return (f"Newer data changes exist: {listed}. Restoring to v{change.base_version} also undoes "
117
+ text = (f"Newer data changes exist: {listed}. Restoring to v{change.base_version} also undoes "
87
118
  f"{'it' if n == 1 else 'them'}. Re-run {'that write' if n == 1 else 'those writes'} after "
88
119
  "restoring, or fix forward instead.")
120
+ if change.newer_other:
121
+ others = ", ".join(f"v{h['version']} ({h['operation']})" for h in change.newer_other[-max_listed:][::-1])
122
+ text += f" It also undoes these table changes: {others}."
123
+ return text
89
124
 
90
125
 
91
126
  def _ts(value: Any) -> datetime | None:
@@ -258,6 +293,7 @@ def check_change(
258
293
  except Exception: # pragma: no cover - keep the first read if a second one fails
259
294
  latest = history
260
295
  change.newer = newer_data_changes(latest, change.version)
296
+ change.newer_other = newer_table_changes(latest, change.version)
261
297
  warning = rollback_warning(change)
262
298
  undo = f"RESTORE TABLE {db.qualified(table)} TO VERSION AS OF {change.base_version}"
263
299
  for t in a.tables:
@@ -50,6 +50,12 @@ class ColumnChange:
50
50
  return None
51
51
  return (self.candidate_sum - self.base_sum) / abs(self.base_sum) * 100
52
52
 
53
+ @property
54
+ def sum_moved_from_zero(self) -> bool:
55
+ """The total was zero (or had no values) and now isn't. No percentage exists for
56
+ that, so it is reported on its own: a total going from 0 to millions has moved."""
57
+ return self.base_sum in (None, 0) and self.candidate_sum not in (None, 0)
58
+
53
59
 
54
60
  @dataclass
55
61
  class SchemaChange:
@@ -137,6 +143,7 @@ class TableDiff:
137
143
  d["is_identical"] = self.is_identical
138
144
  for c, cc in zip(d["columns"], self.columns, strict=False):
139
145
  c["sum_change_pct"] = cc.sum_change_pct
146
+ c["sum_moved_from_zero"] = cc.sum_moved_from_zero
140
147
  return d
141
148
 
142
149
  @classmethod
@@ -16,7 +16,7 @@ never from an LLM, so agents and CI get the same answer for the same change.
16
16
  when: {column_removed: true}
17
17
  then: needs_human
18
18
  - name: certified-downstream
19
- when: {downstream_tag: certified}
19
+ when: {downstream_tag: certified, any_change: true}
20
20
  then: needs_human
21
21
  - name: big-row-loss
22
22
  when: {removed_pct_gt: 1}
@@ -42,6 +42,7 @@ from __future__ import annotations
42
42
  import fnmatch
43
43
  import hashlib
44
44
  import json
45
+ import warnings
45
46
  from typing import Any
46
47
 
47
48
  from bricksentry.measures import is_measure
@@ -57,8 +58,8 @@ DEFAULT_POLICY: dict[str, Any] = {
57
58
  {"name": "null-keys", "when": {"null_keys": True}, "then": "warn"},
58
59
  {"name": "dropped-column", "when": {"column_removed": True}, "then": "needs_human"},
59
60
  {"name": "type-change", "when": {"column_type_changed": True}, "then": "warn"},
60
- {"name": "certified-downstream", "when": {"downstream_tag": "certified"}, "then": "needs_human"},
61
- {"name": "pii-table", "when": {"tag": "pii"}, "then": "needs_human"},
61
+ {"name": "certified-downstream", "when": {"downstream_tag": "certified", "any_change": True}, "then": "needs_human"},
62
+ {"name": "pii-table", "when": {"tag": "pii", "any_change": True}, "then": "needs_human"},
62
63
  {"name": "pii-column-changed", "when": {"changed_column_tag": "pii"}, "then": "needs_human"},
63
64
  {"name": "row-loss", "when": {"removed_pct_gt": 1}, "then": "needs_human"},
64
65
  {"name": "many-rows-changed", "when": {"changed_pct_gt": 10}, "then": "warn"},
@@ -97,6 +98,24 @@ class ColumnContext:
97
98
  self.downstream = downstream or []
98
99
 
99
100
 
101
+ def _verdict(value: Any, where: str) -> Verdict:
102
+ try:
103
+ return Verdict(str(value).strip().lower())
104
+ except ValueError:
105
+ valid = ", ".join(v.value for v in Verdict)
106
+ raise PolicyError(f"Policy {where}: {value!r} is not a verdict. Use one of: {valid}.") from None
107
+
108
+
109
+ def _sum_move(c: Any) -> str:
110
+ if c.sum_moved_from_zero:
111
+ return f"sum({c.column}) {_num(c.base_sum or 0)} -> {_num(c.candidate_sum)}"
112
+ return f"sum({c.column}) {c.sum_change_pct:+.2f}%"
113
+
114
+
115
+ def _num(v: Any) -> str:
116
+ return f"{v:,.2f}".rstrip("0").rstrip(".") if isinstance(v, float) else f"{v:,}"
117
+
118
+
100
119
  def _tag_label(want: Any) -> str:
101
120
  if isinstance(want, dict):
102
121
  return ", ".join(f"{k}={v}" for k, v in want.items())
@@ -110,14 +129,21 @@ class Policy:
110
129
  # traced to the exact policy that produced it.
111
130
  canonical = json.dumps(spec, sort_keys=True, default=str, separators=(",", ":"))
112
131
  self.sha256 = hashlib.sha256(canonical.encode()).hexdigest()
113
- self.default = Verdict(spec.get("default", "pass"))
114
- self.notify_on = Verdict(spec.get("notify_owners_on", "needs_human"))
132
+ if not isinstance(spec, dict):
133
+ raise PolicyError(f"A policy is a mapping with `rules:`; got {type(spec).__name__}.")
134
+ self.default = _verdict(spec.get("default", "pass"), "default")
135
+ self.notify_on = _verdict(spec.get("notify_owners_on", "needs_human"), "notify_owners_on")
115
136
  self.rules = spec.get("rules") or []
116
137
  for r in self.rules:
117
138
  unknown = set((r.get("when") or {}).keys()) - KNOWN_CONDITIONS
118
139
  if unknown:
119
140
  raise PolicyError(f"Rule {r.get('name')!r} uses unknown condition(s): {sorted(unknown)}")
120
- Verdict(r.get("then", "warn"))
141
+ _verdict(r.get("then", "warn"), f"rule {r.get('name')!r}: then")
142
+ if not self.rules and self.default == Verdict.PASS:
143
+ # Most likely an empty or mis-indented policy file. Allowed, but never silently.
144
+ warnings.warn(
145
+ "bricksentry policy has no rules, so every change passes (even a 99% row loss). "
146
+ "Use `policy: builtin:default` for the standard rules.", UserWarning, stacklevel=2)
121
147
 
122
148
  def evaluate(
123
149
  self,
@@ -135,7 +161,7 @@ class Policy:
135
161
  ok, reason = _match(r.get("when") or {}, table, diff, downstream, tags, diff_error, measures, lineage_error,
136
162
  columns or ColumnContext())
137
163
  if ok:
138
- hits.append(RuleHit(rule=r.get("name", "unnamed"), verdict=Verdict(r.get("then", "warn")), table=table, reason=reason))
164
+ hits.append(RuleHit(rule=r.get("name", "unnamed"), verdict=_verdict(r.get("then", "warn"), "then"), table=table, reason=reason))
139
165
  verdict = Verdict.worst([self.default] + [h.verdict for h in hits])
140
166
  return verdict, hits
141
167
 
@@ -225,13 +251,18 @@ def _match(
225
251
  reasons.append(f"{len(downstream)} downstream assets")
226
252
  continue
227
253
 
228
- # Everything below needs a diff.
229
- if diff is None:
230
- return False, ""
231
254
  if cond == "any_change":
232
- if diff.is_identical == bool(val):
255
+ # No diff (it failed or never ran) can't prove nothing changed, so it counts
256
+ # as a change: a gate with any_change never passes silently on a missing diff.
257
+ changed = True if diff is None else not diff.is_identical
258
+ if changed != bool(val):
233
259
  return False, ""
260
+ if diff is None:
261
+ reasons.append("no diff, so a change can't be ruled out")
234
262
  continue
263
+ # Everything below needs a diff.
264
+ if diff is None:
265
+ return False, ""
235
266
  if cond == "duplicate_keys":
236
267
  dup = diff.duplicate_keys_candidate > diff.duplicate_keys_base
237
268
  if dup != bool(val):
@@ -282,13 +313,14 @@ def _match(
282
313
  col = when.get("column")
283
314
  cols = [
284
315
  c for c in diff.columns
285
- if c.sum_change_pct is not None
316
+ if (c.sum_change_pct is not None or c.sum_moved_from_zero)
286
317
  and (c.column == col if col is not None else is_measure(c.column, diff.keys, measures))
287
318
  ]
288
- m = [c for c in cols if abs(c.sum_change_pct) > float(val)]
319
+ # A total that moves away from zero has no percentage, but it has moved.
320
+ m = [c for c in cols if c.sum_moved_from_zero or abs(c.sum_change_pct) > float(val)]
289
321
  if not m:
290
322
  return False, ""
291
- reasons.append(", ".join(f"sum({c.column}) {c.sum_change_pct:+.2f}%" for c in m[:3]))
323
+ reasons.append(", ".join(_sum_move(c) for c in m[:3]))
292
324
  continue
293
325
  if cond == "null_increase_gt":
294
326
  col = when.get("column")
@@ -158,6 +158,7 @@ class _Validation:
158
158
  out = []
159
159
  for fn in (self.row_loss, self.bad_merge, self.everything_wrong, self.hidden_in_sample,
160
160
  self.certified_totals_default, self.certified_totals_strict, self.null_keys,
161
+ self.null_keys_changed, self.pii_noop,
161
162
  self.exact_totals, self.landed_change, self.typo_table):
162
163
  t0 = time.time()
163
164
  try:
@@ -253,6 +254,31 @@ class _Validation:
253
254
  "matched one to one: 3,000 unchanged, nothing added or removed",
254
255
  f"unchanged={d.unchanged_rows}, added={d.added_rows}, removed={d.removed_rows}", ok)
255
256
 
257
+ def null_keys_changed(self) -> ScenarioResult:
258
+ base = self.create("bsv_nulls2", f"SELECT CASE WHEN i <= 2000 THEN NULL ELSE i END AS id, i AS v "
259
+ f"FROM ({self.ids(3000)}) ids")
260
+ cand = self.create("bsv_c_nulls2", f"SELECT id, CASE WHEN v IN (10, 1500) THEN v + 1000000 ELSE v END AS v "
261
+ f"FROM {self.q(base)}")
262
+ d = self.sentry.diff(base, cand, keys=["id"], table=base)
263
+ ok = (d.added_rows, d.removed_rows, d.changed_rows) == (0, 0, 2)
264
+ return ScenarioResult("null_keys_changed", "2 of 2,000 rows sharing a NULL key get a new value",
265
+ "exactly 2 changed; the other copies still match",
266
+ f"changed={d.changed_rows}, added={d.added_rows}, removed={d.removed_rows}", ok)
267
+
268
+ def pii_noop(self) -> ScenarioResult:
269
+ same = self.create("bsv_c_pii_same", f"SELECT * FROM {self.q(self.emp)}")
270
+ a = self.assess(self.emp, same)
271
+ one = self.create("bsv_c_pii_one", f"SELECT emp_id, department, CASE WHEN emp_id = 1 "
272
+ f"THEN CAST(salary + 1 AS DECIMAL(12, 2)) ELSE salary END AS salary, email "
273
+ f"FROM {self.q(self.emp)}")
274
+ b = self.assess(self.emp, one)
275
+ rules = {h.rule for h in b.hits}
276
+ ok = (a.verdict == Verdict.PASS and b.verdict == Verdict.NEEDS_HUMAN
277
+ and {"pii-table", "certified-downstream"} <= rules)
278
+ return ScenarioResult("pii_noop", "a PII table feeding a certified mart: an identical rebuild, then a 1-row salary edit",
279
+ "identical: pass; 1 row changed: needs_human (pii-table, certified-downstream)",
280
+ f"identical: {a.verdict.value}; 1 row: {b.verdict.value} {sorted(rules)}", ok)
281
+
256
282
  def exact_totals(self) -> ScenarioResult:
257
283
  base = self.create("bsv_exact", f"SELECT i AS id, CAST(0.10 AS DECIMAL(18, 2)) AS amount "
258
284
  f"FROM ({self.ids(self.exact_rows)}) ids")
@@ -86,10 +86,10 @@
86
86
  },
87
87
  "bricksentry_version": {
88
88
  "type": "string",
89
- "default": "0.1.25",
89
+ "default": "0.1.26",
90
90
  "description": "bricksentry version to install in the job (pinned; change it and redeploy to upgrade)",
91
91
  "pattern": "^\\d+\\.\\d+\\.\\d+$",
92
- "pattern_match_failure_message": "Use a version like 0.1.25.",
92
+ "pattern_match_failure_message": "Use a version like 0.1.26.",
93
93
  "order": 10
94
94
  }
95
95
  },
@@ -41,7 +41,7 @@ def test_many_null_keys_do_not_multiply(backend):
41
41
  # 2,000 NULL keys on each side used to join into 4,000,000 pairs.
42
42
  assert (d.added_rows, d.removed_rows, d.changed_rows, d.unchanged_rows) == (0, 0, 0, 3000)
43
43
  assert d.null_keys_base == 2000 and d.is_identical
44
- assert d.notes and "paired one to one" in d.notes[0]
44
+ assert d.notes and "Identical copies of a key were matched first" in d.notes[0]
45
45
 
46
46
 
47
47
  def test_a_new_copy_of_a_key_counts_as_added(backend):
@@ -221,6 +221,6 @@ def test_validation_battery_passes_on_duckdb(backend):
221
221
  assert by["hidden_in_sample"].passed and by["certified_totals_default"].actual.startswith("warn")
222
222
  lines = []
223
223
  print_results(results, out=lines.append)
224
- assert lines[-1].startswith("8 passed, 0 failed, 2 skipped")
224
+ assert lines[-1].startswith("10 passed, 0 failed, 2 skipped")
225
225
  left = backend.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'bsv_test'")
226
226
  assert left == [] # everything it made is dropped
@@ -0,0 +1,173 @@
1
+ """0.1.26: fixes for what Genie's worst-case rounds found."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+
7
+ import pytest
8
+
9
+ from bricksentry.config import Config
10
+ from bricksentry.diff import diff_tables
11
+ from bricksentry.history import Change, newer_table_changes, rollback_warning
12
+ from bricksentry.models import ColumnChange, SchemaChange, TableDiff
13
+ from bricksentry.policy import Policy, PolicyError
14
+
15
+
16
+ # --- (b) one changed copy no longer shifts how the other copies pair ---------------
17
+ def test_null_keys_with_two_changes_report_two(backend):
18
+ backend.execute("CREATE SCHEMA p")
19
+ backend.execute("CREATE TABLE p.base AS SELECT CASE WHEN i <= 2000 THEN NULL ELSE i END AS id, i AS v "
20
+ "FROM range(1, 3001) t(i)")
21
+ # Change two rows that share the NULL key, plus nothing else.
22
+ backend.execute("CREATE TABLE p.cand AS SELECT id, CASE WHEN i IN (10, 1500) THEN v + 1000000 ELSE v END AS v "
23
+ "FROM (SELECT *, v AS i FROM p.base)")
24
+ d = diff_tables(backend, "p.base", "p.cand", ["id"])
25
+ assert (d.added_rows, d.removed_rows, d.changed_rows) == (0, 0, 2)
26
+ assert d.columns[0].changed_rows == 2
27
+
28
+
29
+ def test_duplicate_copies_identical_still_match(backend):
30
+ backend.execute("CREATE SCHEMA r")
31
+ backend.execute("CREATE TABLE r.base AS SELECT i % 7 AS id, i AS v FROM range(1, 701) t(i)")
32
+ backend.execute("CREATE TABLE r.cand AS SELECT * FROM r.base")
33
+ d = diff_tables(backend, "r.base", "r.cand", ["id"])
34
+ assert (d.added_rows, d.removed_rows, d.changed_rows) == (0, 0, 0)
35
+
36
+
37
+ def test_extra_and_missing_copies_with_a_change(backend):
38
+ backend.execute("CREATE SCHEMA s")
39
+ backend.execute("CREATE TABLE s.base AS SELECT 1 AS id, i AS v FROM range(1, 6) t(i)") # v 1..5
40
+ # v=1 dropped, v=3 changed to 30, v=9 and v=10 new: 2 leftovers vs 3 leftovers.
41
+ backend.execute("CREATE TABLE s.cand AS SELECT CAST(id AS BIGINT) AS id, CAST(v AS BIGINT) AS v FROM "
42
+ "(VALUES (1, 2), (1, 30), (1, 4), (1, 5), (1, 9), (1, 10)) t(id, v)")
43
+ d = diff_tables(backend, "s.base", "s.cand", ["id"])
44
+ assert d.changed_rows == 2 and d.added_rows == 1 and d.removed_rows == 0
45
+ assert d.base_rows == 5 and d.candidate_rows == 6
46
+
47
+
48
+ # --- (c) an overflowing exact total doesn't kill the diff -------------------------
49
+ def test_decimal_overflow_falls_back_to_approximate_totals(backend):
50
+ backend.execute("CREATE SCHEMA o")
51
+ backend.execute("CREATE TABLE o.base AS SELECT i AS id, CAST(9.9e37 AS DECIMAL(38, 0)) AS big "
52
+ "FROM range(1, 11) t(i)")
53
+ backend.execute("CREATE TABLE o.cand AS SELECT * FROM o.base WHERE id > 1")
54
+ d = diff_tables(backend, "o.base", "o.cand", ["id"])
55
+ assert d.removed_rows == 1
56
+ assert any("approximate" in n or "could not be computed" in n for n in d.notes)
57
+
58
+
59
+ # --- (a) a total moving away from zero fires the total rule ----------------------
60
+ def _diff_with(col: ColumnChange) -> TableDiff:
61
+ return TableDiff(table="t", base="b", candidate="c", keys=["id"], base_rows=10, candidate_rows=10,
62
+ added_rows=0, removed_rows=0, changed_rows=5, unchanged_rows=5, schema=SchemaChange(), columns=[col])
63
+
64
+
65
+ def test_total_moving_from_zero_fires():
66
+ p = Policy({"rules": [{"name": "totals", "when": {"sum_change_pct_gt": 1}, "then": "block"}]})
67
+ col = ColumnChange(column="amount", changed_rows=5, base_nulls=0, candidate_nulls=0, base_sum=0.0,
68
+ candidate_sum=5.0)
69
+ assert col.sum_moved_from_zero
70
+ verdict, hits = p.evaluate("t", _diff_with(col), [], {})
71
+ assert verdict.value == "block" and "0 -> 5" in hits[0].reason
72
+ still = ColumnChange(column="amount", changed_rows=0, base_nulls=0, candidate_nulls=0, base_sum=0.0,
73
+ candidate_sum=0.0)
74
+ assert p.evaluate("t", _diff_with(still), [], {})[0].value == "pass"
75
+
76
+
77
+ # --- (d) metadata changes show in the rollback warning ---------------------------
78
+ def test_metadata_changes_after_the_version_are_listed():
79
+ hist = [{"version": 6, "operation": "SET TBLPROPERTIES"}, {"version": 5, "operation": "OPTIMIZE"},
80
+ {"version": 4, "operation": "RENAME COLUMN"}, {"version": 3, "operation": "DELETE"}]
81
+ other = newer_table_changes(hist, 3)
82
+ assert [h["version"] for h in other] == [4, 6]
83
+ w = rollback_warning(Change("t", 3, 2, "DELETE", "", [3], newer_other=other))
84
+ assert w.startswith("Newer table changes exist: v6 (SET TBLPROPERTIES), v4 (RENAME COLUMN).")
85
+ both = rollback_warning(Change("t", 3, 2, "DELETE", "", [3],
86
+ newer=[{"version": 7, "operation": "WRITE", "timestamp": ""}], newer_other=other))
87
+ assert "It also undoes these table changes: v6 (SET TBLPROPERTIES), v4 (RENAME COLUMN)." in both
88
+
89
+
90
+ # --- (e)(f)(g) policy mistakes give clear messages -------------------------------
91
+ def test_typo_in_a_verdict_names_the_choices():
92
+ with pytest.raises(PolicyError, match="'blok' is not a verdict. Use one of: pass, warn, needs_human, block"):
93
+ Policy({"rules": [{"name": "x", "when": {"removed_pct_gt": 1}, "then": "blok"}]})
94
+ p = Policy({"rules": [{"name": "x", "when": {"removed_pct_gt": 1}, "then": "BLOCK"}]})
95
+ assert p.rules # any case is accepted
96
+
97
+
98
+ def test_template_name_without_builtin_prefix_says_how(tmp_path):
99
+ with pytest.raises(FileNotFoundError, match="builtin:strict"):
100
+ Config.from_dict({"policy": "strict"}, root=tmp_path)
101
+
102
+
103
+ def test_empty_policy_warns():
104
+ with warnings.catch_warnings(record=True) as w:
105
+ warnings.simplefilter("always")
106
+ Policy({"rules": []})
107
+ assert any("every change passes" in str(x.message) for x in w)
108
+
109
+
110
+ def test_non_mapping_policy_is_a_policy_error():
111
+ with pytest.raises(PolicyError, match="mapping"):
112
+ Policy(["rules"]) # type: ignore[arg-type]
113
+
114
+
115
+ # --- (h) preview_write shows one clear line when the statement fails -------------
116
+ def test_preview_write_failure_is_one_line(sentry, backend):
117
+ backend.execute("CREATE SCHEMA IF NOT EXISTS sales")
118
+ backend.execute("CREATE TABLE IF NOT EXISTS sales.pw AS SELECT 1 AS id, 2 AS v")
119
+ with pytest.raises(RuntimeError) as e:
120
+ sentry.preview_write("UPDATE sales.pw SET nope = 1", "sales.pw", keys=["id"])
121
+ msg = str(e.value)
122
+ assert msg.startswith("The statement failed on the preview clone, so production was not touched:")
123
+ assert "\n" not in msg
124
+
125
+
126
+ # --- (i) pii / certified gates ignore no-op changes, but nothing else ------------
127
+ def test_noop_change_to_certified_feeder_passes_and_a_real_one_does_not(sentry, backend):
128
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
129
+ assert sentry.assess(["sales.orders"]).verdict.value == "pass"
130
+ backend.execute("DROP TABLE sales_ci.orders")
131
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
132
+ backend.execute("UPDATE sales_ci.orders SET amount = amount + 1 WHERE order_id = (SELECT MIN(order_id) FROM sales_ci.orders)")
133
+ a = sentry.assess(["sales.orders"])
134
+ hit = next(h for h in a.hits if h.rule == "certified-downstream")
135
+ assert a.verdict.value == "needs_human" and "tagged certified" in hit.reason
136
+
137
+
138
+ def test_pii_gate_names_the_tag_and_fires_on_schema_only_and_missing_diff():
139
+ p = Policy()
140
+ no_rows = TableDiff(table="t", base="b", candidate="c", keys=["id"], base_rows=1, candidate_rows=1,
141
+ added_rows=0, removed_rows=0, changed_rows=0, unchanged_rows=1, schema=SchemaChange())
142
+ assert p.evaluate("t", no_rows, [], {"pii": "true"})[0].value == "pass"
143
+ no_rows.schema = SchemaChange(removed={"email": "string"})
144
+ v, hits = p.evaluate("t", no_rows, [], {"pii": "true"})
145
+ assert v.value == "needs_human" and any(h.rule == "pii-table" and "table is tagged pii" in h.reason for h in hits)
146
+ # No diff at all can't prove nothing changed: the gate still fires.
147
+ custom = Policy({"rules": [{"name": "pii", "when": {"tag": "pii", "any_change": True}, "then": "needs_human"}]})
148
+ v, hits = custom.evaluate("t", None, [], {"pii": "true"}, diff_error="boom")
149
+ assert v.value == "needs_human" and "can't be ruled out" in hits[0].reason
150
+
151
+
152
+ # --- found in the 0.1.26 pre-release check: mistyped names in agent tools --------
153
+ def test_agent_tools_report_a_mistyped_table(sentry):
154
+ from bricksentry import agent_tools
155
+
156
+ agent_tools.set_sentry(sentry)
157
+ try:
158
+ for out in (agent_tools.whats_downstream("sales.orderz"), agent_tools.rollback_plan("sales.orderz")):
159
+ assert out["error"].startswith("LookupError: Table sales.orderz not found.")
160
+ assert agent_tools.whats_downstream("sales.orders")["count"] == 3 # real tables unchanged
161
+ assert "error" not in agent_tools.rollback_plan("sales.orders")
162
+ finally:
163
+ agent_tools.set_sentry(None)
164
+
165
+
166
+ def test_misspelled_backend_key_is_rejected():
167
+ from bricksentry.backends.base import make_backend
168
+
169
+ with pytest.raises(ValueError, match="Unknown key\\(s\\) under backend: path for type duckdb. Valid keys: type, database"):
170
+ make_backend({"type": "duckdb", "path": "x.db"})
171
+ with pytest.raises(ValueError, match="warehouse"):
172
+ make_backend({"type": "databricks", "warehouse": "abc"})
173
+ assert make_backend({"type": "duckdb", "database": ":memory:"}).name == "duckdb"
@@ -9,10 +9,9 @@ from bricksentry.report import MARKER, to_markdown
9
9
  def test_clean_change_passes_but_flags_dashboard(sentry, backend):
10
10
  backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
11
11
  a = sentry.assess(["sales.orders"])
12
- # identical data: certified downstream still requires a human by default policy
13
- assert a.verdict == Verdict.NEEDS_HUMAN
14
- assert {h.rule for h in a.hits} == {"certified-downstream"}
15
- assert a.notify == ["finance-team", "sales-eng"]
12
+ # identical data: nothing changed, so the certified-downstream gate stays quiet (0.1.26)
13
+ assert a.verdict == Verdict.PASS
14
+ assert a.hits == []
16
15
 
17
16
 
18
17
  def test_duplicate_keys_block(sentry, backend):
@@ -1 +0,0 @@
1
- bricksentry[databricks,mcp]==0.1.25
File without changes
File without changes
File without changes
File without changes