bricksentry 0.1.22__tar.gz → 0.1.24__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 (87) hide show
  1. {bricksentry-0.1.22 → bricksentry-0.1.24}/CHANGELOG.md +20 -0
  2. bricksentry-0.1.22/README.md → bricksentry-0.1.24/PKG-INFO +71 -5
  3. bricksentry-0.1.22/PKG-INFO → bricksentry-0.1.24/README.md +24 -52
  4. bricksentry-0.1.24/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_check_my_table.ipynb +1 -1
  6. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_check_my_table.py +1 -1
  7. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_quickstart.ipynb +1 -1
  8. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_quickstart.py +1 -1
  9. {bricksentry-0.1.22 → bricksentry-0.1.24}/pyproject.toml +3 -2
  10. {bricksentry-0.1.22 → bricksentry-0.1.24}/server.json +2 -2
  11. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/__init__.py +1 -1
  12. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/assess.py +22 -0
  13. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/backends/base.py +16 -0
  14. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/backends/databricks_backend.py +3 -0
  15. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/backends/duckdb_backend.py +3 -0
  16. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/cli.py +1 -1
  17. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/diff.py +46 -17
  18. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/history.py +24 -1
  19. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/job.py +5 -0
  20. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/models.py +14 -0
  21. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/policy.py +6 -0
  22. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/report.py +8 -1
  23. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/databricks_template_schema.json +2 -2
  24. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0114.py +3 -1
  25. bricksentry-0.1.24/tests/test_0123.py +195 -0
  26. bricksentry-0.1.22/deploy/databricks-app/requirements.txt +0 -1
  27. {bricksentry-0.1.22 → bricksentry-0.1.24}/.gitignore +0 -0
  28. {bricksentry-0.1.22 → bricksentry-0.1.24}/CONTRIBUTING.md +0 -0
  29. {bricksentry-0.1.22 → bricksentry-0.1.24}/LICENSE +0 -0
  30. {bricksentry-0.1.22 → bricksentry-0.1.24}/SECURITY.md +0 -0
  31. {bricksentry-0.1.22 → bricksentry-0.1.24}/action.yml +0 -0
  32. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/container/Dockerfile +0 -0
  33. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/databricks-app/README.md +0 -0
  34. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/databricks-app/app.yaml +0 -0
  35. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/databricks-app/bricksentry.yml +0 -0
  36. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/databricks-app/databricks.yml +0 -0
  37. {bricksentry-0.1.22 → bricksentry-0.1.24}/deploy/databricks-app/grants.sql +0 -0
  38. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry.yml +0 -0
  39. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  40. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  41. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/github-workflow.yml +0 -0
  42. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/databricks/policy.yml +0 -0
  43. {bricksentry-0.1.22 → bricksentry-0.1.24}/examples/demo/agent_loop_demo.py +0 -0
  44. {bricksentry-0.1.22 → bricksentry-0.1.24}/scripts/build_notebook.py +0 -0
  45. {bricksentry-0.1.22 → bricksentry-0.1.24}/scripts/render_demo_image.py +0 -0
  46. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/__main__.py +0 -0
  47. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/agent_tools.py +0 -0
  48. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/backends/__init__.py +0 -0
  49. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/changes.py +0 -0
  50. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/config.py +0 -0
  51. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/demo.py +0 -0
  52. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/explain.py +0 -0
  53. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/github.py +0 -0
  54. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/job_demo.py +0 -0
  55. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/lineage.py +0 -0
  56. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/mcp_server.py +0 -0
  57. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/measures.py +0 -0
  58. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/netguard.py +0 -0
  59. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/notify.py +0 -0
  60. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/policy_templates.py +0 -0
  61. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/preview.py +0 -0
  62. {bricksentry-0.1.22 → bricksentry-0.1.24}/src/bricksentry/py.typed +0 -0
  63. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/README.md +0 -0
  64. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  65. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  66. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  67. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  68. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  69. {bricksentry-0.1.22 → bricksentry-0.1.24}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  70. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/conftest.py +0 -0
  71. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0110.py +0 -0
  72. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0112.py +0 -0
  73. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0120.py +0 -0
  74. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0121.py +0 -0
  75. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_0122.py +0 -0
  76. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_018.py +0 -0
  77. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_019.py +0 -0
  78. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_assess_policy.py +0 -0
  79. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_check_notebook.py +0 -0
  80. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_databricks_and_uc.py +0 -0
  81. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_demo.py +0 -0
  82. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_diff.py +0 -0
  83. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_hr_notebook.py +0 -0
  84. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_notebook.py +0 -0
  85. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_notify_templates.py +0 -0
  86. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_preview_agents.py +0 -0
  87. {bricksentry-0.1.22 → bricksentry-0.1.24}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.24 (2026-11-16)
4
+
5
+ Small fixes from two adversarial live tests of 0.1.23 on Databricks, including the job task running inside a real Databricks job.
6
+
7
+ - The job task log no longer ends with IPython's "To exit: use 'exit', 'quit', or Ctrl-D." after a failing verdict (Databricks runs `spark_python_task` scripts inside IPython). The exit code is unchanged.
8
+ - `check-last-change` and the job task report a mistyped or missing table in one line ("Table main.hr.employes not found. Check the catalog, schema and table name…"), and a missing permission as "No permission to read …", instead of the engine's full error with the echoed SQL and unrelated hints. Other history errors keep only their first line. Found in a live test of 0.1.23.
9
+ - `bricksentry test-alert --help` said it exits 1 when no webhook is configured; it exits 2 (configuration error), which the help now says. Found in the live test of 0.1.23.
10
+ - README: "Validated on" covers the live run of 0.1.23.
11
+ - README: the default policy is lenient on changes to a certified table itself (a doubled total only warns); use `builtin:certified` or `builtin:finance` to require a human. From an adversarial live test of 0.1.23.
12
+
13
+ ## 0.1.23 (2026-11-16)
14
+
15
+ From a review of accuracy, auditability and documentation:
16
+
17
+ - **Exact totals.** Sums of decimal and integer columns are added as `DECIMAL(38, x)` instead of `DOUBLE`, so totals on large tables don't drift by cents and big integer columns can't overflow. Floating-point columns are still summed as `DOUBLE`.
18
+ - **Duplicated keys are matched one to one.** When a key appears more than once (including many rows with a NULL key, which match each other), copies are numbered and copy *n* is matched with copy *n*. Before, every copy matched every other copy: 2,000 NULL-key rows on each side joined into 4,000,000 pairs, and a duplicated row counted as a second match instead of an added row. A bad MERGE that duplicates rows now shows them as added, and the diff notes that copies were paired. Tables without duplicate keys run exactly as before.
19
+ - **Audit trail on every assessment:** `created_at` (UTC), `bricksentry_version`, `policy_sha256` (a fingerprint of the rules behind the verdict) and `triggered_by` (`BRICKSENTRY_ACTOR`, or the GitHub actor in GitHub Actions). In the JSON and the pull-request report footer. Older saved assessments still load.
20
+ - README: permissions needed per feature, what a check costs, and the audit trail.
21
+ - Links to the agent docs no longer end in `).` where READMEs and notebooks are shown as plain text (some directories turned them into a broken link). Package description and keywords mention change impact analysis and deployment guardrails.
22
+
3
23
  ## 0.1.22 (2026-11-15)
