bricksentry 0.1.0__tar.gz → 0.1.2__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 (41) hide show
  1. {bricksentry-0.1.0 → bricksentry-0.1.2}/CHANGELOG.md +13 -0
  2. bricksentry-0.1.2/CONTRIBUTING.md +33 -0
  3. {bricksentry-0.1.0 → bricksentry-0.1.2}/PKG-INFO +50 -15
  4. {bricksentry-0.1.0 → bricksentry-0.1.2}/README.md +44 -14
  5. bricksentry-0.1.2/SECURITY.md +19 -0
  6. {bricksentry-0.1.0 → bricksentry-0.1.2}/examples/databricks/policy.yml +1 -0
  7. bricksentry-0.1.2/examples/demo/agent_loop_demo.py +12 -0
  8. {bricksentry-0.1.0 → bricksentry-0.1.2}/pyproject.toml +9 -2
  9. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/__init__.py +1 -1
  10. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/cli.py +11 -0
  11. bricksentry-0.1.2/src/bricksentry/demo.py +194 -0
  12. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/diff.py +16 -8
  13. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/explain.py +2 -0
  14. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/models.py +2 -0
  15. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/policy.py +11 -1
  16. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/report.py +1 -1
  17. {bricksentry-0.1.0 → bricksentry-0.1.2}/tests/test_assess_policy.py +13 -0
  18. bricksentry-0.1.2/tests/test_demo.py +27 -0
  19. {bricksentry-0.1.0 → bricksentry-0.1.2}/tests/test_diff.py +23 -0
  20. bricksentry-0.1.0/examples/demo/agent_loop_demo.py +0 -119
  21. {bricksentry-0.1.0 → bricksentry-0.1.2}/.gitignore +0 -0
  22. {bricksentry-0.1.0 → bricksentry-0.1.2}/LICENSE +0 -0
  23. {bricksentry-0.1.0 → bricksentry-0.1.2}/action.yml +0 -0
  24. {bricksentry-0.1.0 → bricksentry-0.1.2}/examples/databricks/bricksentry.yml +0 -0
  25. {bricksentry-0.1.0 → bricksentry-0.1.2}/examples/databricks/github-workflow.yml +0 -0
  26. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/agent_tools.py +0 -0
  27. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/assess.py +0 -0
  28. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/backends/__init__.py +0 -0
  29. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/backends/base.py +0 -0
  30. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/backends/databricks_backend.py +0 -0
  31. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/backends/duckdb_backend.py +0 -0
  32. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/changes.py +0 -0
  33. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/config.py +0 -0
  34. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/github.py +0 -0
  35. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/lineage.py +0 -0
  36. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/mcp_server.py +0 -0
  37. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/preview.py +0 -0
  38. {bricksentry-0.1.0 → bricksentry-0.1.2}/src/bricksentry/py.typed +0 -0
  39. {bricksentry-0.1.0 → bricksentry-0.1.2}/tests/conftest.py +0 -0
  40. {bricksentry-0.1.0 → bricksentry-0.1.2}/tests/test_databricks_and_uc.py +0 -0
  41. {bricksentry-0.1.0 → bricksentry-0.1.2}/tests/test_preview_agents.py +0 -0
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2 (2026-11-10)
4
+
5
+ - Fix: rows whose key is NULL are now matched null-safely. Before, each such row was counted as both added and removed (found on a real Databricks table with a NULL `state`).
6
+ - New `null_keys` policy condition and default `null-keys` rule (warn) when a change introduces rows with a NULL key; summaries mention NULL keys.
7
+
8
+ ## 0.1.1 (2026-11-10)
9
+
10
+ - New `bricksentry demo` command: the full agent safety loop on a local 20,000-row example in about 30 seconds (`pip install "bricksentry[duckdb]"`). `--report FILE` also writes the pull-request comment.
11
+ - Fix: the "Review requested from" line in PR comments no longer runs into the line above it.
12
+ - Project links (website, docs, source, issues, changelog) in package metadata.
13
+ - CI on Python 3.10 to 3.13, and release automation through PyPI Trusted Publishing.
14
+ - CONTRIBUTING, SECURITY and issue templates.
15
+
3
16
  ## 0.1.0 (2026-11-10)
4
17
 
5
18
  - Key-based data diff with SQL pushdown: schema changes, added/removed/changed rows, per-column changes, nulls, numeric totals, duplicate keys, samples, segment attribution, deterministic hash sampling.
@@ -0,0 +1,33 @@
1
+ # Contributing to bricksentry
2
+
3
+ Thanks for helping. Bug reports from real pipelines are the most useful contribution right now: what bricksentry caught, what it missed, and where it got in the way.
4
+
5
+ ## Report a bug or ask for a feature
6
+
7
+ Open an issue using one of the templates. For bugs, include the command you ran, your `bricksentry.yml` (remove anything private), the output, and what you expected.
8
+
9
+ Security problems: please don't open a public issue. See [SECURITY.md](SECURITY.md).
10
+
11
+ ## Develop locally
12
+
13
+ ```bash
14
+ git clone https://github.com/bricksentry/bricksentry
15
+ cd bricksentry
16
+ python -m venv .venv && source .venv/bin/activate
17
+ pip install -e ".[dev]"
18
+ pytest -q
19
+ bricksentry demo
20
+ ```
21
+
22
+ The tests run against DuckDB, so you don't need a Databricks workspace. The Databricks backend is tested against a mocked SDK client; if your change touches it, please say in the pull request whether you also tried it on a real workspace.
23
+
24
+ ## Pull requests
25
+
26
+ - Keep each pull request to one change, with a test that fails before it and passes after.
27
+ - Verdicts must stay deterministic: policy rules decide them, never an LLM.
28
+ - `preview_write` must never be able to write to the production table. Changes to `preview.py` need tests for the guard.
29
+ - Add a line under "Unreleased" in `CHANGELOG.md`.
30
+
31
+ ## Releases
32
+
33
+ Maintainers bump `version` in `pyproject.toml`, update `CHANGELOG.md`, and push a `vX.Y.Z` tag. The release workflow tests, builds and publishes to PyPI through Trusted Publishing.
@@ -1,7 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
+ 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
5
10
  Author: Brahma
6
11
  License-Expression: Apache-2.0
7
12
  License-File: LICENSE
