bricksentry 0.1.3__tar.gz → 0.1.4__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 (45) hide show
  1. {bricksentry-0.1.3 → bricksentry-0.1.4}/.gitignore +3 -0
  2. {bricksentry-0.1.3 → bricksentry-0.1.4}/CHANGELOG.md +7 -0
  3. {bricksentry-0.1.3 → bricksentry-0.1.4}/PKG-INFO +60 -16
  4. {bricksentry-0.1.3 → bricksentry-0.1.4}/README.md +57 -15
  5. {bricksentry-0.1.3 → bricksentry-0.1.4}/pyproject.toml +22 -2
  6. {bricksentry-0.1.3 → bricksentry-0.1.4}/scripts/build_notebook.py +3 -3
  7. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/__init__.py +1 -1
  8. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/assess.py +30 -1
  9. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/backends/base.py +7 -0
  10. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/backends/databricks_backend.py +5 -1
  11. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/backends/duckdb_backend.py +5 -1
  12. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/config.py +18 -2
  13. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/demo.py +1 -1
  14. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/diff.py +50 -0
  15. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/explain.py +2 -0
  16. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/models.py +48 -2
  17. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/conftest.py +6 -0
  18. bricksentry-0.1.4/tests/test_sample_guard_and_store.py +84 -0
  19. {bricksentry-0.1.3 → bricksentry-0.1.4}/CONTRIBUTING.md +0 -0
  20. {bricksentry-0.1.3 → bricksentry-0.1.4}/LICENSE +0 -0
  21. {bricksentry-0.1.3 → bricksentry-0.1.4}/SECURITY.md +0 -0
  22. {bricksentry-0.1.3 → bricksentry-0.1.4}/action.yml +0 -0
  23. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/databricks/bricksentry.yml +0 -0
  24. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  25. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/databricks/bricksentry_quickstart.py +0 -0
  26. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/databricks/github-workflow.yml +0 -0
  27. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/databricks/policy.yml +0 -0
  28. {bricksentry-0.1.3 → bricksentry-0.1.4}/examples/demo/agent_loop_demo.py +0 -0
  29. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/agent_tools.py +0 -0
  30. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/backends/__init__.py +0 -0
  31. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/changes.py +0 -0
  32. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/cli.py +0 -0
  33. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/github.py +0 -0
  34. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/lineage.py +0 -0
  35. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/mcp_server.py +0 -0
  36. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/policy.py +0 -0
  37. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/preview.py +0 -0
  38. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/py.typed +0 -0
  39. {bricksentry-0.1.3 → bricksentry-0.1.4}/src/bricksentry/report.py +0 -0
  40. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_assess_policy.py +0 -0
  41. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_databricks_and_uc.py +0 -0
  42. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_demo.py +0 -0
  43. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_diff.py +0 -0
  44. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_notebook.py +0 -0
  45. {bricksentry-0.1.3 → bricksentry-0.1.4}/tests/test_preview_agents.py +0 -0
@@ -7,3 +7,6 @@ build/
7
7
  *.duckdb
8
8
  bricksentry-report.md
9
9
  bricksentry-result.json
10
+ .coverage
11
+ coverage.xml
12
+ .ruff_cache/
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4 (2026-11-10)
4
+
5
+ From a second end-to-end run on Databricks serverless against a 2-million-row table:
6
+
7
+ - Fix: a sampled diff (`sample_pct`) could report "no change" when the change sat outside the sample, for example one deleted row in 2 million at a 10% sample. A full-table checksum now guards every sampled diff: if the sample looks identical but the tables differ, the diff re-runs on all rows and says so in the summary (`sample_note`). Identical tables stay sampled and cheap. Turn it off with `sample_guard: false`.
8
+ - Fix: `explain_diff` and `safe_to_ship` returned "unknown assessment id" when called from a different `Sentry` instance or process. Assessments are now saved as JSON (default `~/.bricksentry/assessments`, or `assessment_store:` in bricksentry.yml, or env `BRICKSENTRY_STORE`) and loaded by id. Set `assessment_store: false` to keep them in memory only.
9
+
3
10
  ## 0.1.3 (2026-11-10)
4
11
 
5
12
  - Blast radius no longer lists bricksentry's own `preview_write` clones, or tables that Unity Catalog lineage remembers but that no longer exist (when `information_schema` can confirm it). Before, every preview added a stale downstream entry. New lineage settings: `exclude` (name patterns, default `["*__preview_*"]`) and `exclude_dropped` (default true).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
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
5
  Project-URL: Homepage, https://bricksentry.org
6
6
  Project-URL: Documentation, https://bricksentry.org/docs
@@ -36,20 +36,28 @@ Provides-Extra: dev
36
36
  Requires-Dist: databricks-sdk>=0.30; extra == 'dev'
37
37
  Requires-Dist: duckdb>=1.0; extra == 'dev'
38
38
  Requires-Dist: mcp>=1.10; extra == 'dev'
39
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
39
40
  Requires-Dist: pytest>=8; extra == 'dev'
41
+ Requires-Dist: ruff>=0.6; extra == 'dev'
40
42
  Provides-Extra: duckdb
41
43
  Requires-Dist: duckdb>=1.0; extra == 'duckdb'
42
44
  Provides-Extra: mcp
43
45
  Requires-Dist: mcp>=1.10; extra == 'mcp'
44
46
  Description-Content-Type: text/markdown
45
47
 