4
24
 
5
25
  Security hardening, following a review on the Canopii MCP Trust Index:
@@ -1,3 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: bricksentry
3
+ Version: 0.1.24
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
+ Project-URL: Homepage, https://bricksentry.org
6
+ Project-URL: Documentation, https://bricksentry.org/docs
7
+ Project-URL: Source, https://github.com/bricksentry/bricksentry
8
+ Project-URL: Issues, https://github.com/bricksentry/bricksentry/issues
9
+ Project-URL: Changelog, https://github.com/bricksentry/bricksentry/blob/main/CHANGELOG.md
10
+ Author: Brahma
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: ai-agents,change-impact-analysis,ci,data-diff,data-engineering,data-quality,databricks,delta-lake,deployment-guardrails,impact-analysis,lineage,mcp,rollback,unity-catalog
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Database
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Classifier: Topic :: Software Development :: Testing
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: click>=8.1
28
+ Requires-Dist: pyyaml>=6.0
29
+ Provides-Extra: all
30
+ Requires-Dist: databricks-sdk>=0.30; extra == 'all'
31
+ Requires-Dist: duckdb>=1.0; extra == 'all'
32
+ Requires-Dist: mcp>=1.10; extra == 'all'
33
+ Provides-Extra: databricks
34
+ Requires-Dist: databricks-sdk>=0.30; extra == 'databricks'
35
+ Provides-Extra: dev
36
+ Requires-Dist: databricks-sdk>=0.30; extra == 'dev'
37
+ Requires-Dist: duckdb>=1.0; extra == 'dev'
38
+ Requires-Dist: mcp>=1.10; extra == 'dev'
39
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
40
+ Requires-Dist: pytest>=8; extra == 'dev'
41
+ Requires-Dist: ruff>=0.6; extra == 'dev'
42
+ Provides-Extra: duckdb
43
+ Requires-Dist: duckdb>=1.0; extra == 'duckdb'
44
+ Provides-Extra: mcp
45
+ Requires-Dist: mcp>=1.10; extra == 'mcp'
46
+ Description-Content-Type: text/markdown
47
+
1
48
  # Welcome to bricksentry
2
49
 
3
50
  <!-- mcp-name: io.github.bricksentry/bricksentry -->
@@ -375,6 +422,8 @@ Start from a ready-made policy instead of writing one:
375
422
 
376
423
  Use one directly with `policy: builtin:finance`, or write an editable copy with `bricksentry init --policy finance`. `bricksentry policies finance` prints it. Tags come from Unity Catalog, so tag your tables `pii` or `certified` for those templates to apply.
377
424
 
425
+ **The default policy is lenient on certified tables themselves.** It asks a human when a change reaches something *downstream* that's tagged `certified`, but a change *to* a certified table is treated like any other: doubling its totals only warns (`numeric-total-moved`), because many certified marts are rebuilt every day and their totals move for good reasons. If a certified table must not change quietly, use `builtin:certified` (any change to it needs a human, a type change blocks), `builtin:finance` for money tables, or tag the columns that matter so `changed_column_tag` rules apply.
426
+
378
427
  ### Policy conditions
379
428
 
380
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`
@@ -385,17 +434,34 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
385
434
 
386
435
  ## Permissions needed on Databricks
387
436
 
388
- - `CAN USE` on a SQL warehouse.
389
- - `SELECT` on the tables you assess and their candidates.
390
- - `SELECT` on `system.access.table_lineage` (and `system.access.column_lineage` for column-level impact), plus `system.information_schema` for owners, table tags and column tags. Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing.
391
- - `CREATE TABLE` on `sandbox_schema`, for `preview_write` and `check-last-change`. `check-last-change` also needs the table's Delta history (versions not yet removed by `VACUUM`).
437
+ Grant only what the features you use need. Everything is read-only except the scratch schema.
438
+
439
+ | Feature | Needs |
440
+ |---|---|
441
+ | Any check | `CAN USE` on a SQL warehouse |
442
+ | Data diff (`diff`, `assess`, pull-request checks) | `SELECT` on the tables and their candidates |
443
+ | `check-last-change`, the job task | `SELECT` on the table and its Delta history (versions not yet removed by `VACUUM`), and `CREATE TABLE` on `sandbox_schema` for two short-lived shallow clones |
444
+ | `preview_write` (agents) | `CREATE TABLE` on `sandbox_schema`; the write only ever runs on a clone there |
445
+ | Blast radius | `SELECT` on `system.access.table_lineage` |
446
+ | Column-level impact | `SELECT` on `system.access.column_lineage` |
447
+ | Owners and tags | `SELECT` on `system.information_schema` (tables, table tags, column tags) |
448
+
449
+ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing. A dedicated service principal with exactly these grants is the recommended setup for jobs and the MCP server.
450
+
451
+ ## What a check costs
452
+
453
+ The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries: a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
454
+
455
+ ## Audit trail
456
+
457
+ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 fingerprint of the policy rules that produced the verdict, and who triggered it (`BRICKSENTRY_ACTOR`, or the GitHub actor in GitHub Actions). They're in the JSON and in the footer of the pull-request report, so a verdict can be traced to the exact rules behind it. Assessments are saved as JSON under `assessment_store`; point it at a shared, access-controlled folder to keep a history.
392
458
 
393
459
  ## Known limits (v0.1.x)
394
460
 
395
461
  - **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.
396
462
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
397
463
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
398
- - **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.20 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 automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
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. The automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
399
465
 
400
466
  ## Roadmap
401
467
 
@@ -1,50 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: bricksentry
3
- Version: 0.1.22
4
- Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
5
- Project-URL: Homepage, https://bricksentry.org
6
- Project-URL: Documentation, https://bricksentry.org/docs
7
- Project-URL: Source, https://github.com/bricksentry/bricksentry
8
- Project-URL: Issues, https://github.com/bricksentry/bricksentry/issues
9
- Project-URL: Changelog, https://github.com/bricksentry/bricksentry/blob/main/CHANGELOG.md
10
- Author: Brahma
11
- License-Expression: Apache-2.0
12
- License-File: LICENSE
13
- Keywords: ai-agents,ci,data-diff,data-engineering,data-quality,databricks,delta-lake,impact-analysis,lineage,mcp,unity-catalog
14
- Classifier: Development Status :: 3 - Alpha
15
- Classifier: Intended Audience :: Developers
16
- Classifier: Operating System :: OS Independent
17
- Classifier: Programming Language :: Python :: 3
18
- Classifier: Programming Language :: Python :: 3.10
19
- Classifier: Programming Language :: Python :: 3.11
20
- Classifier: Programming Language :: Python :: 3.12
21
- Classifier: Programming Language :: Python :: 3.13
22
- Classifier: Topic :: Database
23
- Classifier: Topic :: Software Development :: Quality Assurance
24
- Classifier: Topic :: Software Development :: Testing
25
- Classifier: Typing :: Typed
26
- Requires-Python: >=3.10
27
- Requires-Dist: click>=8.1
28
- Requires-Dist: pyyaml>=6.0
29
- Provides-Extra: all
30
- Requires-Dist: databricks-sdk>=0.30; extra == 'all'
31
- Requires-Dist: duckdb>=1.0; extra == 'all'
32
- Requires-Dist: mcp>=1.10; extra == 'all'
33
- Provides-Extra: databricks
34
- Requires-Dist: databricks-sdk>=0.30; extra == 'databricks'
35
- Provides-Extra: dev
36
- Requires-Dist: databricks-sdk>=0.30; extra == 'dev'
37
- Requires-Dist: duckdb>=1.0; extra == 'dev'
38
- Requires-Dist: mcp>=1.10; extra == 'dev'
39
- Requires-Dist: pytest-cov>=5; extra == 'dev'
40
- Requires-Dist: pytest>=8; extra == 'dev'
41
- Requires-Dist: ruff>=0.6; extra == 'dev'
42
- Provides-Extra: duckdb
43
- Requires-Dist: duckdb>=1.0; extra == 'duckdb'
44
- Provides-Extra: mcp
45
- Requires-Dist: mcp>=1.10; extra == 'mcp'
46
- Description-Content-Type: text/markdown
47
-
48
1
  # Welcome to bricksentry
49
2
 
50
3
  <!-- mcp-name: io.github.bricksentry/bricksentry -->
@@ -422,6 +375,8 @@ Start from a ready-made policy instead of writing one:
422
375
 
423
376
  Use one directly with `policy: builtin:finance`, or write an editable copy with `bricksentry init --policy finance`. `bricksentry policies finance` prints it. Tags come from Unity Catalog, so tag your tables `pii` or `certified` for those templates to apply.
424
377
 
378
+ **The default policy is lenient on certified tables themselves.** It asks a human when a change reaches something *downstream* that's tagged `certified`, but a change *to* a certified table is treated like any other: doubling its totals only warns (`numeric-total-moved`), because many certified marts are rebuilt every day and their totals move for good reasons. If a certified table must not change quietly, use `builtin:certified` (any change to it needs a human, a type change blocks), `builtin:finance` for money tables, or tag the columns that matter so `changed_column_tag` rules apply.
379
+
425
380
  ### Policy conditions
426
381
 
427
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`
@@ -432,17 +387,34 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
432
387
 