@@ -40,7 +45,24 @@ Description-Content-Type: text/markdown
40
45
 
41
46
  # bricksentry
42
47
 
43
- **Change-safety for Databricks pipelines and the AI agents that edit them.**
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)
49
+
50
+ ***Change-safety for Databricks pipelines and the AI agents that edit them.***
51
+
52
+ **Website and docs: [bricksentry.org](https://bricksentry.org)**
53
+
54
+ ## Try it in 30 seconds (no Databricks needed)
55
+
56
+ ```bash
57
+ pip install "bricksentry[duckdb]"
58
+ bricksentry demo
59
+ ```
60
+
61
+ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE on a clone (production untouched), **blocks** its pull request for a join that duplicates 40 orders, and routes the fixed version to the owners of a certified table downstream. Everything runs locally on DuckDB.
62
+
63
+ ![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
+
65
+ ## What it does
44
66
 
45
67
  Before a change reaches production, bricksentry answers three questions, in a
46
68
  pull-request comment for humans and in structured JSON for agents:
@@ -49,8 +71,11 @@ pull-request comment for humans and in structured JSON for agents:
49
71
  2. **Who gets hurt?** The downstream blast radius from Unity Catalog lineage: tables, jobs, notebooks, Lakeflow pipelines, dashboards and queries, with owners and tags.
50
72
  3. **Is it safe, and how do I undo it?** A deterministic policy verdict (`pass` · `warn` · `needs_human` · `block`) and the exact `RESTORE TABLE … VERSION AS OF n` rollback.
51
73
 
52
- ```
74
+ For your Databricks workspace:
75
+
76
+ ```bash
53
77
  pip install "bricksentry[databricks,mcp]"
78
+ bricksentry init # writes bricksentry.yml and policy.yml
54
79
  ```
55
80
 
56
81
  ## Why it exists
@@ -86,14 +111,7 @@ Designed for agents:
86
111
 
87
112
  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.
88
113
 
89
- ### See the agent loop (no Databricks needed)
90
-
91
- ```bash
92
- pip install "bricksentry[duckdb]"
93
- python examples/demo/agent_loop_demo.py
94
- ```
95
-
96
- In the demo, an agent previews a risky DELETE (needs_human, production untouched), ships a pipeline change with a join fan-out (**blocked**: 40 duplicate keys), fixes it, and gets routed to the certified table's owners. It ends with the pull-request comment a reviewer would see.
114
+ To watch the whole loop, run `bricksentry demo` (see the top of this page). `bricksentry demo --report report.md` also writes the pull-request comment a reviewer would see.
97
115
 
98
116
  ## For data engineers: CLI and CI
99
117
 
@@ -126,7 +144,20 @@ Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration err
126
144
  DATABRICKS_WAREHOUSE_ID: ${{ secrets.DATABRICKS_WAREHOUSE_ID }}
127
145
  ```
128
146
 
129
- It detects changed tables from the files in the PR and posts or updates one PR comment. Check out with `fetch-depth: 0` and give the job `pull-requests: write` permission. The source repository also ships a composite `action.yml` that wraps these steps.
147
+ It detects changed tables from the files in the PR and posts or updates one PR comment, like this one for the demo's fan-out bug:
148
+
149
+ ![A bricksentry pull-request comment: blocked for 40 duplicate keys, with the data diff and blast radius](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/pr-comment.png)
150
+
151
+ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permission.
152
+
153
+ Or use the bundled GitHub Action, which also writes the report to the job summary:
154
+
155
+ ```yaml
156
+ - uses: bricksentry/bricksentry@v0.1.0
157
+ with:
158
+ config: bricksentry.yml
159
+ fail-on: needs_human
160
+ ```
130
161
 
131
162
  ## Python API
132
163
 
@@ -159,7 +190,7 @@ policy: policy.yml
159
190
 
160
191
  ### Policy conditions
161
192
 
162
- `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` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
193
+ `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`
163
194
 
164
195
  All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
165
196
 
@@ -170,7 +201,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
170
201
  - `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without these, bricksentry still diffs; lineage is just empty.
171
202
  - `CREATE TABLE` on `sandbox_schema`, for `preview_write`.
172
203
 
173
- ## Known limits (v0.1)
204
+ ## Known limits (v0.1.x)
174
205
 
175
206
  - **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.
176
207
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
@@ -181,6 +212,10 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
181
212
 
182
213
  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.
183
214
 
215
+ ## Contributing
216
+
217
+ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTING.md), and [SECURITY.md](SECURITY.md) for reporting vulnerabilities privately.
218
+
184
219
  ## License
185
220
 
186
- Apache-2.0
221
+ Apache-2.0. Created and maintained by Brahma.
@@ -1,6 +1,23 @@
1
1
  # bricksentry
2
2
 
3
- **Change-safety for Databricks pipelines and the AI agents that edit them.**
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)
4
+
5
+ ***Change-safety for Databricks pipelines and the AI agents that edit them.***
6
+
7
+ **Website and docs: [bricksentry.org](https://bricksentry.org)**
8
+
9
+ ## Try it in 30 seconds (no Databricks needed)
10
+
11
+ ```bash
12
+ pip install "bricksentry[duckdb]"
13
+ bricksentry demo
14
+ ```
15
+
16
+ An AI agent changes a 20,000-row revenue table. bricksentry previews its DELETE on a clone (production untouched), **blocks** its pull request for a join that duplicates 40 orders, and routes the fixed version to the owners of a certified table downstream. Everything runs locally on DuckDB.
17
+
18
+ ![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
+
20
+ ## What it does
4
21
 
5
22
  Before a change reaches production, bricksentry answers three questions, in a
6
23
  pull-request comment for humans and in structured JSON for agents:
@@ -9,8 +26,11 @@ pull-request comment for humans and in structured JSON for agents:
9
26
  2. **Who gets hurt?** The downstream blast radius from Unity Catalog lineage: tables, jobs, notebooks, Lakeflow pipelines, dashboards and queries, with owners and tags.
10
27
  3. **Is it safe, and how do I undo it?** A deterministic policy verdict (`pass` · `warn` · `needs_human` · `block`) and the exact `RESTORE TABLE … VERSION AS OF n` rollback.
11
28
 
12
- ```
29
+ For your Databricks workspace:
30
+
31
+ ```bash
13
32
  pip install "bricksentry[databricks,mcp]"
33
+ bricksentry init # writes bricksentry.yml and policy.yml
14
34
  ```
15
35
 
16
36
  ## Why it exists
@@ -46,14 +66,7 @@ Designed for agents:
46
66
 
47
67
  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.
48
68
 
49
- ### See the agent loop (no Databricks needed)
50
-
51
- ```bash
52
- pip install "bricksentry[duckdb]"
53
- python examples/demo/agent_loop_demo.py
54
- ```
55
-
56
- In the demo, an agent previews a risky DELETE (needs_human, production untouched), ships a pipeline change with a join fan-out (**blocked**: 40 duplicate keys), fixes it, and gets routed to the certified table's owners. It ends with the pull-request comment a reviewer would see.
69
+ To watch the whole loop, run `bricksentry demo` (see the top of this page). `bricksentry demo --report report.md` also writes the pull-request comment a reviewer would see.
57
70
 
58
71
  ## For data engineers: CLI and CI
59
72
 
@@ -86,7 +99,20 @@ Exit codes: `0` below `--fail-on`, `1` at or above it, `2` for configuration err
86
99
  DATABRICKS_WAREHOUSE_ID: ${{ secrets.DATABRICKS_WAREHOUSE_ID }}
87
100
  ```
88
101
 
89
- It detects changed tables from the files in the PR and posts or updates one PR comment. Check out with `fetch-depth: 0` and give the job `pull-requests: write` permission. The source repository also ships a composite `action.yml` that wraps these steps.
102
+ It detects changed tables from the files in the PR and posts or updates one PR comment, like this one for the demo's fan-out bug:
103
+
104
+ ![A bricksentry pull-request comment: blocked for 40 duplicate keys, with the data diff and blast radius](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/pr-comment.png)
105
+
106
+ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permission.
107
+
108
+ Or use the bundled GitHub Action, which also writes the report to the job summary:
109
+
110
+ ```yaml
111
+ - uses: bricksentry/bricksentry@v0.1.0
112
+ with:
113
+ config: bricksentry.yml
114
+ fail-on: needs_human
115
+ ```
90
116
 
91
117
  ## Python API
92
118
 
@@ -119,7 +145,7 @@ policy: policy.yml
119
145
 
120
146
  ### Policy conditions
121
147
 
122
- `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` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
148
+ `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`
123
149
 
124
150
  All conditions in a `when` must hold. The most severe matching rule sets the verdict. Unknown conditions are rejected at load time, so a typo can't silently disable a rule.
125
151
 
@@ -130,7 +156,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
130
156
  - `SELECT` on `system.access.table_lineage`, plus `system.information_schema` for owners and tags. Without these, bricksentry still diffs; lineage is just empty.
131
157
  - `CREATE TABLE` on `sandbox_schema`, for `preview_write`.
132
158
 
133
- ## Known limits (v0.1)
159
+ ## Known limits (v0.1.x)
134
160
 
135
161
  - **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.
136
162
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
@@ -141,6 +167,10 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
141
167
 
142
168
  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.
143
169
 
170
+ ## Contributing
171
+
172
+ Bug reports from real pipelines help the most. See [CONTRIBUTING.md](CONTRIBUTING.md), and [SECURITY.md](SECURITY.md) for reporting vulnerabilities privately.
173
+
144
174
  ## License
145
175
 
146
- Apache-2.0
176
+ Apache-2.0. Created and maintained by Brahma.
@@ -0,0 +1,19 @@
1
+ # Security policy
2
+
3
+ bricksentry runs SQL against your data warehouse and can be called by AI agents, so we take reports seriously.
4
+
5
+ ## Reporting a vulnerability
6
+
7
+ Please use GitHub's private vulnerability reporting: open the repository's **Security** tab and choose **Report a vulnerability**. Don't open a public issue for security problems.
8
+
9
+ Especially relevant:
10
+
11
+ - Any way for `preview_write` to modify a table other than its sandbox clone
12
+ - SQL injection through table names, keys or config values
13
+ - Ways for an agent to obtain a `pass` verdict that the policy should not allow
14
+
15
+ You'll get an acknowledgement as soon as possible, and a fix or mitigation plan once the report is confirmed.
16
+
17
+ ## Supported versions
18
+
19
+ Only the latest release receives security fixes during the 0.x series.
@@ -6,6 +6,7 @@ notify_owners_on: needs_human
6
6
  rules:
7
7
  - {name: diff-failed, when: {diff_error: true}, then: needs_human}
8
8
  - {name: duplicate-keys, when: {duplicate_keys: true}, then: block}
9
+ - {name: null-keys, when: {null_keys: true}, then: warn}
9
10
  - {name: dropped-column, when: {column_removed: true}, then: needs_human}
10
11
  - {name: type-change, when: {column_type_changed: true}, then: warn}
11
12
  - {name: certified-downstream, when: {downstream_tag: certified}, then: needs_human}
@@ -0,0 +1,12 @@
1
+ """Runnable demo (no Databricks needed). Same as running `bricksentry demo`:
2
+
3
+ pip install "bricksentry[duckdb]"
4
+ bricksentry demo # or: python examples/demo/agent_loop_demo.py
5
+
6
+ The demo code lives in src/bricksentry/demo.py.
7
+ """
8
+
9
+ from bricksentry.demo import run_demo
10
+
11
+ if __name__ == "__main__":
12
+ run_demo(report_path=None)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.0"
7
+ version = "0.1.2"
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"
@@ -43,8 +43,15 @@ dev = ["pytest>=8", "duckdb>=1.0", "mcp>=1.10", "databricks-sdk>=0.30"]
43
43
  [project.scripts]
44
44
  bricksentry = "bricksentry.cli:entry"
45
45
 
46
+ [project.urls]
47
+ Homepage = "https://bricksentry.org"
48
+ Documentation = "https://bricksentry.org/docs"
49
+ Source = "https://github.com/bricksentry/bricksentry"
50
+ Issues = "https://github.com/bricksentry/bricksentry/issues"
51
+ Changelog = "https://github.com/bricksentry/bricksentry/blob/main/CHANGELOG.md"
52
+
46
53
  [tool.hatch.build.targets.sdist]
47
- include = ["src", "tests", "examples", "README.md", "LICENSE", "CHANGELOG.md", "action.yml"]
54
+ include = ["src", "tests", "examples", "README.md", "LICENSE", "CHANGELOG.md", "CONTRIBUTING.md", "SECURITY.md", "action.yml"]
48
55
 
49
56
  [tool.hatch.build.targets.wheel]
50
57
  packages = ["src/bricksentry"]
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.0"
26
+ __version__ = "0.1.2"
@@ -161,6 +161,16 @@ def preview(target, sql_text, sql_file, keys, fmt, fail_on, config_path):
161
161
  _exit_for(Verdict(out["verdict"]), fail_on)
162
162
 
163
163
 
164
+ @main.command()
165
+ @click.option("--report", "report_path", type=click.Path(), default=None,
166
+ help="Also write the final pull-request comment (markdown) to this file.")
167
+ def demo(report_path):
168
+ """Run the agent safety loop on a local 20,000-row example (needs bricksentry[duckdb])."""
169
+ from bricksentry.demo import run_demo
170
+
171
+ run_demo(report_path)
172
+
173
+
164
174
  @main.command()
165
175
  @click.argument("table")
166
176
  @config_opt
@@ -212,6 +222,7 @@ notify_owners_on: needs_human
212
222
  rules:
213
223
  - {name: diff-failed, when: {diff_error: true}, then: needs_human}
214
224
  - {name: duplicate-keys, when: {duplicate_keys: true}, then: block}
225
+ - {name: null-keys, when: {null_keys: true}, then: warn}
215
226
  - {name: dropped-column, when: {column_removed: true}, then: needs_human}
216
227
  - {name: type-change, when: {column_type_changed: true}, then: warn}
217
228
  - {name: certified-downstream, when: {downstream_tag: certified}, then: needs_human}
@@ -0,0 +1,194 @@
1
+ """``bricksentry demo``: the whole agent safety loop in about 30 seconds, locally.
2
+
3
+ Runs on an in-memory DuckDB database with a 20,000-row orders table and a small
4
+ lineage graph, so it needs no Databricks workspace and no data leaves your machine.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import click
13
+
14
+ from bricksentry import agent_tools
15
+ from bricksentry.assess import Sentry
16
+ from bricksentry.config import Config
17
+
18
+ DOCS_URL = "https://bricksentry.org/docs"
19
+
20
+ CONFIG: dict[str, Any] = {
21
+ "sandbox_schema": "sandbox",
22
+ "candidate_pattern": "{schema}_pr_{pr}.{table}",
23
+ "tables": {"sales.orders": {"keys": ["order_id"], "segment_by": ["region"]}},
24
+ "lineage": {
25
+ "type": "static",
26
+ "edges": {
27
+ "sales.orders": ["sales.daily_revenue", "job:orders_hourly", "dashboard:Exec Revenue"],
28
+ "sales.daily_revenue": ["finance.month_close", "genie_space:Revenue Q&A"],
29
+ },
30
+ "owners": {
31
+ "sales.orders": "sales-data-eng",
32
+ "sales.daily_revenue": "finance-analytics",
33
+ "finance.month_close": "finance-analytics",
34
+ },
35
+ "tags": {"sales.daily_revenue": {"certified": "true"}},
36
+ },
37
+ }
38
+
39
+ SEED_SQL = """
40
+ CREATE TABLE sales.orders AS
41
+ SELECT i AS order_id,
42
+ ['APAC','EMEA','AMER'][1 + (i % 3)] AS region,
43
+ round(20 + (i % 97) * 3.1, 2)::DOUBLE AS amount,
44
+ CASE WHEN i % 10 = 0 THEN 'refunded' ELSE 'paid' END AS status
45
+ FROM range(1, 20001) t(i)
46
+ """
47
+
48
+ # The agent's first attempt: a join that fans out 40 orders (duplicate keys).
49
+ BUGGY_SQL = """
50
+ CREATE OR REPLACE TABLE sales_pr_42.orders AS
51
+ SELECT o.order_id, o.region,
52
+ CASE WHEN o.region = 'APAC' THEN round(o.amount * 0.92, 2) ELSE o.amount END AS amount,
53
+ o.status
54
+ FROM sales.orders o
55
+ LEFT JOIN (SELECT * FROM (VALUES (1), (1)) v(k)) dup ON o.order_id % 500 = 0 AND dup.k = 1
56
+ """
57
+
58
+ FIXED_SQL = """
59
+ CREATE OR REPLACE TABLE sales_pr_42.orders AS
60
+ SELECT order_id, region,
61
+ CASE WHEN region = 'APAC' THEN round(amount * 0.92, 2) ELSE amount END AS amount,
62
+ status
63
+ FROM sales.orders
64
+ """
65
+
66
+ DELETE_SQL = "DELETE FROM sales.orders WHERE status <> 'paid'"
67
+
68
+ # Same verdict colors as the website: pass green, warn amber, needs_human orange, block red.
69
+ _COLORS: dict[str, Any] = {"pass": (29, 160, 100), "warn": (214, 160, 40), "needs_human": (235, 115, 40), "block": (210, 40, 50)}
70
+
71
+
72
+ def _verdict(v: str) -> str:
73
+ return click.style(f" {v.upper()} ", fg="white", bg=_COLORS.get(v, "white"), bold=True)
74
+
75
+
76
+ def _step(n: int, total: int, title: str, tool: str) -> None:
77
+ click.echo()
78
+ click.echo(
79
+ click.style(f"[{n}/{total}] ", fg="cyan", bold=True)
80
+ + click.style(title, bold=True)
81
+ + click.style(f" {tool}", fg="bright_black")
82
+ )
83
+
84
+
85
+ def _line(text: str = "", **style: Any) -> None:
86
+ click.echo(" " + (click.style(text, **style) if style else text))
87
+
88
+
89
+ def _short(summary: str) -> str:
90
+ """Drop the table-name prefix and the lineage sentence (already shown in step 1)."""
91
+ s = summary.split(" sales.orders feeds")[0]
92
+ return s.removeprefix("sales.orders: ")
93
+
94
+
95
+ def _hits(rule_hits: list[dict[str, Any]]) -> None:
96
+ for h in rule_hits:
97
+ _line(click.style(f"[{h['verdict']}]", fg=_COLORS.get(h["verdict"], "white")) + f" {h['rule']}: {h['reason']}")
98
+
99
+
100
+ def run_demo(report_path: str | None = None) -> dict[str, Any]:
101
+ """Run the demo, print it, and return the key results (used by tests)."""
102
+ try:
103
+ from bricksentry.backends.duckdb_backend import DuckDBBackend
104
+
105
+ backend = DuckDBBackend()
106
+ except ImportError as e:
107
+ raise click.ClickException(
108
+ 'The demo runs on DuckDB. Install it with: pip install "bricksentry[duckdb]"'
109
+ ) from e
110
+
111
+ backend.execute("CREATE SCHEMA sales; CREATE SCHEMA sales_pr_42")
112
+ backend.execute(SEED_SQL)
113
+ sentry = Sentry(Config.from_dict(CONFIG), backend=backend)
114
+ previous = agent_tools._SENTRY
115
+ agent_tools.set_sentry(sentry)
116
+ results: dict[str, Any] = {}
117
+ try:
118
+ click.echo(
119
+ click.style("bricksentry demo", bold=True)
120
+ + click.style(" · 20,000-row sales.orders on local DuckDB; nothing leaves your machine", fg="bright_black")
121
+ )
122
+ click.echo(click.style("An AI agent is changing a revenue table. Watch what bricksentry tells it.", fg="bright_black"))
123
+ total = 5
124
+
125
+ _step(1, total, "Before editing: what depends on sales.orders?", "whats_downstream")
126
+ ds = agent_tools.whats_downstream("sales.orders")
127
+ _line("sales.orders")
128
+ children: dict[str, list[dict[str, Any]]] = {}
129
+ for n in ds["downstream"]:
130
+ children.setdefault(n["via"], []).append(n)
131
+
132
+ def walk(parent: str, prefix: str) -> None:
133
+ kids = children.get(parent, [])
134
+ for i, n in enumerate(kids):
135
+ last = i == len(kids) - 1
136
+ tags = " ".join(f"[{k}]" for k in n["tags"])
137
+ _line(
138
+ f"{prefix}{'└─' if last else '├─'} {n['kind']:<11} {n['name']:<22} "
139
+ + click.style(n["owner"] or "", fg="bright_black")
140
+ + (" " + click.style(tags, fg=_COLORS["needs_human"]) if tags else "")
141
+ )
142
+ walk(n["name"], prefix + (" " if last else "│ "))
143
+
144
+ walk("sales.orders", "")
145
+ results["downstream_count"] = ds["count"]
146
+
147
+ _step(2, total, "Capture a rollback plan first", "rollback_plan")
148
+ _line("On Databricks this returns the exact command, e.g.", fg="bright_black")
149
+ _line("RESTORE TABLE `main`.`sales`.`orders` TO VERSION AS OF 41")
150
+ _line("(DuckDB has no table history, so the demo skips it.)", fg="bright_black")
151
+
152
+ _step(3, total, "Agent wants to delete refunded orders. It previews first", "preview_write")
153
+ _line(DELETE_SQL, fg="bright_black")
154
+ p = agent_tools.preview_write(DELETE_SQL, "sales.orders")
155
+ _line(_verdict(p["verdict"]) + " " + _short(p["tables"][0]["summary"]))
156
+ _hits(p["rule_hits"])
157
+ prod_rows = backend.scalar("SELECT COUNT(*) FROM sales.orders")
158
+ _line(f"Ran on a disposable clone. Production still has {prod_rows:,} rows.", fg="green")
159
+ results["preview_verdict"] = p["verdict"]
160
+ results["production_rows_after_preview"] = prod_rows
161
+
162
+ _step(4, total, "Agent opens PR #42 instead. Its join has a fan-out bug", "assess_change")
163
+ backend.execute(BUGGY_SQL)
164
+ a = agent_tools.assess_change(["sales.orders"], pr="42")
165
+ _line(_verdict(a["verdict"]) + f" risk {a['risk_tier']}")
166
+ _hits(a["rule_hits"])
167
+ gate = agent_tools.safe_to_ship(a["id"])
168
+ _line("next_step: " + gate["next_step"], fg="cyan")
169
+ results["buggy_verdict"] = a["verdict"]
170
+
171
+ _step(5, total, "Agent fixes the join, rebuilds and checks again", "assess_change → safe_to_ship")
172
+ backend.execute(FIXED_SQL)
173
+ a2 = agent_tools.assess_change(["sales.orders"], pr="42")
174
+ explanation = agent_tools.explain_diff(assessment_id=a2["id"])["explanations"]["sales.orders"]
175
+ _line(_verdict(a2["verdict"]) + " " + _short(explanation))
176
+ _hits(a2["rule_hits"])
177
+ gate2 = agent_tools.safe_to_ship(a2["id"])
178
+ _line("next_step: " + gate2["next_step"], fg="cyan")
179
+ results["fixed_verdict"] = a2["verdict"]
180
+ results["notify"] = gate2["notify"]
181
+
182
+ if report_path:
183
+ from bricksentry.report import to_markdown
184
+
185
+ Path(report_path).write_text(to_markdown(sentry.get_assessment(a2["id"])))
186
+ click.echo()
187
+ click.echo(f"Wrote {report_path}: the pull-request comment a reviewer would see.")
188
+
189
+ click.echo()
190
+ click.echo(click.style("The agent was stopped once, corrected itself, and handed the final call to the owners.", bold=True))
191
+ click.echo("Next: run `bricksentry init` in your project, then see " + click.style(DOCS_URL, underline=True))
192
+ finally:
193
+ agent_tools.set_sentry(previous)
194
+ return results
@@ -61,13 +61,18 @@ def diff_tables(
61
61
  if columns:
62
62
  common = [c for c in common if c in columns]
63
63
 
64
+ # A marker column says whether a joined row exists on each side. Testing the key
65
+ # for NULL instead would count a NULL-key row as both added and removed.
66
+ present = q("__bs_present")
67
+
64
68
  def side(tbl: str, alias: str) -> str:
65
69
  where = f" WHERE {backend.sample_predicate(keys, sample_pct)}" if sample_pct else ""
66
- return f"{alias} AS (SELECT * FROM {backend.qualified(tbl)}{where})"
70
+ return f"{alias} AS (SELECT *, 1 AS {present} FROM {backend.qualified(tbl)}{where})"
67
71
 
68
72
  ctes = f"WITH {side(base, 'b_src')}, {side(candidate, 'c_src')}"
69
- join_on = " AND ".join(f"b.{q(k)} = c.{q(k)}" for k in keys)
70
- k0 = q(keys[0])
73
+ # Null-safe key match: a NULL key in production matches a NULL key in the candidate.
74
+ join_on = " AND ".join(f"b.{q(k)} IS NOT DISTINCT FROM c.{q(k)}" for k in keys)
75
+ in_b, in_c = f"b.{present} IS NOT NULL", f"c.{present} IS NOT NULL"
71
76
 
72
77
  def cmp(col: str) -> str:
73
78
  bc, cc = f"b.{q(col)}", f"c.{q(col)}"
@@ -76,12 +81,12 @@ def diff_tables(
76
81
  bc, cc = f"CAST({bc} AS {st})", f"CAST({cc} AS {st})"
77
82
  return f"{bc} IS DISTINCT FROM {cc}"
78
83
 
79
- both = f"b.{k0} IS NOT NULL AND c.{k0} IS NOT NULL"
84
+ both = f"{in_b} AND {in_c}"
80
85
  any_diff = " OR ".join(f"({cmp(c)})" for c in common) or "FALSE"
81
86
 
82
87
  selects = [
83
- f"SUM(CASE WHEN b.{k0} IS NULL THEN 1 ELSE 0 END) AS added_rows",
84
- f"SUM(CASE WHEN c.{k0} IS NULL THEN 1 ELSE 0 END) AS removed_rows",
88
+ f"SUM(CASE WHEN NOT ({in_b}) THEN 1 ELSE 0 END) AS added_rows",
89
+ f"SUM(CASE WHEN NOT ({in_c}) THEN 1 ELSE 0 END) AS removed_rows",
85
90
  f"SUM(CASE WHEN {both} AND ({any_diff}) THEN 1 ELSE 0 END) AS changed_rows",
86
91
  f"SUM(CASE WHEN {both} AND NOT ({any_diff}) THEN 1 ELSE 0 END) AS unchanged_rows",
87
92
  ]
@@ -96,7 +101,8 @@ def diff_tables(
96
101
 
97
102
  # Row counts, nulls, numeric sums per side.
98
103
  def profile(tbl_cte: str, cols: dict[str, str]) -> dict:
99
- parts = ["COUNT(*) AS n_rows"]
104
+ any_null_key = " OR ".join(f"{q(k)} IS NULL" for k in keys)
105
+ parts = ["COUNT(*) AS n_rows", f"SUM(CASE WHEN {any_null_key} THEN 1 ELSE 0 END) AS null_keys"]
100
106
  for i, col in enumerate(common):
101
107
  parts.append(f"SUM(CASE WHEN {q(col)} IS NULL THEN 1 ELSE 0 END) AS nul_{i}")
102
108
  if backend.is_numeric(cols[col]):
@@ -147,7 +153,7 @@ def diff_tables(
147
153
  continue
148
154
  b_seg = f"b.{q(seg)}" if seg in b_cols else "NULL"
149
155
  c_seg = f"c.{q(seg)}" if seg in c_cols else "NULL"
150
- affected = f"(b.{k0} IS NULL OR c.{k0} IS NULL OR ({any_diff}))"
156
+ affected = f"(NOT ({in_b}) OR NOT ({in_c}) OR ({any_diff}))"
151
157
  sql = (
152
158
  f"{ctes} SELECT COALESCE({c_seg}, {b_seg}) AS seg_value, COUNT(*) AS n "
153
159
  f"FROM b_src b FULL OUTER JOIN c_src c ON {join_on} WHERE {affected} "
@@ -171,6 +177,8 @@ def diff_tables(
171
177
  columns=col_changes,
172
178
  duplicate_keys_base=dupes("b_src"),
173
179
  duplicate_keys_candidate=dupes("c_src"),
180
+ null_keys_base=int(pb.get("null_keys") or 0),
181
+ null_keys_candidate=int(pc.get("null_keys") or 0),
174
182
  segments=segments,
175
183
  sampled_pct=sample_pct,
176
184
  )
@@ -73,6 +73,8 @@ def explain_diff(d: TableDiff) -> str:
73
73
 
74
74
  if d.duplicate_keys_candidate > d.duplicate_keys_base:
75
75
  s += f". WARNING: {_n(d.duplicate_keys_candidate)} duplicate key(s) on {', '.join(d.keys)}"
76
+ if d.null_keys_candidate:
77
+ s += f". Note: {_n(d.null_keys_candidate)} row(s) have a NULL key ({', '.join(d.keys)})"
76
78
  if d.sampled_pct:
77
79
  s += f" (based on a {d.sampled_pct:g}% key sample)"
78
80
  return s + "."
@@ -85,6 +85,8 @@ class TableDiff:
85
85
  columns: list[ColumnChange] = field(default_factory=list)
86
86
  duplicate_keys_base: int = 0
87
87
  duplicate_keys_candidate: int = 0
88
+ null_keys_base: int = 0
89
+ null_keys_candidate: int = 0
88
90
  segments: list[Segment] = field(default_factory=list)
89
91
  sampled_pct: float | None = None
90
92
  error: str | None = None
@@ -9,6 +9,9 @@ never from an LLM, so agents and CI get the same answer for the same change.
9
9
  - name: duplicate-keys
10
10
  when: {duplicate_keys: true}
11
11
  then: block
12
+ - name: new-null-keys
13
+ when: {null_keys: true}
14
+ then: warn
12
15
  - name: dropped-column
13
16
  when: {column_removed: true}
14
17
  then: needs_human
@@ -41,6 +44,7 @@ DEFAULT_POLICY: dict[str, Any] = {
41
44
  "rules": [
42
45
  {"name": "diff-failed", "when": {"diff_error": True}, "then": "needs_human"},
43
46
  {"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
47
+ {"name": "null-keys", "when": {"null_keys": True}, "then": "warn"},
44
48
  {"name": "dropped-column", "when": {"column_removed": True}, "then": "needs_human"},
45
49
  {"name": "type-change", "when": {"column_type_changed": True}, "then": "warn"},
46
50
  {"name": "certified-downstream", "when": {"downstream_tag": "certified"}, "then": "needs_human"},
@@ -57,7 +61,7 @@ KNOWN_CONDITIONS = {
57
61
  "table", "tag", "downstream_tag", "downstream_kind", "downstream_count_gt",
58
62
  "removed_pct_gt", "added_pct_gt", "changed_pct_gt", "row_count_change_pct_gt",
59
63
  "row_count_drop_pct_gt", "column_removed", "column_type_changed", "column_added",
60
- "duplicate_keys", "column", "sum_change_pct_gt", "null_increase_gt",
64
+ "duplicate_keys", "null_keys", "column", "sum_change_pct_gt", "null_increase_gt",
61
65
  "any_change", "diff_error",
62
66
  }
63
67
 
@@ -164,6 +168,12 @@ def _match(
164
168
  return False, ""
165
169
  reasons.append(f"{diff.duplicate_keys_candidate} duplicate key(s) in candidate (base had {diff.duplicate_keys_base})")
166
170
  continue
171
+ if cond == "null_keys":
172
+ new_nulls = diff.null_keys_candidate > diff.null_keys_base
173
+ if new_nulls != bool(val):
174
+ return False, ""
175
+ reasons.append(f"{diff.null_keys_candidate} row(s) with a NULL key in candidate (base had {diff.null_keys_base})")
176
+ continue
167
177
  if cond == "column_removed":
168
178
  if bool(diff.schema.removed) != bool(val):
169
179
  return False, ""
@@ -29,7 +29,7 @@ def to_markdown(a: Assessment, max_downstream: int = 15) -> str:
29
29
  f"**Risk tier:** `{v.risk_tier}` · **Tables checked:** {len(a.tables)} · **Assessment:** `{a.id}`",
30
30
  ]
31
31
  if a.notify:
32
- lines.append(f"**Review requested from:** {', '.join(a.notify)}")
32
+ lines += ["", f"**Review requested from:** {', '.join(a.notify)}"]
33
33
  lines.append("")
34
34
  if a.hits:
35
35
  lines += ["### Why", "", "| Verdict | Rule | Table | Reason |", "|---|---|---|---|"]
@@ -59,6 +59,8 @@ def test_markdown_report(sentry, backend):
59
59
  assert MARKER in md
60
60
  assert "Needs human review" in md
61
61
  assert "Blast radius" in md and "finance-team" in md
62
+ # the reviewers line is its own paragraph, not merged into the risk-tier line
63
+ assert "\n\n**Review requested from:**" in md
62
64
 
63
65
 
64
66
  def test_candidate_pattern():
@@ -72,3 +74,14 @@ def test_changed_tables_from_files():
72
74
  cfg = Config.from_dict({"tables": {"main.sales.orders": {"keys": ["id"], "paths": ["src/orders/**", "resources/orders.yml"]}}})
73
75
  assert tables_for_files(cfg, ["src/orders/transform.py"]) == ["main.sales.orders"]
74
76
  assert tables_for_files(cfg, ["README.md"]) == []
77
+
78
+
79
+ def test_new_null_keys_warn(backend):
80
+ from bricksentry import Sentry
81
+
82
+ backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders")
83
+ backend.execute("UPDATE sales_ci.orders SET order_id = NULL WHERE order_id = 7")
84
+ cfg = Config.from_dict({"tables": {"sales.orders": {"keys": ["order_id"]}}, "lineage": {"type": "static"}})
85
+ a = Sentry(cfg, backend=backend).assess(["sales.orders"])
86
+ assert "null-keys" in {h.rule for h in a.hits}
87
+ assert "NULL key" in a.tables[0].summary
@@ -0,0 +1,27 @@
1
+ from click.testing import CliRunner
2
+
3
+ from bricksentry import agent_tools
4
+ from bricksentry.cli import main
5
+ from bricksentry.demo import run_demo
6
+
7
+
8
+ def test_demo_results(capsys):
9
+ r = run_demo()
10
+ assert r["downstream_count"] == 5
11
+ assert r["preview_verdict"] == "needs_human"
12
+ assert r["production_rows_after_preview"] == 20000
13
+ assert r["buggy_verdict"] == "block"
14
+ assert r["fixed_verdict"] == "needs_human"
15
+ assert r["notify"] == ["finance-analytics", "sales-data-eng"]
16
+ out = capsys.readouterr().out
17
+ assert "duplicate-keys" in out and "Production still has 20,000 rows" in out
18
+ assert agent_tools._SENTRY is None # demo restores global agent state
19
+
20
+
21
+ def test_demo_cli_writes_report(tmp_path):
22
+ report = tmp_path / "report.md"
23
+ res = CliRunner().invoke(main, ["demo", "--report", str(report)])
24
+ assert res.exit_code == 0, res.output
25
+ assert "BLOCK" in res.output
26
+ text = report.read_text()
27
+ assert "Needs human review" in text and "finance-analytics" in text
@@ -73,3 +73,26 @@ def test_composite_keys(backend):
73
73
  backend.execute("UPDATE sales_ci.orders SET status = 'late' WHERE order_id = 7")
74
74
  d = diff_tables(backend, "sales.orders", "sales_ci.orders", ["order_id", "region"])
75
75
  assert d.changed_rows == 1
76
+
77
+
78
+ def test_null_keys_are_matched_not_double_counted(backend):
79
+ # Regression: a row whose key is NULL used to count as both added and removed.
80
+ backend.execute("CREATE SCHEMA s")
81
+ backend.execute(
82
+ "CREATE TABLE s.base AS SELECT * FROM (VALUES (NULL, 1.0), ('CA', 2.0), ('TX', 3.0), ('NY', 4.0)) t(state, v)"
83
+ )
84
+ # Unchanged NULL-key row: must be matched, not reported as added + removed.
85
+ backend.execute("CREATE TABLE s.same AS SELECT * FROM s.base")
86
+ d = diff_tables(backend, "s.base", "s.same", ["state"])
87
+ assert (d.added_rows, d.removed_rows, d.changed_rows) == (0, 0, 0)
88
+ assert d.is_identical and d.null_keys_base == 1
89
+
90
+ # NULL-key row changed: one changed row, nothing added or removed.
91
+ backend.execute("CREATE TABLE s.chg AS SELECT state, CASE WHEN state IS NULL THEN 9.0 ELSE v END AS v FROM s.base")
92
+ d = diff_tables(backend, "s.base", "s.chg", ["state"])
93
+ assert (d.added_rows, d.removed_rows, d.changed_rows) == (0, 0, 1)
94
+
95
+ # DELETE of three rows including the NULL-key row.
96
+ backend.execute("CREATE TABLE s.del AS SELECT * FROM s.base WHERE state = 'NY'")
97
+ d = diff_tables(backend, "s.base", "s.del", ["state"])
98
+ assert (d.added_rows, d.removed_rows) == (0, 3)
@@ -1,119 +0,0 @@
1
- """Runnable demo (no Databricks needed): an "agent" makes a buggy change, bricksentry
2
- catches it, the agent fixes it, and the gate routes the final change to a human.
3
-
4
- pip install "bricksentry[duckdb]"
5
- python examples/demo/agent_loop_demo.py
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import json
11
- import textwrap
12
-
13
- from bricksentry import Config, Sentry, agent_tools
14
- from bricksentry.backends.duckdb_backend import DuckDBBackend
15
-
16
-
17
- def banner(s: str) -> None:
18
- print("\n" + "=" * 78 + f"\n{s}\n" + "=" * 78)
19
-
20
-
21
- def show(obj, keys=None):
22
- if keys:
23
- obj = {k: obj[k] for k in keys if k in obj}
24
- print(textwrap.indent(json.dumps(obj, indent=2, default=str), " "))
25
-
26
-
27
- def seed(b: DuckDBBackend) -> None:
28
- b.execute("CREATE SCHEMA sales; CREATE SCHEMA sales_pr_42")
29
- b.execute(
30
- """
31
- CREATE TABLE sales.orders AS
32
- SELECT i AS order_id,
33
- ['APAC','EMEA','AMER'][1 + (i % 3)] AS region,
34
- round(20 + (i % 97) * 3.1, 2)::DOUBLE AS amount,
35
- CASE WHEN i % 10 = 0 THEN 'refunded' ELSE 'paid' END AS status
36
- FROM range(1, 20001) t(i)
37
- """
38
- )
39
-
40
-
41
- CONFIG = {
42
- "sandbox_schema": "sandbox",
43
- "candidate_pattern": "{schema}_pr_{pr}.{table}",
44
- "tables": {"sales.orders": {"keys": ["order_id"], "segment_by": ["region"]}},
45
- "lineage": {
46
- "type": "static",
47
- "edges": {
48
- "sales.orders": ["sales.daily_revenue", "job:orders_hourly", "dashboard:Exec Revenue"],
49
- "sales.daily_revenue": ["finance.month_close", "genie_space:Revenue Q&A"],
50
- },
51
- "owners": {"sales.orders": "sales-data-eng", "sales.daily_revenue": "finance-analytics",
52
- "finance.month_close": "finance-analytics"},
53
- "tags": {"sales.daily_revenue": {"certified": "true"}},
54
- },
55
- }
56
-
57
-
58
- def main() -> None:
59
- b = DuckDBBackend()
60
- seed(b)
61
- agent_tools.set_sentry(Sentry(Config.from_dict(CONFIG), backend=b))
62
-
63
- banner("1. Agent asks: what depends on sales.orders before I touch it?")
64
- ds = agent_tools.whats_downstream("sales.orders")
65
- for n in ds["downstream"]:
66
- print(f" depth {n['depth']} [{n['kind']}] {n['name']} {n['owner'] or ''} {n['tags'] or ''}")
67
-
68
- banner("2. Agent captures a rollback plan first")
69
- show(agent_tools.rollback_plan("sales.orders"), ["rollback_sql"])
70
-
71
- banner("3. Agent wants to 'clean up refunds' directly. It previews the write first")
72
- p = agent_tools.preview_write("DELETE FROM sales.orders WHERE status <> 'paid'", "sales.orders")
73
- print(" verdict:", p["verdict"], "| risk:", p["risk_tier"])
74
- print(" ", p["tables"][0]["summary"])
75
- print(" production rows still:", b.scalar("SELECT COUNT(*) FROM sales.orders"))
76
-
77
- banner("4. Agent instead edits the pipeline. Its first attempt has a join bug (fan-out)")
78
- b.execute(
79
- """
80
- CREATE TABLE sales_pr_42.orders AS
81
- SELECT o.order_id, o.region,
82
- CASE WHEN o.region = 'APAC' THEN round(o.amount * 0.92, 2) ELSE o.amount END AS amount,
83
- o.status
84
- FROM sales.orders o
85
- LEFT JOIN (SELECT * FROM (VALUES (1), (1)) v(k)) dup ON o.order_id % 500 = 0 AND dup.k = 1
86
- """
87
- )
88
- a = agent_tools.assess_change(["sales.orders"], pr="42")
89
- print(" verdict:", a["verdict"])
90
- for h in a["rule_hits"]:
91
- print(f" - [{h['verdict']}] {h['rule']}: {h['reason']}")
92
- gate = agent_tools.safe_to_ship(a["id"])
93
- print(" next_step:", gate["next_step"])
94
-
95
- banner("5. Agent fixes the join, rebuilds the candidate and assesses again")
96
- b.execute(
97
- """
98
- CREATE OR REPLACE TABLE sales_pr_42.orders AS
99
- SELECT order_id, region,
100
- CASE WHEN region = 'APAC' THEN round(amount * 0.92, 2) ELSE amount END AS amount,
101
- status
102
- FROM sales.orders
103
- """
104
- )
105
- a2 = agent_tools.assess_change(["sales.orders"], pr="42")
106
- print(" verdict:", a2["verdict"])
107
- print(" ", agent_tools.explain_diff(assessment_id=a2["id"])["explanations"]["sales.orders"])
108
- gate2 = agent_tools.safe_to_ship(a2["id"])
109
- print(" safe_to_ship:", gate2["safe_to_ship"])
110
- print(" next_step:", gate2["next_step"])
111
-
112
- banner("6. The PR comment a human reviewer sees")
113
- from bricksentry.report import to_markdown
114
-
115
- print(to_markdown(agent_tools.get_sentry().get_assessment(a2["id"])))
116
-
117
-
118
- if __name__ == "__main__":
119
- main()
File without changes
File without changes
File without changes