46
- # bricksentry
48
+ # Welcome to bricksentry
47
49
 
48
- [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![CI](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
50
+ [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
49
51
 
50
- ***Change-safety for Databricks pipelines and the AI agents that edit them.***
52
+ ***The safety check for data changes in the AI era.***
51
53
 
52
- **Website and docs: [bricksentry.org](https://bricksentry.org)**
54
+ Change-safety for Databricks pipelines and the AI agents that edit them: know what a change does to your data before it ships.
55
+
56
+ **[Try it in 30 seconds](#try-it-in-30-seconds-no-databricks-needed)** · **[Run the Databricks notebook](#run-it-in-your-databricks-workspace)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
57
+
58
+ Built by Brahmareddy, Databricks Champion. Open source under Apache-2.0.
59
+
60
+ *Why the name?* Bricks plus entry. Your tables and pipelines are the bricks of the lakehouse, and every change to them is an entry. bricksentry checks each entry, reports what it does, and stands guard before it lands.
53
61
 
54
62
  ## Try it in 30 seconds (no Databricks needed)
55
63
 
@@ -62,15 +70,12 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
62
70
 
63
71
  ![bricksentry demo: an agent's change is previewed, blocked for duplicate keys, then routed to the table owners](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
64
72
 
65
- ### Or run it in your Databricks workspace
73
+ ## Run it in your Databricks workspace
66
74
 
67
- The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
68
-
69
- In Databricks: **Workspace → Import → URL**, and paste:
75
+ > **Databricks quickstart notebook:** in your workspace, go to **Workspace → Import → URL** and paste
76
+ > `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py`
70
77
 
71
- ```
72
- https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py
73
- ```
78
+ The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
74
79
 
75
80
  You need a SQL warehouse, `CREATE TABLE` on the schema you pick, and `SELECT` on `system.access.table_lineage` for the blast radius. A Jupyter copy is in [`bricksentry_quickstart.ipynb`](examples/databricks/bricksentry_quickstart.ipynb).
76
81
 
@@ -119,7 +124,8 @@ Designed for agents:
119
124
  - **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
120
125
  - **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements.
121
126
  - **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
122
- - **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window.
127
+ - **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window. A full-table checksum guards the sample: if the sample shows no change but the tables differ, the diff re-runs on every row, so a one-row change can't slip through.
128
+ - **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
123
129
 
124
130
  The same tools are plain Python functions in `bricksentry.agent_tools`, so you can use them from LangGraph, the OpenAI Agents SDK or the Databricks Agent Framework without MCP.
125
131
 
@@ -190,7 +196,8 @@ s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sal
190
196
  backend: {type: databricks, warehouse_id: abc123} # auth: standard Databricks SDK chain
191
197
  sandbox_schema: main.bricksentry_sandbox
192
198
  candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
193
- sample_pct: 10
199
+ sample_pct: 10 # sample_guard re-checks the whole table (on by default)
200
+ assessment_store: ~/.bricksentry/assessments # or false to keep assessments in memory
194
201
  lineage: {type: databricks, depth: 3, lookback_days: 90} # also: exclude, exclude_dropped
195
202
  tables:
196
203
  main.sales.orders:
@@ -200,6 +207,37 @@ tables:
200
207
  policy: policy.yml
201
208
  ```
202
209
 
210
+ ### Policy example
211
+
212
+ A small `policy.yml` with one rule per severity. `pass` is the default: a change gets it when no rule matches.
213
+
214
+ ```yaml
215
+ default: pass # no rule matched -> pass
216
+ notify_owners_on: needs_human # tag downstream owners from this level up
217
+
218
+ rules:
219
+ - name: type-change # a column changed type -> warn
220
+ when: {column_type_changed: true}
221
+ then: warn
222
+
223
+ - name: revenue-moved # total revenue moved more than 2% -> a human signs off
224
+ when: {column: amount, sum_change_pct_gt: 2}
225
+ then: needs_human
226
+
227
+ - name: duplicate-keys # a join fanned out and duplicated keys -> block the PR
228
+ when: {duplicate_keys: true}
229
+ then: block
230
+ ```
231
+
232
+ | The change | Verdict |
233
+ |---|---|
234
+ | A filter fix that changes 40 rows, nothing else | `pass` |
235
+ | `order_date` goes from `STRING` to `DATE` | `warn` |
236
+ | A pricing fix moves `SUM(amount)` by 3.1% | `needs_human` |
237
+ | A new join duplicates 40 `order_id`s | `block` |
238
+
239
+ If several rules match, the most severe one wins. The full starter policy is in [`examples/databricks/policy.yml`](examples/databricks/policy.yml), and `bricksentry init` writes one for you.
240
+
203
241
  ### Policy conditions
204
242
 
205
243
  `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`) · `any_change` · `diff_error`
@@ -218,11 +256,13 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
218
256
  - **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.
219
257
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
220
258
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
221
- - **Validated on one Databricks workspace so far** (serverless, November 2026): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. 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.
259
+ - **Validated on one Databricks workspace so far** (serverless, November 2026, on a 2-million-row table): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. 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.
222
260
 
223
261
  ## Roadmap
224
262
 
225
- Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
263
+ **Top priority: validation across more workspaces.** Classic and serverless compute, AWS, Azure and GCP, and workspaces with restricted system-table access. If you run the quickstart notebook, please [share what you see](https://github.com/bricksentry/bricksentry/issues), whether it works or not.
264
+
265
+ Next: Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
226
266
 
227
267
  ## Contributing
228
268
 
@@ -231,3 +271,7 @@ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTIN
231
271
  ## License
232
272
 
233
273
  Apache-2.0. Created and maintained by Brahma - Databricks Champion.
274
+
275
+ ## Trademarks
276
+
277
+ bricksentry is an independent open-source project. It is not affiliated with, endorsed by, or sponsored by Databricks, Inc. or Functional Software, Inc. (Sentry). Databricks, Unity Catalog and Lakeflow are trademarks of Databricks, Inc. Delta Lake is a trademark of the Linux Foundation, and Apache Spark and PySpark are trademarks of the Apache Software Foundation. All other names are the trademarks of their respective owners and are used here only to describe compatibility. Thank you.
@@ -1,10 +1,16 @@
1
- # bricksentry
1
+ # Welcome to bricksentry
2
2
 
3
- [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![CI](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
3
+ [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
4
4
 
5
- ***Change-safety for Databricks pipelines and the AI agents that edit them.***
5
+ ***The safety check for data changes in the AI era.***
6
6
 
7
- **Website and docs: [bricksentry.org](https://bricksentry.org)**
7
+ Change-safety for Databricks pipelines and the AI agents that edit them: know what a change does to your data before it ships.
8
+
9
+ **[Try it in 30 seconds](#try-it-in-30-seconds-no-databricks-needed)** · **[Run the Databricks notebook](#run-it-in-your-databricks-workspace)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
10
+
11
+ Built by Brahmareddy, Databricks Champion. Open source under Apache-2.0.
12
+
13
+ *Why the name?* Bricks plus entry. Your tables and pipelines are the bricks of the lakehouse, and every change to them is an entry. bricksentry checks each entry, reports what it does, and stands guard before it lands.
8
14
 
9
15
  ## Try it in 30 seconds (no Databricks needed)
10
16
 
@@ -17,15 +23,12 @@ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE
17
23
 
18
24
  ![bricksentry demo: an agent's change is previewed, blocked for duplicate keys, then routed to the table owners](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
19
25
 
20
- ### Or run it in your Databricks workspace
26
+ ## Run it in your Databricks workspace
21
27
 
22
- The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
23
-
24
- In Databricks: **Workspace → Import → URL**, and paste:
28
+ > **Databricks quickstart notebook:** in your workspace, go to **Workspace → Import → URL** and paste
29
+ > `https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py`
25
30
 
26
- ```
27
- https://raw.githubusercontent.com/bricksentry/bricksentry/main/examples/databricks/bricksentry_quickstart.py
28
- ```
31
+ The [quickstart notebook](examples/databricks/bricksentry_quickstart.py) creates a small demo table in a schema you choose and runs the same loop on Databricks: Unity Catalog blast radius, a real `RESTORE` rollback plan, a preview on a shallow clone, a blocked pull request and the fix. Then it checks one of your own tables, read-only, and cleans up after itself.
29
32
 
30
33
  You need a SQL warehouse, `CREATE TABLE` on the schema you pick, and `SELECT` on `system.access.table_lineage` for the blast radius. A Jupyter copy is in [`bricksentry_quickstart.ipynb`](examples/databricks/bricksentry_quickstart.ipynb).
31
34
 
@@ -74,7 +77,8 @@ Designed for agents:
74
77
  - **The verdict never comes from an LLM.** Rules in `policy.yml` decide, so the same change always gets the same answer.
75
78
  - **Read-only by default.** Only `preview_write` writes, and only to a sandbox clone. It accepts a single INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE whose target must be the clone, and it refuses DROP, TRUNCATE, ALTER, GRANT and multiple statements.
76
79
  - **Errors come back as `{"error": ...}`**, so agents can recover instead of crashing.
77
- - **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window.
80
+ - **Bounded cost:** deterministic hash sampling (`sample_pct`), capped samples, and lineage limited by depth and lookback window. A full-table checksum guards the sample: if the sample shows no change but the tables differ, the diff re-runs on every row, so a one-row change can't slip through.
81
+ - **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
78
82
 
79
83
  The same tools are plain Python functions in `bricksentry.agent_tools`, so you can use them from LangGraph, the OpenAI Agents SDK or the Databricks Agent Framework without MCP.
80
84
 
@@ -145,7 +149,8 @@ s.preview_write("DELETE FROM main.sales.orders WHERE status = 'test'", "main.sal
145
149
  backend: {type: databricks, warehouse_id: abc123} # auth: standard Databricks SDK chain
146
150
  sandbox_schema: main.bricksentry_sandbox
147
151
  candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
148
- sample_pct: 10
152
+ sample_pct: 10 # sample_guard re-checks the whole table (on by default)
153
+ assessment_store: ~/.bricksentry/assessments # or false to keep assessments in memory
149
154
  lineage: {type: databricks, depth: 3, lookback_days: 90} # also: exclude, exclude_dropped
150
155
  tables:
151
156
  main.sales.orders:
@@ -155,6 +160,37 @@ tables:
155
160
  policy: policy.yml
156
161
  ```
157
162
 
163
+ ### Policy example
164
+
165
+ A small `policy.yml` with one rule per severity. `pass` is the default: a change gets it when no rule matches.
166
+
167
+ ```yaml
168
+ default: pass # no rule matched -> pass
169
+ notify_owners_on: needs_human # tag downstream owners from this level up
170
+
171
+ rules:
172
+ - name: type-change # a column changed type -> warn
173
+ when: {column_type_changed: true}
174
+ then: warn
175
+
176
+ - name: revenue-moved # total revenue moved more than 2% -> a human signs off
177
+ when: {column: amount, sum_change_pct_gt: 2}
178
+ then: needs_human
179
+
180
+ - name: duplicate-keys # a join fanned out and duplicated keys -> block the PR
181
+ when: {duplicate_keys: true}
182
+ then: block
183
+ ```
184
+
185
+ | The change | Verdict |
186
+ |---|---|
187
+ | A filter fix that changes 40 rows, nothing else | `pass` |
188
+ | `order_date` goes from `STRING` to `DATE` | `warn` |
189
+ | A pricing fix moves `SUM(amount)` by 3.1% | `needs_human` |
190
+ | A new join duplicates 40 `order_id`s | `block` |
191
+
192
+ If several rules match, the most severe one wins. The full starter policy is in [`examples/databricks/policy.yml`](examples/databricks/policy.yml), and `bricksentry init` writes one for you.
193
+
158
194
  ### Policy conditions
159
195
 
160
196
  `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`) · `any_change` · `diff_error`
@@ -173,11 +209,13 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
173
209
  - **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.
174
210
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
175
211
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
176
- - **Validated on one Databricks workspace so far** (serverless, November 2026): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. 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.
212
+ - **Validated on one Databricks workspace so far** (serverless, November 2026, on a 2-million-row table): lineage, Delta rollback plans, previews on shallow clones, every verdict level and sampling. 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.
177
213
 
178
214
  ## Roadmap
179
215
 
180
- Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
216
+ **Top priority: validation across more workspaces.** Classic and serverless compute, AWS, Azure and GCP, and workspaces with restricted system-table access. If you run the quickstart notebook, please [share what you see](https://github.com/bricksentry/bricksentry/issues), whether it works or not.
217
+
218
+ Next: Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
181
219
 
182
220
  ## Contributing
183
221
 
@@ -186,3 +224,7 @@ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTIN
186
224
  ## License
187
225
 
188
226
  Apache-2.0. Created and maintained by Brahma - Databricks Champion.
227
+
228
+ ## Trademarks
229
+
230
+ bricksentry is an independent open-source project. It is not affiliated with, endorsed by, or sponsored by Databricks, Inc. or Functional Software, Inc. (Sentry). Databricks, Unity Catalog and Lakeflow are trademarks of Databricks, Inc. Delta Lake is a trademark of the Linux Foundation, and Apache Spark and PySpark are trademarks of the Apache Software Foundation. All other names are the trademarks of their respective owners and are used here only to describe compatibility. Thank you.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.3"
7
+ version = "0.1.4"
8
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."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -38,7 +38,7 @@ databricks = ["databricks-sdk>=0.30"]
38
38
  duckdb = ["duckdb>=1.0"]
39
39
  mcp = ["mcp>=1.10"]
40
40
  all = ["databricks-sdk>=0.30", "duckdb>=1.0", "mcp>=1.10"]
41
- dev = ["pytest>=8", "duckdb>=1.0", "mcp>=1.10", "databricks-sdk>=0.30"]
41
+ dev = ["pytest>=8", "pytest-cov>=5", "ruff>=0.6", "duckdb>=1.0", "mcp>=1.10", "databricks-sdk>=0.30"]
42
42
 
43
43
  [project.scripts]
44
44
  bricksentry = "bricksentry.cli:entry"
@@ -58,3 +58,23 @@ packages = ["src/bricksentry"]
58
58
 
59
59
  [tool.pytest.ini_options]
60
60
  testpaths = ["tests"]
61
+
62
+ [tool.ruff]
63
+ line-length = 120
64
+ target-version = "py310"
65
+ builtins = ["dbutils", "spark", "display"] # Databricks notebook globals
66
+
67
+ [tool.ruff.lint]
68
+ select = ["E", "F", "W", "I", "UP", "B"]
69
+ ignore = ["E501"]
70
+
71
+ [tool.coverage.run]
72
+ source = ["bricksentry"]
73
+ branch = true
74
+
75
+ [tool.coverage.report]
76
+ show_missing = true
77
+ skip_covered = true
78
+
79
+ [tool.ruff.lint.per-file-ignores]
80
+ "examples/**" = ["E402"] # notebooks import after %pip install cells
@@ -23,8 +23,8 @@ def cells_from_source(text: str) -> list[dict]:
23
23
  lines = raw.strip("\n").splitlines()
24
24
  if not lines:
25
25
  continue
26
- if all(l.startswith("# MAGIC") for l in lines):
27
- stripped = [l[len("# MAGIC"):].removeprefix(" ") for l in lines]
26
+ if all(ln.startswith("# MAGIC") for ln in lines):
27
+ stripped = [ln[len("# MAGIC"):].removeprefix(" ") for ln in lines]
28
28
  if stripped[0].startswith("%md"):
29
29
  md = stripped[1:]
30
30
  cells.append({"cell_type": "markdown", "metadata": {}, "source": _src(md)})
@@ -36,7 +36,7 @@ def cells_from_source(text: str) -> list[dict]:
36
36
 
37
37
 
38
38
  def _src(lines: list[str]) -> list[str]:
39
- return [l + "\n" for l in lines[:-1]] + ([lines[-1]] if lines else [])
39
+ return [ln + "\n" for ln in lines[:-1]] + ([lines[-1]] if lines else [])
40
40
 
41
41
 
42
42
  def _code(lines: list[str]) -> dict:
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.3"
26
+ __version__ = "0.1.4"
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
6
+ import re
5
7
  import uuid
6
8
  from typing import Any
7
9
 
@@ -49,6 +51,7 @@ class Sentry:
49
51
  sample_pct=sample_pct if sample_pct is not None else self.config.sample_pct,
50
52
  segment_by=spec.segment_by,
51
53
  max_samples=self.config.max_samples,
54
+ sample_guard=self.config.sample_guard,
52
55
  )
53
56
  self._diffs[d.table] = d
54
57
  return d
@@ -126,6 +129,32 @@ class Sentry:
126
129
  notify=sorted(notify),
127
130
  )
128
131
  self._assessments[a.id] = a
132
+ self._save(a)
133
+ return a
134
+
135
+ # --- saved assessments -------------------------------------------------
136
+ def _save(self, a: Assessment) -> None:
137
+ """Save an assessment as JSON so another Sentry (another process, the MCP
138
+ server, a later notebook cell) can look it up by id. Best effort."""
139
+ folder = self.config.store_dir()
140
+ if folder is None:
141
+ return
142
+ try:
143
+ folder.mkdir(parents=True, exist_ok=True)
144
+ (folder / f"{a.id}.json").write_text(json.dumps(a.to_dict(), default=str))
145
+ except OSError:
146
+ pass
147
+
148
+ def _load(self, assessment_id: str) -> Assessment | None:
149
+ folder = self.config.store_dir()
150
+ if folder is None or not re.fullmatch(r"[0-9a-f]{1,64}", assessment_id or ""):
151
+ return None
152
+ f = folder / f"{assessment_id}.json"
153
+ try:
154
+ a = Assessment.from_dict(json.loads(f.read_text()))
155
+ except (OSError, ValueError, KeyError, TypeError):
156
+ return None
157
+ self._assessments[a.id] = a
129
158
  return a
130
159
 
131
160
  def preview_write(
@@ -159,7 +188,7 @@ class Sentry:
159
188
 
160
189
  # --- lookups for agents -------------------------------------------------
161
190
  def get_assessment(self, assessment_id: str) -> Assessment | None:
162
- return self._assessments.get(assessment_id)
191
+ return self._assessments.get(assessment_id) or self._load(assessment_id)
163
192
 
164
193
  def get_diff(self, table: str) -> TableDiff | None:
165
194
  return self._diffs.get(table)
@@ -47,6 +47,13 @@ class Backend(ABC):
47
47
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
48
48
  """Deterministic hash sample on the key columns, identical on both sides."""
49
49
 
50
+ def row_checksum(self, columns: list[str]) -> str | None:
51
+ """SQL aggregate: an order-independent checksum over ``columns`` for every row.
52
+
53
+ Used to check a sampled diff against the whole table. ``None`` means the
54
+ backend has no cheap row hash, and the guard is skipped."""
55
+ return None
56
+
50
57
  @abstractmethod
51
58
  def days_ago(self, days: int) -> str:
52
59
  """SQL expression for the date ``days`` days ago."""
@@ -87,7 +87,7 @@ class DatabricksBackend(Backend):
87
87
  if nxt is None:
88
88
  break
89
89
  chunk = api.get_statement_result_chunk_n(resp.statement_id, nxt)
90
- return [{n: _convert(v, t) for n, v, t in zip(names, row, types)} for row in rows]
90
+ return [{n: _convert(v, t) for n, v, t in zip(names, row, types, strict=False)} for row in rows]
91
91
 
92
92
  @staticmethod
93
93
  def _format_kwargs() -> dict[str, Any]:
@@ -102,6 +102,10 @@ class DatabricksBackend(Backend):
102
102
  def quote(self, ident: str) -> str:
103
103
  return "`" + ident.replace("`", "``") + "`"
104
104
 
105
+ def row_checksum(self, columns: list[str]) -> str | None:
106
+ cols = ", ".join(self.quote(c) for c in columns)
107
+ return f"SUM(CAST(xxhash64({cols}) AS DECIMAL(38, 0)))"
108
+
105
109
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
106
110
  pre = f"{alias}." if alias else ""
107
111
  cols = ", ".join(f"{pre}{self.quote(k)}" for k in keys)
@@ -25,7 +25,7 @@ class DuckDBBackend(Backend):
25
25
  if cur.description is None:
26
26
  return []
27
27
  cols = [d[0] for d in cur.description]
28
- return [dict(zip(cols, row)) for row in cur.fetchall()]
28
+ return [dict(zip(cols, row, strict=False)) for row in cur.fetchall()]
29
29
 
30
30
  def quote(self, ident: str) -> str:
31
31
  return '"' + ident.replace('"', '""') + '"'
@@ -34,6 +34,10 @@ class DuckDBBackend(Backend):
34
34
  def string_type(self) -> str:
35
35
  return "VARCHAR"
36
36
 
37
+ def row_checksum(self, columns: list[str]) -> str | None:
38
+ cols = ", ".join(self.quote(c) for c in columns)
39
+ return f"SUM(CAST(hash({cols}) AS HUGEINT))"
40
+
37
41
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
38
42
  pre = f"{alias}." if alias else ""
39
43
  cols = ", ".join(f"{pre}{self.quote(k)}" for k in keys)
@@ -8,6 +8,8 @@ Example::
8
8
  sandbox_schema: main.bricksentry_sandbox
9
9
  candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
10
10
  sample_pct: 10 # diff a deterministic 10% hash sample (omit for full diff)
11
+ sample_guard: true # re-run on all rows if the sample misses a change (default)
12
+ assessment_store: ~/.bricksentry/assessments # where assessments are saved; false to keep them in memory only
11
13
  lineage:
12
14
  depth: 3
13
15
  lookback_days: 90
@@ -46,6 +48,8 @@ class Config:
46
48
  sandbox_schema: str = "bricksentry_sandbox"
47
49
  candidate_pattern: str = "{catalog}.{schema}_ci.{table}"
48
50
  sample_pct: float | None = None
51
+ sample_guard: bool = True
52
+ assessment_store: str | bool | None = None
49
53
  max_samples: int = 5
50
54
  lineage: dict[str, Any] = field(default_factory=dict)
51
55
  tables: dict[str, TableSpec] = field(default_factory=dict)
@@ -53,7 +57,7 @@ class Config:
53
57
  root: Path = field(default_factory=Path.cwd)
54
58
 
55
59
  @classmethod
56
- def from_dict(cls, data: dict[str, Any], root: Path | None = None) -> "Config":
60
+ def from_dict(cls, data: dict[str, Any], root: Path | None = None) -> Config:
57
61
  root = root or Path.cwd()
58
62
  tables = {}
59
63
  for name, spec in (data.get("tables") or {}).items():
@@ -79,6 +83,8 @@ class Config:
79
83
  sandbox_schema=data.get("sandbox_schema", "bricksentry_sandbox"),
80
84
  candidate_pattern=data.get("candidate_pattern", "{catalog}.{schema}_ci.{table}"),
81
85
  sample_pct=data.get("sample_pct"),
86
+ sample_guard=bool(data.get("sample_guard", True)),
87
+ assessment_store=data.get("assessment_store"),
82
88
  max_samples=int(data.get("max_samples", 5)),
83
89
  lineage=data.get("lineage") or {},
84
90
  tables=tables,
@@ -87,7 +93,7 @@ class Config:
87
93
  )
88
94
 
89
95
  @classmethod
90
- def load(cls, path: str | os.PathLike | None = None) -> "Config":
96
+ def load(cls, path: str | os.PathLike | None = None) -> Config:
91
97
  if path is None:
92
98
  path = os.environ.get("BRICKSENTRY_CONFIG")
93
99
  if path is None:
@@ -101,6 +107,16 @@ class Config:
101
107
  data = yaml.safe_load(p.read_text()) or {}
102
108
  return cls.from_dict(data, root=p.resolve().parent)
103
109
 
110
+ def store_dir(self) -> Path | None:
111
+ """Folder where assessments are saved as JSON, or None to keep them in memory."""
112
+ v = self.assessment_store
113
+ if v is False:
114
+ return None
115
+ if v in (None, True, ""):
116
+ v = os.environ.get("BRICKSENTRY_STORE") or "~/.bricksentry/assessments"
117
+ p = Path(str(v)).expanduser()
118
+ return p if p.is_absolute() else (self.root / p)
119
+
104
120
  def spec(self, table: str) -> TableSpec:
105
121
  if table in self.tables:
106
122
  return self.tables[table]
@@ -110,7 +110,7 @@ def run_demo(report_path: str | None = None) -> dict[str, Any]:
110
110
 
111
111
  backend.execute("CREATE SCHEMA sales; CREATE SCHEMA sales_pr_42")
112
112
  backend.execute(SEED_SQL)
113
- sentry = Sentry(Config.from_dict(CONFIG), backend=backend)
113
+ sentry = Sentry(Config.from_dict({**CONFIG, "assessment_store": False}), backend=backend)
114
114
  previous = agent_tools._SENTRY
115
115
  agent_tools.set_sentry(sentry)
116
116
  results: dict[str, Any] = {}
@@ -36,6 +36,56 @@ def diff_tables(
36
36
  segment_by: list[str] | None = None,
37
37
  max_samples: int = 5,
38
38
  columns: list[str] | None = None,
39
+ sample_guard: bool = True,
40
+ ) -> TableDiff:
41
+ """Diff ``base`` against ``candidate``.
42
+
43
+ With ``sample_pct``, only a hash sample of keys is compared. ``sample_guard``
44
+ (on by default) then checks a full-table checksum: if the sample shows no
45
+ change but the tables differ, the diff re-runs on every row, so a small change
46
+ outside the sample can never pass as "no change".
47
+ """
48
+ d = _diff(backend, base, candidate, keys, table=table, sample_pct=sample_pct,
49
+ segment_by=segment_by, max_samples=max_samples, columns=columns)
50
+ if not (sample_pct and sample_guard and d.is_identical):
51
+ return d
52
+ cols = list(d.keys) + [c.column for c in d.columns]
53
+ full = _full_fingerprints(backend, base, candidate, cols)
54
+ if full is None or full[0] == full[1]:
55
+ return d
56
+ full_d = _diff(backend, base, candidate, keys, table=table, sample_pct=None,
57
+ segment_by=segment_by, max_samples=max_samples, columns=columns)
58
+ full_d.sample_note = (
59
+ f"The {sample_pct:g}% sample showed no changes, but the full tables differ, "
60
+ "so the diff was re-run on all rows."
61
+ )
62
+ return full_d
63
+
64
+
65
+ def _full_fingerprints(backend: Backend, base: str, candidate: str, cols: list[str]):
66
+ """(rows, checksum) for each table over all rows, or None if unsupported."""
67
+ agg = backend.row_checksum(cols)
68
+ if agg is None:
69
+ return None
70
+
71
+ def fp(tbl: str):
72
+ r = backend.query(f"SELECT COUNT(*) AS n, {agg} AS h FROM {backend.qualified(tbl)}")[0]
73
+ return int(r.get("n") or 0), str(r.get("h"))
74
+
75
+ return fp(base), fp(candidate)
76
+
77
+
78
+ def _diff(
79
+ backend: Backend,
80
+ base: str,
81
+ candidate: str,
82
+ keys: list[str],
83
+ *,
84
+ table: str | None,
85
+ sample_pct: float | None,
86
+ segment_by: list[str] | None,
87
+ max_samples: int,
88
+ columns: list[str] | None,
39
89
  ) -> TableDiff:
40
90
  if not keys:
41
91
  raise DiffError(
@@ -77,6 +77,8 @@ def explain_diff(d: TableDiff) -> str:
77
77
  s += f". Note: {_n(d.null_keys_candidate)} row(s) have a NULL key ({', '.join(d.keys)})"
78
78
  if d.sampled_pct:
79
79
  s += f" (based on a {d.sampled_pct:g}% key sample)"
80
+ if d.sample_note:
81
+ s += f" ({d.sample_note})"
80
82
  return s + "."
81
83
 
82
84
 
@@ -30,7 +30,7 @@ class Verdict(str, Enum):
30
30
  }[self]
31
31
 
32
32
  @staticmethod
33
- def worst(verdicts: list["Verdict"]) -> "Verdict":
33
+ def worst(verdicts: list[Verdict]) -> Verdict:
34
34
  return max(verdicts, key=lambda v: v.rank, default=Verdict.PASS)
35
35
 
36
36
 
@@ -89,6 +89,7 @@ class TableDiff:
89
89
  null_keys_candidate: int = 0
90
90
  segments: list[Segment] = field(default_factory=list)
91
91
  sampled_pct: float | None = None
92
+ sample_note: str | None = None
92
93
  error: str | None = None
93
94
 
94
95
  def _pct(self, n: int) -> float:
@@ -133,10 +134,28 @@ class TableDiff:
133
134
  d["changed_pct"] = self.changed_pct
134
135
  d["row_count_change_pct"] = self.row_count_change_pct
135
136
  d["is_identical"] = self.is_identical
136
- for c, cc in zip(d["columns"], self.columns):
137
+ for c, cc in zip(d["columns"], self.columns, strict=False):
137
138
  c["sum_change_pct"] = cc.sum_change_pct
138
139
  return d
139
140
 
141
+ @classmethod
142
+ def from_dict(cls, d: dict[str, Any]) -> TableDiff:
143
+ sc = d.get("schema") or {}
144
+ schema = SchemaChange(
145
+ added=dict(sc.get("added") or {}),
146
+ removed=dict(sc.get("removed") or {}),
147
+ type_changed={
148
+ k: (v["base"], v["candidate"]) if isinstance(v, dict) else tuple(v)
149
+ for k, v in (sc.get("type_changed") or {}).items()
150
+ },
151
+ )
152
+ col_fields = {f for f in ColumnChange.__dataclass_fields__}
153
+ cols = [ColumnChange(**{k: v for k, v in c.items() if k in col_fields}) for c in d.get("columns") or []]
154
+ segs = [Segment(**s) for s in d.get("segments") or []]
155
+ skip = {"schema", "columns", "segments"}
156
+ rest = {k: v for k, v in d.items() if k in cls.__dataclass_fields__ and k not in skip}
157
+ return cls(schema=schema, columns=cols, segments=segs, **rest)
158
+
140
159
 
141
160
  @dataclass
142
161
  class ImpactNode:
@@ -163,6 +182,10 @@ class RuleHit:
163
182
  def to_dict(self) -> dict[str, Any]:
164
183
  return {"rule": self.rule, "verdict": self.verdict.value, "table": self.table, "reason": self.reason}
165
184
 
185
+ @classmethod
186
+ def from_dict(cls, d: dict[str, Any]) -> RuleHit:
187
+ return cls(rule=d["rule"], verdict=Verdict(d["verdict"]), table=d["table"], reason=d["reason"])
188
+
166
189
 
167
190
  @dataclass
168
191
  class TableAssessment:
@@ -190,6 +213,20 @@ class TableAssessment:
190
213
  "rollback": self.rollback,
191
214
  }
192
215
 
216
+ @classmethod
217
+ def from_dict(cls, d: dict[str, Any]) -> TableAssessment:
218
+ return cls(
219
+ table=d["table"],
220
+ diff=TableDiff.from_dict(d["diff"]) if d.get("diff") else None,
221
+ downstream=[ImpactNode(**n) for n in d.get("downstream") or []],
222
+ owner=d.get("owner"),
223
+ tags=dict(d.get("tags") or {}),
224
+ rollback=d.get("rollback"),
225
+ verdict=Verdict(d.get("verdict", "pass")),
226
+ hits=[RuleHit.from_dict(h) for h in d.get("rule_hits") or []],
227
+ summary=d.get("summary", ""),
228
+ )
229
+
193
230
 
194
231
  @dataclass
195
232
  class Assessment:
@@ -212,3 +249,12 @@ class Assessment:
212
249
  "rule_hits": [h.to_dict() for h in self.hits],
213
250
  "tables": [t.to_dict() for t in self.tables],
214
251
  }
252
+
253
+ @classmethod
254
+ def from_dict(cls, d: dict[str, Any]) -> Assessment:
255
+ return cls(
256
+ id=d["id"],
257
+ tables=[TableAssessment.from_dict(t) for t in d.get("tables") or []],
258
+ verdict=Verdict(d["verdict"]),
259
+ notify=list(d.get("notify") or []),
260
+ )
@@ -21,6 +21,12 @@ def backend():
21
21
  return b
22
22
 
23
23
 
24
+ @pytest.fixture(autouse=True)
25
+ def _isolated_store(tmp_path, monkeypatch):
26
+ """Saved assessments go to a temp folder, never the real home directory."""
27
+ monkeypatch.setenv("BRICKSENTRY_STORE", str(tmp_path / "assessments"))
28
+
29
+
24
30
  @pytest.fixture
25
31
  def config():
26
32
  return Config.from_dict(
@@ -0,0 +1,84 @@
1
+ """v0.1.4: sampled diffs can't miss a change, and assessments outlive their Sentry."""
2
+
3
+ from bricksentry import Config, Sentry, agent_tools
4
+ from bricksentry.diff import diff_tables
5
+
6
+
7
+ def _one_row_outside_sample(backend, pct):
8
+ """The key of a row that a pct% sample does not include."""
9
+ pred = backend.sample_predicate(["order_id"], pct)
10
+ return backend.scalar(f"SELECT MIN(order_id) FROM sales.orders WHERE NOT ({pred})")
11
+
12
+
13
+ def test_small_change_outside_sample_is_caught(backend):
14
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
15
+ k = _one_row_outside_sample(backend, 10)
16
+ backend.execute(f"DELETE FROM sales_ci.orders WHERE order_id = {k}")
17
+
18
+ unguarded = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"],
19
+ sample_pct=10, sample_guard=False)
20
+ assert unguarded.is_identical # the old behaviour: the sample cannot see it
21
+
22
+ d = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"], sample_pct=10)
23
+ assert not d.is_identical
24
+ assert d.removed_rows == 1
25
+ assert d.base_rows == 1000 and d.candidate_rows == 999 # full counts, not the sample
26
+ assert d.sampled_pct is None and d.sample_note
27
+
28
+
29
+ def test_value_change_outside_sample_is_caught(backend):
30
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
31
+ k = _one_row_outside_sample(backend, 10)
32
+ backend.execute(f"UPDATE sales_ci.orders SET amount = amount + 1 WHERE order_id = {k}")
33
+ d = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"], sample_pct=10)
34
+ assert d.changed_rows == 1
35
+
36
+
37
+ def test_identical_tables_stay_sampled(backend):
38
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
39
+ d = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id"], sample_pct=10)
40
+ assert d.is_identical and d.sampled_pct == 10 and d.sample_note is None
41
+
42
+
43
+ def test_guard_never_passes_a_changed_table_via_sentry(backend, config):
44
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
45
+ k = _one_row_outside_sample(backend, 10)
46
+ backend.execute(f"DELETE FROM sales_ci.orders WHERE order_id = {k}")
47
+ config.sample_pct = 10
48
+ s = Sentry(config, backend=backend)
49
+ a = s.assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
50
+ assert a.verdict.value != "pass" # the certified downstream table makes it needs_human
51
+ assert "re-run on all rows" in a.tables[0].summary
52
+
53
+
54
+ def test_assessment_found_from_another_sentry(backend, config, tmp_path):
55
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
56
+ backend.execute("DELETE FROM sales_ci.orders WHERE order_id <= 50")
57
+ config.assessment_store = str(tmp_path / "store")
58
+ a = Sentry(config, backend=backend).assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
59
+
60
+ other = Sentry(config, backend=backend) # a fresh instance: nothing in memory
61
+ agent_tools.set_sentry(other)
62
+ try:
63
+ exp = agent_tools.explain_diff(assessment_id=a.id)
64
+ assert exp["assessment_id"] == a.id and "50 rows removed" in exp["explanations"]["sales.orders"]
65
+ gate = agent_tools.safe_to_ship(a.id)
66
+ assert gate["verdict"] == a.verdict.value
67
+ assert gate["rule_hits"] == [h.to_dict() for h in a.hits]
68
+ loaded = other.get_assessment(a.id)
69
+ assert loaded.tables[0].diff.removed_rows == 50
70
+ assert agent_tools.safe_to_ship("../../etc/passwd").get("error")
71
+ finally:
72
+ agent_tools.set_sentry(None)
73
+
74
+
75
+ def test_store_can_be_disabled(backend, config, tmp_path):
76
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
77
+ config.assessment_store = False
78
+ a = Sentry(config, backend=backend).assess(["sales.orders"], candidates={"sales.orders": "sales_ci.orders"})
79
+ assert Sentry(config, backend=backend).get_assessment(a.id) is None
80
+
81
+
82
+ def test_config_reads_new_keys():
83
+ c = Config.from_dict({"sample_guard": False, "assessment_store": "state/assess"})
84
+ assert c.sample_guard is False and str(c.store_dir()).endswith("state/assess")
File without changes
File without changes
File without changes
File without changes