433
388
  ## Permissions needed on Databricks
434
389
 
435
- - `CAN USE` on a SQL warehouse.
436
- - `SELECT` on the tables you assess and their candidates.
437
- - `SELECT` on `system.access.table_lineage` (and `system.access.column_lineage` for column-level impact), plus `system.information_schema` for owners, table tags and column tags. Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing.
438
- - `CREATE TABLE` on `sandbox_schema`, for `preview_write` and `check-last-change`. `check-last-change` also needs the table's Delta history (versions not yet removed by `VACUUM`).
390
+ Grant only what the features you use need. Everything is read-only except the scratch schema.
391
+
392
+ | Feature | Needs |
393
+ |---|---|
394
+ | Any check | `CAN USE` on a SQL warehouse |
395
+ | Data diff (`diff`, `assess`, pull-request checks) | `SELECT` on the tables and their candidates |
396
+ | `check-last-change`, the job task | `SELECT` on the table and its Delta history (versions not yet removed by `VACUUM`), and `CREATE TABLE` on `sandbox_schema` for two short-lived shallow clones |
397
+ | `preview_write` (agents) | `CREATE TABLE` on `sandbox_schema`; the write only ever runs on a clone there |
398
+ | Blast radius | `SELECT` on `system.access.table_lineage` |
399
+ | Column-level impact | `SELECT` on `system.access.column_lineage` |
400
+ | Owners and tags | `SELECT` on `system.information_schema` (tables, table tags, column tags) |
401
+
402
+ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable` warning (blast radius unknown) instead of guessing. A dedicated service principal with exactly these grants is the recommended setup for jobs and the MCP server.
403
+
404
+ ## What a check costs
405
+
406
+ The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries: a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
407
+
408
+ ## Audit trail
409
+
410
+ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 fingerprint of the policy rules that produced the verdict, and who triggered it (`BRICKSENTRY_ACTOR`, or the GitHub actor in GitHub Actions). They're in the JSON and in the footer of the pull-request report, so a verdict can be traced to the exact rules behind it. Assessments are saved as JSON under `assessment_store`; point it at a shared, access-controlled folder to keep a history.
439
411
 
440
412
  ## Known limits (v0.1.x)
441
413
 
442
414
  - **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.
443
415
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
444
416
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
445
- - **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.20 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 automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
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. The automated tests use DuckDB and a mocked SDK, so please [open an issue](https://github.com/bricksentry/bricksentry/issues) if something behaves differently on yours.
446
418
 
447
419
  ## Roadmap
448
420
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.24
@@ -287,7 +287,7 @@
287
287
  "source": [
288
288
  "## Next steps\n",
289
289
  "- **Check every change before it ships:** run the same check in CI on pull requests. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).\n",
290
- "- **Let AI agents check their own changes:** `uvx bricksentry-mcp`. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).\n",
290
+ "- **Let AI agents check their own changes:** `uvx bricksentry-mcp`, docs at <https://bricksentry.org/docs/agents>\n",
291
291
  "- **Get alerts:** set a Slack or Teams webhook and run `bricksentry test-alert`. See [bricksentry.org/docs/configuration](https://bricksentry.org/docs/configuration)."
292
292
  ]
293
293
  }
@@ -229,5 +229,5 @@ print("Share what it found:\nhttps://github.com/bricksentry/bricksentry/issues/n
229
229
  # MAGIC %md
230
230
  # MAGIC ## Next steps
231
231
  # MAGIC - **Check every change before it ships:** run the same check in CI on pull requests. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).
232
- # MAGIC - **Let AI agents check their own changes:** `uvx bricksentry-mcp`. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).
232
+ # MAGIC - **Let AI agents check their own changes:** `uvx bricksentry-mcp`, docs at <https://bricksentry.org/docs/agents>
233
233
  # MAGIC - **Get alerts:** set a Slack or Teams webhook and run `bricksentry test-alert`. See [bricksentry.org/docs/configuration](https://bricksentry.org/docs/configuration).
@@ -343,7 +343,7 @@
343
343
  "source": [
344
344
  "## Next steps\n",
345
345
  "- **In CI:** `bricksentry init` writes `bricksentry.yml` and `policy.yml`; add `bricksentry assess --from-git origin/main --comment` to your pull-request workflow. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).\n",
346
- "- **For AI agents:** `bricksentry mcp` exposes these same tools over MCP. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).\n",
346
+ "- **For AI agents:** `bricksentry mcp` exposes these same tools over MCP, docs at <https://bricksentry.org/docs/agents>\n",
347
347
  "- **Feedback and bugs:** [github.com/bricksentry/bricksentry/issues](https://github.com/bricksentry/bricksentry/issues)"
348
348
  ]
349
349
  }
@@ -257,5 +257,5 @@ agent_tools.set_sentry(None)
257
257
  # MAGIC %md
258
258
  # MAGIC ## Next steps
259
259
  # MAGIC - **In CI:** `bricksentry init` writes `bricksentry.yml` and `policy.yml`; add `bricksentry assess --from-git origin/main --comment` to your pull-request workflow. See [bricksentry.org/docs/ci](https://bricksentry.org/docs/ci).
260
- # MAGIC - **For AI agents:** `bricksentry mcp` exposes these same tools over MCP. See [bricksentry.org/docs/agents](https://bricksentry.org/docs/agents).
260
+ # MAGIC - **For AI agents:** `bricksentry mcp` exposes these same tools over MCP, docs at <https://bricksentry.org/docs/agents>
261
261
  # MAGIC - **Feedback and bugs:** [github.com/bricksentry/bricksentry/issues](https://github.com/bricksentry/bricksentry/issues)
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.22"
8
- description = "Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
7
+ version = "0.1.24"
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"
11
11
  license = "Apache-2.0"
@@ -13,6 +13,7 @@ authors = [{ name = "Brahma" }]
13
13
  keywords = [
14
14
  "databricks", "delta-lake", "unity-catalog", "data-engineering", "data-diff",
15
15
  "lineage", "impact-analysis", "ci", "mcp", "ai-agents", "data-quality",
16
+ "change-impact-analysis", "deployment-guardrails", "rollback",
16
17
  ]
17
18
  classifiers = [
18
19
  "Development Status :: 3 - Alpha",
@@ -8,12 +8,12 @@
8
8
  "source": "github"
9
9
  },
10
10
  "websiteUrl": "https://bricksentry.org",
11
- "version": "0.1.22",
11
+ "version": "0.1.24",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.22",
16
+ "version": "0.1.24",
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.22"
26
+ __version__ = "0.1.24"
@@ -3,8 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
6
7
  import re
7
8
  import uuid
9
+ from datetime import datetime, timezone
8
10
  from typing import Any
9
11
 
10
12
  from bricksentry.backends.base import Backend, make_backend
@@ -138,6 +140,10 @@ class Sentry:
138
140
  tables=results,
139
141
  verdict=Verdict.worst([t.verdict for t in results]),
140
142
  notify=sorted(notify),
143
+ created_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
144
+ bricksentry_version=_version(),
145
+ policy_sha256=self.policy.sha256,
146
+ triggered_by=_actor(),
141
147
  )
142
148
  self._assessments[a.id] = a
143
149
  self._save(a)
@@ -255,6 +261,22 @@ class Sentry:
255
261
  return self._diffs.get(table)
256
262
 
257
263
 
264
+ def _version() -> str:
265
+ from bricksentry import __version__ # imported late: bricksentry/__init__ imports this module
266
+
267
+ return __version__
268
+
269
+
270
+ def _actor() -> str | None:
271
+ """Who asked for the check: BRICKSENTRY_ACTOR if set, else the GitHub actor in
272
+ GitHub Actions. Nothing is read from the machine itself."""
273
+ if os.environ.get("BRICKSENTRY_ACTOR"):
274
+ return os.environ["BRICKSENTRY_ACTOR"].strip()[:200]
275
+ if os.environ.get("GITHUB_ACTOR"):
276
+ return "github:" + os.environ["GITHUB_ACTOR"].strip()[:200]
277
+ return None
278
+
279
+
258
280
  def _first_line(e: Exception, limit: int = 200) -> str:
259
281
  """A short, single-line error for verdict reasons and alerts."""
260
282
  text = (str(e).strip().splitlines() or [type(e).__name__])[0]
@@ -54,6 +54,22 @@ class Backend(ABC):
54
54
  backend has no cheap row hash, and the guard is skipped."""
55
55
  return None
56
56
 
57
+ def row_hash(self, columns: list[str]) -> str | None:
58
+ """SQL for a hash of one row's ``columns``; orders copies of a duplicated key
59
+ so identical copies pair up. ``None`` means unsupported (copies are paired in
60
+ no particular order)."""
61
+ return None
62
+
63
+ def exact_sum(self, expr: str, type_name: str) -> str:
64
+ """SUM that doesn't drift on large tables: decimals and integers are added as
65
+ DECIMAL(38, x), only floating-point columns as DOUBLE."""
66
+ t = type_name.lower()
67
+ if t.startswith(("decimal", "numeric")):
68
+ return f"SUM({expr})"
69
+ if t.startswith(("float", "double", "real")):
70
+ return f"SUM(CAST({expr} AS DOUBLE))"
71
+ return f"SUM(CAST({expr} AS DECIMAL(38, 0)))"
72
+
57
73
  @abstractmethod
58
74
  def days_ago(self, days: int) -> str:
59
75
  """SQL expression for the date ``days`` days ago."""
@@ -109,6 +109,9 @@ class DatabricksBackend(Backend):
109
109
  cols = ", ".join(self.quote(c) for c in columns)
110
110
  return f"SUM(CAST(xxhash64({cols}) AS DECIMAL(38, 0)))"
111
111
 
112
+ def row_hash(self, columns: list[str]) -> str | None:
113
+ return f"xxhash64({', '.join(self.quote(c) for c in columns)})"
114
+
112
115
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
113
116
  pre = f"{alias}." if alias else ""
114
117
  cols = ", ".join(f"{pre}{self.quote(k)}" for k in keys)
@@ -38,6 +38,9 @@ class DuckDBBackend(Backend):
38
38
  cols = ", ".join(self.quote(c) for c in columns)
39
39
  return f"SUM(CAST(hash({cols}) AS HUGEINT))"
40
40
 
41
+ def row_hash(self, columns: list[str]) -> str | None:
42
+ return f"hash({', '.join(self.quote(c) for c in columns)})"
43
+
41
44
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
42
45
  pre = f"{alias}." if alias else ""
43
46
  cols = ", ".join(f"{pre}{self.quote(k)}" for k in keys)
@@ -395,7 +395,7 @@ def policies(name):
395
395
  def test_alert(verdict, owner, config_path):
396
396
  """Send a clearly labelled sample alert to your Slack / Teams webhooks.
397
397
 
398
- Reads no tables. Exits 1 if a webhook failed or none is configured."""
398
+ Reads no tables. Exits 1 if a webhook failed or was skipped, 2 if none is configured."""
399
399
  from bricksentry.notify import NotifySettings, sample_assessment, send
400
400
 
401
401
  cfg = _config(config_path)
@@ -114,14 +114,50 @@ def _diff(
114
114
  # A marker column says whether a joined row exists on each side. Testing the key
115
115
  # for NULL instead would count a NULL-key row as both added and removed.
116
116
  present = q("__bs_present")
117
+ occ = q("__bs_occ")
118
+ kc = ", ".join(q(k) for k in keys)
117
119
 
118
- def side(tbl: str, alias: str) -> str:
119
- where = f" WHERE {backend.sample_predicate(keys, sample_pct)}" if sample_pct else ""
120
- return f"{alias} AS (SELECT *, 1 AS {present} FROM {backend.qualified(tbl)}{where})"
120
+ def sample_where() -> str:
121
+ return f" WHERE {backend.sample_predicate(keys, sample_pct)}" if sample_pct else ""
121
122
 
122
- ctes = f"WITH {side(base, 'b_src')}, {side(candidate, 'c_src')}"
123
+ def raw_cte(tbl: str, alias: str) -> str:
124
+ return f"{alias} AS (SELECT *, 1 AS {present} FROM {backend.qualified(tbl)}{sample_where()})"
125
+
126
+ # Duplicate keys first: a key that appears more than once (including many NULL
127
+ # keys, which match each other) would multiply rows in the key join.
128
+ raw_ctes = f"WITH {raw_cte(base, 'b_src')}, {raw_cte(candidate, 'c_src')}"
129
+
130
+ def dupes(tbl_cte: str) -> int:
131
+ sql = (
132
+ f"{raw_ctes} SELECT COUNT(*) AS n FROM "
133
+ f"(SELECT {kc} FROM {tbl_cte} GROUP BY {kc} HAVING COUNT(*) > 1) d"
134
+ )
135
+ return int(backend.scalar(sql) or 0)
136
+
137
+ dup_b, dup_c = dupes("b_src"), dupes("c_src")
138
+ notes: list[str] = []
139
+ pair_copies = bool(dup_b or dup_c)
140
+ if pair_copies:
141
+ # Number the copies of each key and match copy n to copy n, so the join stays
142
+ # one to one: an extra copy counts as added (or removed), not as a second match.
143
+ # Ordering by a row hash pairs identical copies with each other.
144
+ order = backend.row_hash([c for c in b_cols if c in c_cols and c not in schema.type_changed]) or kc
145
+
146
+ def side(tbl: str, alias: str) -> str:
147
+ return (f"{alias} AS (SELECT *, 1 AS {present}, ROW_NUMBER() OVER (PARTITION BY {kc} "
148
+ f"ORDER BY {order}) AS {occ} FROM {backend.qualified(tbl)}{sample_where()})")
149
+
150
+ ctes = f"WITH {side(base, 'b_src')}, {side(candidate, 'c_src')}"
151
+ notes.append(
152
+ "Some keys appear more than once, so copies of the same key were paired one to one "
153
+ "(an extra copy counts as added or removed, not as another match)."
154
+ )
155
+ else:
156
+ ctes = raw_ctes
123
157
  # Null-safe key match: a NULL key in production matches a NULL key in the candidate.
124
158
  join_on = " AND ".join(f"b.{q(k)} IS NOT DISTINCT FROM c.{q(k)}" for k in keys)
159
+ if pair_copies:
160
+ join_on += f" AND b.{occ} = c.{occ}"
125
161
  in_b, in_c = f"b.{present} IS NOT NULL", f"c.{present} IS NOT NULL"
126
162
 
127
163
  def cmp(col: str) -> str:
@@ -149,27 +185,19 @@ def _diff(
149
185
  )
150
186
  j = backend.query(join_sql)[0]
151
187
 
152
- # Row counts, nulls, numeric sums per side.
188
+ # Row counts, nulls, numeric sums per side. Sums are exact for decimals and integers.
153
189
  def profile(tbl_cte: str, cols: dict[str, str]) -> dict:
154
190
  any_null_key = " OR ".join(f"{q(k)} IS NULL" for k in keys)
155
191
  parts = ["COUNT(*) AS n_rows", f"SUM(CASE WHEN {any_null_key} THEN 1 ELSE 0 END) AS null_keys"]
156
192
  for i, col in enumerate(common):
157
193
  parts.append(f"SUM(CASE WHEN {q(col)} IS NULL THEN 1 ELSE 0 END) AS nul_{i}")
158
194
  if backend.is_numeric(cols[col]):
159
- parts.append(f"SUM(CAST({q(col)} AS DOUBLE)) AS sum_{i}")
160
- return backend.query(f"{ctes} SELECT {', '.join(parts)} FROM {tbl_cte}")[0]
195
+ parts.append(f"{backend.exact_sum(q(col), cols[col])} AS sum_{i}")
196
+ return backend.query(f"{raw_ctes} SELECT {', '.join(parts)} FROM {tbl_cte}")[0]
161
197
 
162
198
  pb = profile("b_src", b_cols)
163
199
  pc = profile("c_src", c_cols)
164
200
 
165
- def dupes(tbl_cte: str) -> int:
166
- kc = ", ".join(q(k) for k in keys)
167
- sql = (
168
- f"{ctes} SELECT COUNT(*) AS n FROM "
169
- f"(SELECT {kc} FROM {tbl_cte} GROUP BY {kc} HAVING COUNT(*) > 1) d"
170
- )
171
- return int(backend.scalar(sql) or 0)
172
-
173
201
  col_changes: list[ColumnChange] = []
174
202
  for i, col in enumerate(common):
175
203
  changed = int(j.get(f"chg_{i}") or 0)
@@ -225,12 +253,13 @@ def _diff(
225
253
  unchanged_rows=int(j.get("unchanged_rows") or 0),
226
254
  schema=schema,
227
255
  columns=col_changes,
228
- duplicate_keys_base=dupes("b_src"),
229
- duplicate_keys_candidate=dupes("c_src"),
256
+ duplicate_keys_base=dup_b,
257
+ duplicate_keys_candidate=dup_c,
230
258
  null_keys_base=int(pb.get("null_keys") or 0),
231
259
  null_keys_candidate=int(pc.get("null_keys") or 0),
232
260
  segments=segments,
233
261
  sampled_pct=sample_pct,
262
+ notes=notes,
234
263
  )
235
264
 
236
265
 
@@ -177,6 +177,29 @@ def _ensure_scratch(db: Any, schema: str) -> None:
177
177
  raise
178
178
 
179
179
 
180
+ _NOT_FOUND = re.compile(
181
+ r"TABLE_OR_VIEW_NOT_FOUND|cannot be found|does not exist|not found|no such table", re.IGNORECASE)
182
+
183
+
184
+ def _read_history(db: Any, table: str, limit: int) -> list[dict[str, Any]]:
185
+ """DESCRIBE HISTORY, with a one-line message for the common mistakes instead of the
186
+ engine's full error (which echoes the SQL and adds unrelated hints)."""
187
+ try:
188
+ return db.history(table, limit)
189
+ except Exception as e:
190
+ msg = str(e)
191
+ if _NOT_FOUND.search(msg):
192
+ raise ValueError(
193
+ f"Table {table} not found. Check the catalog, schema and table name (they must match "
194
+ "Unity Catalog exactly) and that you have SELECT on it.") from None
195
+ if "PERMISSION_DENIED" in msg or "INSUFFICIENT_PERMISSIONS" in msg:
196
+ raise ValueError(
197
+ f"No permission to read {table}: check-last-change needs SELECT on the table "
198
+ "(and its Delta history).") from None
199
+ first = (msg.strip().splitlines() or [type(e).__name__])[0][:300]
200
+ raise RuntimeError(f"Could not read the history of {table}: {first}") from None
201
+
202
+
180
203
  def check_change(
181
204
  sentry: Sentry,
182
205
  table: str,
@@ -195,7 +218,7 @@ def check_change(
195
218
  if not _NAME.fullmatch(table):
196
219
  raise ValueError(f"table must be schema.table or catalog.schema.table; got {table!r}")
197
220
 
198
- history = db.history(table, history_limit)
221
+ history = _read_history(db, table, history_limit)
199
222
  change = pick_change(table, history, version=version, since=since)
200
223
  keys = keys or sentry.config.spec(table).keys or db.primary_key(table)
201
224
  if not keys:
@@ -17,6 +17,7 @@ import argparse
17
17
  import json
18
18
  import os
19
19
  import sys
20
+ import warnings
20
21
  from datetime import datetime, timedelta, timezone
21
22
  from typing import Any
22
23
 
@@ -185,6 +186,10 @@ def main(argv: list[str] | None = None) -> None:
185
186
  even ``SystemExit(0)``, as a task error, so a clean run must simply return."""
186
187
  code = run(argv)
187
188
  if code:
189
+ # In a spark_python_task the script runs inside IPython, which follows a
190
+ # SystemExit with "To exit: use 'exit', 'quit', or Ctrl-D." at the end of the
191
+ # task log. The exit code is what matters, so keep that line out of the log.
192
+ warnings.filterwarnings("ignore", message="To exit: use")
188
193
  sys.exit(code)
189
194
 
190
195
 
@@ -91,6 +91,7 @@ class TableDiff:
91
91
  sampled_pct: float | None = None
92
92
  sample_note: str | None = None
93
93
  error: str | None = None
94
+ notes: list[str] = field(default_factory=list)
94
95
 
95
96
  def _pct(self, n: int) -> float:
96
97
  denom = max(self.base_rows, 1)
@@ -260,6 +261,11 @@ class Assessment:
260
261
  tables: list[TableAssessment]
261
262
  verdict: Verdict
262
263
  notify: list[str] = field(default_factory=list)
264
+ # Audit trail: when, with which bricksentry and policy, and who asked.
265
+ created_at: str | None = None # UTC, ISO 8601
266
+ bricksentry_version: str | None = None
267
+ policy_sha256: str | None = None # fingerprint of the policy rules that produced the verdict
268
+ triggered_by: str | None = None # BRICKSENTRY_ACTOR, or the GitHub actor in GitHub Actions
263
269
 
264
270
  @property
265
271
  def hits(self) -> list[RuleHit]:
@@ -272,6 +278,10 @@ class Assessment:
272
278
  "risk_tier": self.verdict.risk_tier,
273
279
  "safe_to_ship": self.verdict in (Verdict.PASS, Verdict.WARN),
274
280
  "notify": self.notify,
281
+ "created_at": self.created_at,
282
+ "bricksentry_version": self.bricksentry_version,
283
+ "policy_sha256": self.policy_sha256,
284
+ "triggered_by": self.triggered_by,
275
285
  "rule_hits": [h.to_dict() for h in self.hits],
276
286
  "tables": [t.to_dict() for t in self.tables],
277
287
  }
@@ -283,4 +293,8 @@ class Assessment:
283
293
  tables=[TableAssessment.from_dict(t) for t in d.get("tables") or []],
284
294
  verdict=Verdict(d["verdict"]),
285
295
  notify=list(d.get("notify") or []),
296
+ created_at=d.get("created_at"),
297
+ bricksentry_version=d.get("bricksentry_version"),
298
+ policy_sha256=d.get("policy_sha256"),
299
+ triggered_by=d.get("triggered_by"),
286
300
  )
@@ -40,6 +40,8 @@ All conditions inside one ``when`` must hold (AND). Use several rules for OR.
40
40
  from __future__ import annotations
41
41
 
42
42
  import fnmatch
43
+ import hashlib
44
+ import json
43
45
  from typing import Any
44
46
 
45
47
  from bricksentry.measures import is_measure
@@ -104,6 +106,10 @@ def _tag_label(want: Any) -> str:
104
106
  class Policy:
105
107
  def __init__(self, spec: dict[str, Any] | None = None):
106
108
  spec = spec if spec is not None else DEFAULT_POLICY
109
+ # A fingerprint of the rules, recorded on every assessment so a verdict can be
110
+ # traced to the exact policy that produced it.
111
+ canonical = json.dumps(spec, sort_keys=True, default=str, separators=(",", ":"))
112
+ self.sha256 = hashlib.sha256(canonical.encode()).hexdigest()
107
113
  self.default = Verdict(spec.get("default", "pass"))
108
114
  self.notify_on = Verdict(spec.get("notify_owners_on", "needs_human"))
109
115
  self.rules = spec.get("rules") or []
@@ -38,7 +38,13 @@ def to_markdown(a: Assessment, max_downstream: int = 15) -> str:
38
38
  lines.append("")
39
39
  for t in a.tables:
40
40
  lines += _table_section(t, max_downstream)
41
- lines += ["", "<sub>Generated by bricksentry. Verdicts come from policy rules, not from an LLM.</sub>"]
41
+ audit = " · ".join(x for x in (
42
+ f"bricksentry {a.bricksentry_version}" if a.bricksentry_version else "bricksentry",
43
+ f"policy `{a.policy_sha256[:12]}`" if a.policy_sha256 else "",
44
+ a.created_at.replace("T", " ").replace("+00:00", " UTC") if a.created_at else "",
45
+ f"triggered by {a.triggered_by}" if a.triggered_by else "",
46
+ ) if x)
47
+ lines += ["", f"<sub>Generated by {audit}. Verdicts come from policy rules, not from an LLM.</sub>"]
42
48
  return "\n".join(lines)
43
49
 
44
50
 
@@ -53,6 +59,7 @@ def _table_section(t: TableAssessment, max_downstream: int) -> list[str]:
53
59
  f"{d.changed_rows:,} | {d.unchanged_rows:,} |",
54
60
  "",
55
61
  ]
62
+ out += [f"> {_esc(n)}" for n in d.notes] + ([""] if d.notes else [])
56
63
  changed_cols = [c for c in d.columns if c.changed_rows or (c.sum_change_pct and abs(c.sum_change_pct) > 0.01)]
57
64
  if changed_cols:
58
65
  out += ["<details><summary>Column changes</summary>", "",
@@ -86,10 +86,10 @@
86
86
  },
87
87
  "bricksentry_version": {
88
88
  "type": "string",
89
- "default": "0.1.22",
89
+ "default": "0.1.24",
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.22.",
92
+ "pattern_match_failure_message": "Use a version like 0.1.24.",
93
93
  "order": 10
94
94
  }
95
95
  },
@@ -107,7 +107,9 @@ def test_check_change_end_to_end():
107
107
  a, change = sentry(db).check_change("sales.orders")
108
108
  t = a.tables[0]
109
109
  assert change.version == 3 and change.base_version == 2
110
- assert t.diff.added_rows == 0 and t.diff.base_rows == 1800 and t.diff.candidate_rows == 1804
110
+ # The 4 duplicated copies count as added (0.1.23); before, each copy was counted
111
+ # as a second match of the same key, which reported 0 added for a table that grew.
112
+ assert t.diff.added_rows == 4 and t.diff.base_rows == 1800 and t.diff.candidate_rows == 1804
111
113
  assert t.diff.duplicate_keys_candidate > 0
112
114
  assert a.verdict.value == "block" # duplicate keys
113
115
  assert t.rollback == 'RESTORE TABLE "sales"."orders" TO VERSION AS OF 2'
@@ -0,0 +1,195 @@
1
+ """0.1.23: exact totals, one-to-one matching of duplicated keys, and an audit trail
2
+ on every assessment."""
3
+
4
+ from bricksentry import Config, Sentry, __version__
5
+ from bricksentry.backends.databricks_backend import DatabricksBackend
6
+ from bricksentry.diff import diff_tables
7
+ from bricksentry.lineage import StaticLineage
8
+ from bricksentry.models import Assessment
9
+ from bricksentry.policy import Policy
10
+ from bricksentry.report import to_markdown
11
+
12
+
13
+ # --- exact totals ----------------------------------------------------------------
14
+ def test_decimal_totals_are_exact(backend):
15
+ backend.execute("CREATE SCHEMA m")
16
+ backend.execute("CREATE TABLE m.base AS SELECT i AS id, CAST(0.10 AS DECIMAL(18, 2)) AS amount "
17
+ "FROM range(1, 1000001) t(i)")
18
+ backend.execute("CREATE TABLE m.cand AS SELECT * FROM m.base")
19
+ d = diff_tables(backend, "m.base", "m.cand", ["id"])
20
+ amount = d.columns[0]
21
+ # Adding 0.1 a million times as DOUBLE drifts (100000.00000133...); as DECIMAL it doesn't.
22
+ assert amount.base_sum == 100000.0 and amount.candidate_sum == 100000.0
23
+ assert amount.sum_change_pct == 0
24
+
25
+
26
+ def test_sum_sql_by_type():
27
+ b = DatabricksBackend(warehouse_id="wh", client=object())
28
+ assert b.exact_sum("`a`", "decimal(18,2)") == "SUM(`a`)"
29
+ assert b.exact_sum("`a`", "bigint") == "SUM(CAST(`a` AS DECIMAL(38, 0)))" # no BIGINT overflow
30
+ assert b.exact_sum("`a`", "double") == "SUM(CAST(`a` AS DOUBLE))"
31
+ assert b.row_hash(["a", "b"]) == "xxhash64(`a`, `b`)"
32
+
33
+
34
+ # --- duplicated keys are matched one to one --------------------------------------
35
+ def test_many_null_keys_do_not_multiply(backend):
36
+ backend.execute("CREATE SCHEMA n")
37
+ backend.execute("CREATE TABLE n.base AS SELECT CASE WHEN i <= 2000 THEN NULL ELSE i END AS id, i AS v "
38
+ "FROM range(1, 3001) t(i)")
39
+ backend.execute("CREATE TABLE n.cand AS SELECT * FROM n.base")
40
+ d = diff_tables(backend, "n.base", "n.cand", ["id"])
41
+ # 2,000 NULL keys on each side used to join into 4,000,000 pairs.
42
+ assert (d.added_rows, d.removed_rows, d.changed_rows, d.unchanged_rows) == (0, 0, 0, 3000)
43
+ assert d.null_keys_base == 2000 and d.is_identical
44
+ assert d.notes and "paired one to one" in d.notes[0]
45
+
46
+
47
+ def test_a_new_copy_of_a_key_counts_as_added(backend):
48
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders "
49
+ "UNION ALL SELECT order_id, region, amount, status FROM sales.orders WHERE order_id <= 3")
50
+ d = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"])
51
+ assert (d.added_rows, d.removed_rows, d.changed_rows, d.unchanged_rows) == (3, 0, 0, 1000)
52
+ assert d.duplicate_keys_candidate == 3
53
+
54
+
55
+ def test_changed_copy_of_a_duplicated_key(backend):
56
+ backend.execute("CREATE SCHEMA k")
57
+ backend.execute("CREATE TABLE k.base AS SELECT * FROM (VALUES (1, 'a'), (1, 'b'), (2, 'c')) t(id, v)")
58
+ backend.execute("CREATE TABLE k.cand AS SELECT * FROM (VALUES (1, 'a'), (1, 'z'), (2, 'c')) t(id, v)")
59
+ d = diff_tables(backend, "k.base", "k.cand", ["id"])
60
+ assert d.base_rows == d.candidate_rows == 3
61
+ assert d.added_rows == d.removed_rows == 0
62
+ assert d.changed_rows == 1 and d.unchanged_rows == 2
63
+
64
+
65
+ def test_no_note_without_duplicates(backend):
66
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
67
+ assert diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"]).notes == []
68
+
69
+
70
+ # --- audit trail ------------------------------------------------------------------
71
+ def _sentry(backend, policy=None):
72
+ cfg = Config.from_dict({"assessment_store": False, "policy": policy,
73
+ "tables": {"sales.orders": {"keys": ["order_id"]}}})
74
+ return Sentry(cfg, backend=backend, lineage=StaticLineage({}))
75
+
76
+
77
+ def test_assessment_records_when_what_and_who(backend, monkeypatch):
78
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
79
+ monkeypatch.delenv("GITHUB_ACTOR", raising=False)
80
+ monkeypatch.setenv("BRICKSENTRY_ACTOR", "nightly-orders-job")
81
+ a = _sentry(backend).assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
82
+ assert a.created_at and a.created_at.endswith("+00:00")
83
+ assert a.bricksentry_version == __version__
84
+ assert a.policy_sha256 == Policy().sha256 and len(a.policy_sha256) == 64
85
+ assert a.triggered_by == "nightly-orders-job"
86
+
87
+ d = a.to_dict()
88
+ assert {"created_at", "bricksentry_version", "policy_sha256", "triggered_by"} <= set(d)
89
+ again = Assessment.from_dict(d)
90
+ assert (again.created_at, again.policy_sha256, again.triggered_by) == (
91
+ a.created_at, a.policy_sha256, "nightly-orders-job")
92
+
93
+ md = to_markdown(a)
94
+ assert f"bricksentry {__version__}" in md and f"policy `{a.policy_sha256[:12]}`" in md
95
+ assert "triggered by nightly-orders-job" in md and " UTC" in md
96
+
97
+
98
+ def test_github_actor_and_nobody(backend, monkeypatch):
99
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
100
+ monkeypatch.delenv("BRICKSENTRY_ACTOR", raising=False)
101
+ monkeypatch.setenv("GITHUB_ACTOR", "octocat")
102
+ a = _sentry(backend).assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
103
+ assert a.triggered_by == "github:octocat"
104
+ monkeypatch.delenv("GITHUB_ACTOR")
105
+ a = _sentry(backend).assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
106
+ assert a.triggered_by is None
107
+ assert "triggered by" not in to_markdown(a)
108
+
109
+
110
+ def test_policy_fingerprint_changes_with_the_rules():
111
+ a = Policy({"rules": [{"name": "x", "when": {"duplicate_keys": True}, "then": "block"}]})
112
+ b = Policy({"rules": [{"name": "x", "when": {"duplicate_keys": True}, "then": "warn"}]})
113
+ c = Policy({"rules": [{"then": "block", "when": {"duplicate_keys": True}, "name": "x"}]}) # same, reordered
114
+ assert a.sha256 != b.sha256
115
+ assert a.sha256 == c.sha256
116
+
117
+
118
+ def test_old_saved_assessments_still_load():
119
+ old = {"id": "abc", "verdict": "pass", "tables": [], "notify": []}
120
+ a = Assessment.from_dict(old)
121
+ assert a.created_at is None and a.policy_sha256 is None
122
+
123
+
124
+ # --- friendly errors for a mistyped table (found in a live test of 0.1.23) ---------
125
+ class _HistoryFails:
126
+ """A Delta-like backend whose DESCRIBE HISTORY raises the given engine error."""
127
+
128
+ name = "fake"
129
+ supports_time_travel = True
130
+
131
+ def __init__(self, message):
132
+ self.message = message
133
+
134
+ def history(self, table, limit=50):
135
+ raise RuntimeError(self.message)
136
+
137
+
138
+ def _check(message):
139
+ import pytest
140
+
141
+ from bricksentry.history import _read_history
142
+
143
+ with pytest.raises((ValueError, RuntimeError)) as e:
144
+ _read_history(_HistoryFails(message), "main.hr.employes", 50)
145
+ return e.value
146
+
147
+
148
+ def test_typo_in_table_name_is_one_clear_line():
149
+ raw = ("[TABLE_OR_VIEW_NOT_FOUND] The table or view `main`.`hr`.`employes` cannot be found. "
150
+ "Verify the spelling and correctness of the schema and catalog.\nIf you did not qualify the "
151
+ "name with a schema, verify the current_schema() output, or qualify the name with the correct "
152
+ "schema and catalog.\nTo tolerate the error on drop use DROP VIEW IF EXISTS or DROP TABLE IF "
153
+ "EXISTS. SQLSTATE: 42P01; line 1 pos 17;\n'DescribeDeltaHistory ...")
154
+ e = _check(raw)
155
+ assert isinstance(e, ValueError)
156
+ assert str(e).startswith("Table main.hr.employes not found.")
157
+ assert "DROP VIEW" not in str(e) and "\n" not in str(e)
158
+
159
+
160
+ def test_permission_and_other_errors():
161
+ e = _check("[INSUFFICIENT_PERMISSIONS] User does not have SELECT on table")
162
+ assert isinstance(e, ValueError) and "No permission to read main.hr.employes" in str(e)
163
+ e = _check("something odd happened\nwith a long second line")
164
+ assert isinstance(e, RuntimeError)
165
+ assert str(e) == "Could not read the history of main.hr.employes: something odd happened"
166
+
167
+
168
+ def test_job_task_reports_a_typo_cleanly():
169
+ from bricksentry.job import run
170
+
171
+ lines = []
172
+ raw = ("[TABLE_OR_VIEW_NOT_FOUND] The table or view `main`.`hr`.`employes` cannot be found.\n"
173
+ "To tolerate the error on drop use DROP VIEW IF EXISTS. SQLSTATE: 42P01")
174
+ code = run(["--tables", "main.hr.employes", "--key", "id"], backend=_HistoryFails(raw), out=lines.append)
175
+ assert code == 2
176
+ err = [ln for ln in lines if "ERROR" in ln]
177
+ assert err == ["main.hr.employes: ERROR Table main.hr.employes not found. Check the catalog, schema and "
178
+ "table name (they must match Unity Catalog exactly) and that you have SELECT on it."]
179
+
180
+
181
+ def test_job_main_exits_without_the_ipython_exit_hint(monkeypatch):
182
+ import warnings
183
+
184
+ import pytest
185
+
186
+ from bricksentry import job
187
+
188
+ monkeypatch.setattr(job, "run", lambda argv=None: 1)
189
+ with warnings.catch_warnings(record=True) as caught:
190
+ warnings.simplefilter("default")
191
+ with pytest.raises(SystemExit) as e:
192
+ job.main([])
193
+ warnings.warn("To exit: use 'exit', 'quit', or Ctrl-D.", UserWarning, stacklevel=2) # IPython's hint
194
+ assert e.value.code == 1
195
+ assert not [w for w in caught if "To exit" in str(w.message)]
@@ -1 +0,0 @@
1
- bricksentry[databricks,mcp]==0.1.22
File without changes
File without changes
File without changes
File without changes