bricksentry 0.1.25__tar.gz → 0.1.27__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.
- {bricksentry-0.1.25 → bricksentry-0.1.27}/CHANGELOG.md +26 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/PKG-INFO +31 -3
- {bricksentry-0.1.25 → bricksentry-0.1.27}/README.md +30 -2
- bricksentry-0.1.27/deploy/databricks-app/requirements.txt +1 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_validation.ipynb +1 -1
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_validation.py +1 -1
- {bricksentry-0.1.25 → bricksentry-0.1.27}/pyproject.toml +1 -1
- {bricksentry-0.1.25 → bricksentry-0.1.27}/server.json +2 -2
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/__init__.py +1 -1
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/agent_tools.py +45 -8
- bricksentry-0.1.27/src/bricksentry/agent_view.py +125 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/assess.py +21 -2
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/backends/base.py +33 -4
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/backends/databricks_backend.py +34 -6
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/backends/duckdb_backend.py +14 -5
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/config.py +40 -2
- bricksentry-0.1.27/src/bricksentry/diff.py +466 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/explain.py +26 -6
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/history.py +39 -3
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/models.py +11 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/policy.py +62 -14
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/report.py +20 -2
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/validation.py +67 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/databricks_template_schema.json +2 -2
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0123.py +2 -2
- bricksentry-0.1.27/tests/test_0126.py +173 -0
- bricksentry-0.1.27/tests/test_0127.py +267 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_assess_policy.py +3 -4
- bricksentry-0.1.25/deploy/databricks-app/requirements.txt +0 -1
- bricksentry-0.1.25/src/bricksentry/diff.py +0 -284
- {bricksentry-0.1.25 → bricksentry-0.1.27}/.gitignore +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/CONTRIBUTING.md +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/LICENSE +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/SECURITY.md +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/action.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/container/Dockerfile +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/databricks-app/README.md +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/databricks-app/app.yaml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/databricks-app/bricksentry.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/databricks-app/databricks.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/deploy/databricks-app/grants.sql +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_check_my_table.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/bricksentry_quickstart.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/github-workflow.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/databricks/policy.yml +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/examples/demo/agent_loop_demo.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/scripts/build_notebook.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/scripts/render_demo_image.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/__main__.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/backends/__init__.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/changes.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/cli.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/demo.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/github.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/job.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/job_demo.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/lineage.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/mcp_server.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/measures.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/netguard.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/notify.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/policy_templates.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/preview.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/src/bricksentry/py.typed +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/README.md +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/conftest.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0110.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0112.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0114.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0120.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0121.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_0122.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_018.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_019.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_check_notebook.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_databricks_and_uc.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_demo.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_diff.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_hr_notebook.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_notebook.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_notify_templates.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_preview_agents.py +0 -0
- {bricksentry-0.1.25 → bricksentry-0.1.27}/tests/test_sample_guard_and_store.py +0 -0
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.27 (2026-11-17)
|
|
4
|
+
|
|
5
|
+
A safety release. A live round of leak, data-shape and race tests on 0.1.26 found four problems; two could mislead. A verification round re-ran every original attack on the fixes: no production value reached an agent, mid-diff rewrites returned the pinned state 3 of 3 times, MAP diffs and the key-order trap were exact, and the 14-scenario battery passed 14 of 14. Pinning makes a diff slower (a 1M-row diff took about 10 s instead of 5 s); that will be reduced in a later release.
|
|
6
|
+
|
|
7
|
+
- **Agents never get production values.** `preview_write` returned up to 5 before→after values per changed column, so an agent with no access to a table could "update" chosen rows and read their old values (SSNs, salaries) back, because bricksentry does the reading. Every agent tool (MCP and `bricksentry.agent_tools`) now returns counts, columns, schema, null counts, percentages and verdicts, never values: no example values on either side (an agent can copy a value into the "new" side), no absolute totals (a total over one row is the value; percentages are rounded to one decimal), no segment values, and quoted values are removed from engine errors. Humans keep the detail in the CLI, Python API and reports, except values in `pii`-tagged tables and columns, which reports never show. Rule reasons no longer contain totals ("sum(amount) moved from 0").
|
|
8
|
+
- **`agent_tables`** in bricksentry.yml lists the tables agents may assess or preview (globs, any case); others are refused. Counts alone can still be probed (`DELETE ... WHERE ssn LIKE '1%'`), which only limiting tables can stop. Every agent `assess_change` / `preview_write` is logged to `bricksentry.audit` and `audit.jsonl` in the assessment store. The README has a table of what each tool can reveal.
|
|
9
|
+
- **Every diff reads one consistent version of each table.** The diff runs several queries; a table rewritten between them mixed two states (a candidate replaced mid-diff gave changed=49 when the old state had 5 and the new 50). Both tables are now pinned to their Delta version at the start (`VERSION AS OF`, schema included), and a candidate that changes during the check gets `needs_human` ("changed-during-check"). Objects that can't time travel are checked before and after.
|
|
10
|
+
- **MAP columns no longer fail the whole diff.** Spark can't compare or hash maps, so one MAP column gave `diff-failed`. Maps are compared by their entries sorted by key (equal maps written in another order are equal); maps nested in structs or arrays as JSON. A column the engine still can't compare is left out with a note and the check asks a human (`columns-not-compared`), instead of losing the diff.
|
|
11
|
+
- **Float rounding.** FLOAT/DOUBLE stay exact by default, but a column that changed everywhere while its total stayed the same gets a note that it's likely rounding. New opt-in `float_tolerance` (relative, e.g. `1e-9`); NaN, infinity and NULL still compare exactly; DECIMAL is always exact.
|
|
12
|
+
- **Key names match case-insensitively** (`keys: [ID]` finds `id`), like the engine.
|
|
13
|
+
- New validation scenarios `agent_sees_no_values` and `map_column` (the battery is now 14).
|
|
14
|
+
|
|
15
|
+
## 0.1.26 (2026-11-17)
|
|
16
|
+
|
|
17
|
+
Fixes for what two worst-case live tests of 0.1.25 on Databricks found. A pre-release check passed on two Databricks Free Edition workspaces (47 of 47 on the first), including the 12-scenario validation battery and before/after repros of every fix.
|
|
18
|
+
|
|
19
|
+
- **A changed copy of a duplicated key no longer shifts how the other copies pair.** 0.1.23 numbered the copies of a key by row hash and matched copy *n* with copy *n*, so one changed copy could move every copy after it: 2,000 rows sharing a NULL key with 2 real changes reported over a thousand changed rows (50,000 such rows: 36,563). Identical copies are now matched first; only the copies left over are paired. The same test now reports exactly 2 changed. New validation scenario `null_keys_changed`.
|
|
20
|
+
- **A total moving away from zero now fires `sum_change_pct_gt`.** A column whose total went from 0 to 5 had no percentage change, so the rule never matched. It now matches, with the reason "sum(col) 0 -> 5", and the plain-English explanation lists it under totals.
|
|
21
|
+
- **An overflowing exact total no longer loses the whole diff.** If a `DECIMAL(38)` total overflows, totals fall back to `DOUBLE` (or are skipped), the row counts and changes are still reported, and the diff notes it.
|
|
22
|
+
- **The rollback warning lists newer table changes that aren't data** (renamed columns, table properties, constraints): `RESTORE` undoes those too. Maintenance (OPTIMIZE, VACUUM, ANALYZE) is still ignored.
|
|
23
|
+
- **Clearer policy mistakes.** A verdict typo (`then: blok`) names the valid verdicts; verdicts are accepted in any case; `policy: strict` without `builtin:` says to write `builtin:strict`; a policy with no rules warns that every change will pass.
|
|
24
|
+
- **Behavior change: no-op pull requests to pii and certified-fed tables now pass.** The default rules `pii-table` and `certified-downstream` now have `any_change: true`, like `dashboard-downstream`: they fire on any added, removed or changed row, any schema change or new duplicate keys, but not when the candidate is identical to production (before, that got `needs_human` with nothing to review). A failed or missing diff still counts as a change, for every `any_change` rule. To require a review regardless, add a custom rule such as `{name: pii-review, when: {tag: pii}, then: needs_human}`. New validation scenario `pii_noop` (identical rebuild: pass; 1-row edit: needs_human). Found in a live test of 0.1.25.
|
|
25
|
+
- `preview_write` / `bricksentry preview` show one line when the clone or the statement fails ("The statement failed on the preview clone, so production was not touched: …") instead of the engine's full error. MCP tool errors keep only the first line.
|
|
26
|
+
- The MCP tools `whats_downstream` and `rollback_plan` report a mistyped or missing table as "Table … not found" instead of an empty downstream list (which read as "nothing is downstream") or advice to take a snapshot. Found in the pre-release check.
|
|
27
|
+
- A misspelled key under `backend:` in `bricksentry.yml` (say `path:` instead of `database:`) is rejected with the valid keys, instead of being ignored and connecting somewhere else. Found in the pre-release check.
|
|
28
|
+
|
|
3
29
|
## 0.1.25 (2026-11-16)
|
|
4
30
|
|
|
5
31
|
- **Validation you can reproduce.** `VALIDATION.md` records every live test on Databricks with its numbers, the results that weren't perfect and the bugs each test found. `bricksentry.validation.run_validation()` and the new notebook `examples/databricks/bricksentry_validation.py` run the same ten risky changes on your own workspace in a scratch schema and drop everything afterwards. A new issue form, "Validation report", collects results from other setups.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bricksentry
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.27
|
|
4
4
|
Summary: Change impact analysis and deployment guardrails for data changes on Databricks, for pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
|
|
5
5
|
Project-URL: Homepage, https://bricksentry.org
|
|
6
6
|
Project-URL: Documentation, https://bricksentry.org/docs
|
|
@@ -200,6 +200,26 @@ Designed for agents:
|
|
|
200
200
|
- **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.
|
|
201
201
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
202
202
|
|
|
203
|
+
### What an agent can learn about your data
|
|
204
|
+
|
|
205
|
+
bricksentry usually runs with more read access than the agent that calls it, so the tools are built so an agent never sees production *values*:
|
|
206
|
+
|
|
207
|
+
| Tool | What the agent gets | What it never gets |
|
|
208
|
+
|---|---|---|
|
|
209
|
+
| `whats_downstream`, `rollback_plan` | Table and column names, owners, tags, versions | Any row data |
|
|
210
|
+
| `preview_write`, `assess_change` | Row counts (added, removed, changed), changed columns, schema changes, null counts, duplicate keys, total changes as a percentage (one decimal), the verdict and rule reasons | Example values (before or after), absolute totals, segment values, quoted values in engine errors |
|
|
211
|
+
| `explain_diff`, `safe_to_ship` | The same, as text | The same |
|
|
212
|
+
|
|
213
|
+
The new value is hidden too, because an agent can write `SET note = ssn` and read its own "new" value. Humans keep the detail: the CLI, the Python API and the pull-request report show example values, except in tables or columns tagged `pii`, whose values a report never shows.
|
|
214
|
+
|
|
215
|
+
**Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may assess or preview:
|
|
216
|
+
|
|
217
|
+
```yaml
|
|
218
|
+
agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Without `agent_tables`, agents can check any table bricksentry can read. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
|
|
222
|
+
|
|
203
223
|
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.
|
|
204
224
|
|
|
205
225
|
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.
|
|
@@ -344,6 +364,8 @@ backend: {type: databricks, warehouse_id: abc123} # auth: standard Databric
|
|
|
344
364
|
sandbox_schema: main.bricksentry_sandbox
|
|
345
365
|
candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
|
|
346
366
|
sample_pct: 10 # sample_guard re-checks the whole table (on by default)
|
|
367
|
+
float_tolerance: 1e-9 # optional: FLOAT/DOUBLE within this relative difference count as equal
|
|
368
|
+
agent_tables: ["main.sales_dev.*"] # optional: tables AI agents may assess or preview (see above)
|
|
347
369
|
assessment_store: ~/.bricksentry/assessments # or false to keep assessments in memory
|
|
348
370
|
lineage: {type: databricks, depth: 3, lookback_days: 90, column_depth: 2} # also: exclude, exclude_dropped
|
|
349
371
|
tables:
|
|
@@ -374,6 +396,10 @@ lineage:
|
|
|
374
396
|
|
|
375
397
|
Typos are caught: an unknown key such as `sample_pc` prints a warning that names the right one (`did you mean 'sample_pct'?`) instead of being silently ignored.
|
|
376
398
|
|
|
399
|
+
**Consistent reads.** Every diff reads both tables at the Delta version they had when it started (`VERSION AS OF`), so a job writing to them mid-check can't mix two states into one result. If the candidate gets a new version during the check, the result says so and asks a human to re-run. Views and other objects without time travel are read as they are, with a before-and-after version check.
|
|
400
|
+
|
|
401
|
+
**Floats.** FLOAT and DOUBLE are compared exactly by default, so `0.1 + 0.2` and `0.3` differ. If a column changes everywhere but its total stays the same, the diff says it's likely rounding. Set `float_tolerance` to compare within a relative tolerance; NaN, infinity and NULL still compare exactly, and DECIMAL is always exact. MAP columns are compared by their entries sorted by key, so a map written in a different order isn't a change. A column the engine can't compare at all is left out with a note, and the check asks a human.
|
|
402
|
+
|
|
377
403
|
**Which totals are checked.** `sum_change_pct_gt` rules and summaries look at measures: by default every numeric column except keys and columns whose names look like IDs, codes, years and other date parts, coordinates, ratings, scores or rates (a 10% drop in `sum(established_year)` only says rows were removed). List `measures` for a table to choose exactly, or set `measures: all` to check every numeric column. A rule that names a column (`when: {column: rating, sum_change_pct_gt: 1}`) always checks it.
|
|
378
404
|
|
|
379
405
|
### Policy example
|
|
@@ -428,6 +454,8 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
|
|
|
428
454
|
|
|
429
455
|
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `changed_column` (glob) · `changed_column_tag` · `downstream_column_tag` · `any_change` · `diff_error` · `lineage_error`
|
|
430
456
|
|
|
457
|
+
**The pii and certified gates skip changes that change nothing.** In the default policy, `pii-table` (the table is tagged `pii`) and `certified-downstream` (it feeds something tagged `certified`) fire only when the diff shows a change: rows added, removed or changed, a schema change or new duplicate keys. A rebuild identical to production passes. A failed or missing diff still counts as a possible change. To require a review of every pull request touching a PII table regardless, add a rule without `any_change`: `{name: pii-review, when: {tag: pii}, then: needs_human}`.
|
|
458
|
+
|
|
431
459
|
**Column conditions** look only at the columns the change touched (changed values, new NULLs, dropped or retyped): `changed_column_tag: pii` matches when one of them is tagged `pii` in Unity Catalog, and `downstream_column_tag: certified` when one of them feeds a column tagged `certified`, following `system.access.column_lineage` up to `lineage.column_depth` hops (default 2; `0` turns it off). The default policy asks a human when a `pii` column changes; `strict`, `agent-safe` and `certified` also flag changes that feed certified columns.
|
|
432
460
|
|
|
433
461
|
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.
|
|
@@ -450,7 +478,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
|
|
|
450
478
|
|
|
451
479
|
## What a check costs
|
|
452
480
|
|
|
453
|
-
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries: a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
481
|
+
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus a few cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
454
482
|
|
|
455
483
|
## Audit trail
|
|
456
484
|
|
|
@@ -461,7 +489,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
|
|
|
461
489
|
- **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
|
|
462
490
|
- **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
|
|
463
491
|
- **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
|
|
464
|
-
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.
|
|
492
|
+
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.27 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, and a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
|
|
465
493
|
|
|
466
494
|
## Roadmap
|
|
467
495
|
|
|
@@ -153,6 +153,26 @@ Designed for agents:
|
|
|
153
153
|
- **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.
|
|
154
154
|
- **Assessments are saved** as JSON (default `~/.bricksentry/assessments`), so `explain_diff` and `safe_to_ship` work from another process or a fresh `Sentry`.
|
|
155
155
|
|
|
156
|
+
### What an agent can learn about your data
|
|
157
|
+
|
|
158
|
+
bricksentry usually runs with more read access than the agent that calls it, so the tools are built so an agent never sees production *values*:
|
|
159
|
+
|
|
160
|
+
| Tool | What the agent gets | What it never gets |
|
|
161
|
+
|---|---|---|
|
|
162
|
+
| `whats_downstream`, `rollback_plan` | Table and column names, owners, tags, versions | Any row data |
|
|
163
|
+
| `preview_write`, `assess_change` | Row counts (added, removed, changed), changed columns, schema changes, null counts, duplicate keys, total changes as a percentage (one decimal), the verdict and rule reasons | Example values (before or after), absolute totals, segment values, quoted values in engine errors |
|
|
164
|
+
| `explain_diff`, `safe_to_ship` | The same, as text | The same |
|
|
165
|
+
|
|
166
|
+
The new value is hidden too, because an agent can write `SET note = ssn` and read its own "new" value. Humans keep the detail: the CLI, the Python API and the pull-request report show example values, except in tables or columns tagged `pii`, whose values a report never shows.
|
|
167
|
+
|
|
168
|
+
**Counts can still leak information.** An agent could preview `DELETE ... WHERE ssn LIKE '1%'` and read the number of removed rows, then narrow it down. No masking stops that, so list the tables agents may assess or preview:
|
|
169
|
+
|
|
170
|
+
```yaml
|
|
171
|
+
agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Without `agent_tables`, agents can check any table bricksentry can read. Run the MCP server under an identity that can read only what the agent should. Every agent `assess_change` and `preview_write`, refused or not, is logged to `bricksentry.audit` and to `audit.jsonl` in the assessment store (time, actor, tables, verdict, row counts), so a run of small probing previews is visible.
|
|
175
|
+
|
|
156
176
|
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.
|
|
157
177
|
|
|
158
178
|
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.
|
|
@@ -297,6 +317,8 @@ backend: {type: databricks, warehouse_id: abc123} # auth: standard Databric
|
|
|
297
317
|
sandbox_schema: main.bricksentry_sandbox
|
|
298
318
|
candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
|
|
299
319
|
sample_pct: 10 # sample_guard re-checks the whole table (on by default)
|
|
320
|
+
float_tolerance: 1e-9 # optional: FLOAT/DOUBLE within this relative difference count as equal
|
|
321
|
+
agent_tables: ["main.sales_dev.*"] # optional: tables AI agents may assess or preview (see above)
|
|
300
322
|
assessment_store: ~/.bricksentry/assessments # or false to keep assessments in memory
|
|
301
323
|
lineage: {type: databricks, depth: 3, lookback_days: 90, column_depth: 2} # also: exclude, exclude_dropped
|
|
302
324
|
tables:
|
|
@@ -327,6 +349,10 @@ lineage:
|
|
|
327
349
|
|
|
328
350
|
Typos are caught: an unknown key such as `sample_pc` prints a warning that names the right one (`did you mean 'sample_pct'?`) instead of being silently ignored.
|
|
329
351
|
|
|
352
|
+
**Consistent reads.** Every diff reads both tables at the Delta version they had when it started (`VERSION AS OF`), so a job writing to them mid-check can't mix two states into one result. If the candidate gets a new version during the check, the result says so and asks a human to re-run. Views and other objects without time travel are read as they are, with a before-and-after version check.
|
|
353
|
+
|
|
354
|
+
**Floats.** FLOAT and DOUBLE are compared exactly by default, so `0.1 + 0.2` and `0.3` differ. If a column changes everywhere but its total stays the same, the diff says it's likely rounding. Set `float_tolerance` to compare within a relative tolerance; NaN, infinity and NULL still compare exactly, and DECIMAL is always exact. MAP columns are compared by their entries sorted by key, so a map written in a different order isn't a change. A column the engine can't compare at all is left out with a note, and the check asks a human.
|
|
355
|
+
|
|
330
356
|
**Which totals are checked.** `sum_change_pct_gt` rules and summaries look at measures: by default every numeric column except keys and columns whose names look like IDs, codes, years and other date parts, coordinates, ratings, scores or rates (a 10% drop in `sum(established_year)` only says rows were removed). List `measures` for a table to choose exactly, or set `measures: all` to check every numeric column. A rule that names a column (`when: {column: rating, sum_change_pct_gt: 1}`) always checks it.
|
|
331
357
|
|
|
332
358
|
### Policy example
|
|
@@ -381,6 +407,8 @@ Use one directly with `policy: builtin:finance`, or write an editable copy with
|
|
|
381
407
|
|
|
382
408
|
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `changed_column` (glob) · `changed_column_tag` · `downstream_column_tag` · `any_change` · `diff_error` · `lineage_error`
|
|
383
409
|
|
|
410
|
+
**The pii and certified gates skip changes that change nothing.** In the default policy, `pii-table` (the table is tagged `pii`) and `certified-downstream` (it feeds something tagged `certified`) fire only when the diff shows a change: rows added, removed or changed, a schema change or new duplicate keys. A rebuild identical to production passes. A failed or missing diff still counts as a possible change. To require a review of every pull request touching a PII table regardless, add a rule without `any_change`: `{name: pii-review, when: {tag: pii}, then: needs_human}`.
|
|
411
|
+
|
|
384
412
|
**Column conditions** look only at the columns the change touched (changed values, new NULLs, dropped or retyped): `changed_column_tag: pii` matches when one of them is tagged `pii` in Unity Catalog, and `downstream_column_tag: certified` when one of them feeds a column tagged `certified`, following `system.access.column_lineage` up to `lineage.column_depth` hops (default 2; `0` turns it off). The default policy asks a human when a `pii` column changes; `strict`, `agent-safe` and `certified` also flag changes that feed certified columns.
|
|
385
413
|
|
|
386
414
|
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.
|
|
@@ -403,7 +431,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
|
|
|
403
431
|
|
|
404
432
|
## What a check costs
|
|
405
433
|
|
|
406
|
-
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries: a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
434
|
+
The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus a few cheap metadata queries to pin each table's Delta version): a duplicate-key count on each side, one full outer join on the key columns, and one profile (row count, nulls, totals) per side, plus up to ten small queries for example values. Each reads both versions of the table, so cost grows with table size: seconds for millions of rows, minutes and real warehouse cost for hundreds of millions. For big tables, set `sample_pct` (a fixed hash sample of keys, checked against a full-table checksum so a change outside the sample isn't missed), or check only the tables that matter. Lineage lookups are one query per depth level, bounded by `lookback_days`.
|
|
407
435
|
|
|
408
436
|
## Audit trail
|
|
409
437
|
|
|
@@ -414,7 +442,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
|
|
|
414
442
|
- **Lineage is recorded at runtime.** Brand-new tables have no downstream history yet. Unity Catalog doesn't capture RDD operations, and UDFs hide column-level mapping; column lineage records source-to-target derivations, so a column used only in a filter or join may not appear.
|
|
415
443
|
- **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
|
|
416
444
|
- **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
|
|
417
|
-
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.
|
|
445
|
+
- **Validated on Databricks** (serverless, November 2026): a 2-million-row table with 0.1.4 (lineage, rollback plans, previews on shallow clones, every verdict level, the sampling guard catching a single changed row), then live runs of every release up to 0.1.27 on a Free Edition workspace with an HR pipeline: pull-request gating with comment updates, the bundle demo job, `check-last-change` and the newer-changes warning in the CLI, report, JSON and Slack, the refused-statement guards, outbound-URL checks, one-to-one matching of 2,000 NULL keys, exact totals over a million decimal rows, the audit trail, an AI agent attempting six risky changes on the live pipeline, the job task blocking a bad MERGE inside a real Databricks job, and worst-case rounds (50,000 NULL keys, near-max decimals, exotic types, 200-column tables) whose five findings were fixed in 0.1.26, and a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27. Every run, with its numbers and the bugs it found, is in [VALIDATION.md](VALIDATION.md). The automated tests use DuckDB and a mocked SDK, so please run the [validation notebook](examples/databricks/bricksentry_validation.py) on your workspace and [share a validation report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml), whether it passes or not.
|
|
418
446
|
|
|
419
447
|
## Roadmap
|
|
420
448
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bricksentry[databricks,mcp]==0.1.27
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"source": [
|
|
7
7
|
"# Validate bricksentry on your own workspace\n",
|
|
8
8
|
"\n",
|
|
9
|
-
"**
|
|
9
|
+
"**14 risky changes, about 3 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
|
|
10
10
|
"validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),\n",
|
|
11
11
|
"so you can check the results yourself instead of taking our word for them.\n",
|
|
12
12
|
"\n",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
# MAGIC %md
|
|
3
3
|
# MAGIC # Validate bricksentry on your own workspace
|
|
4
4
|
# MAGIC
|
|
5
|
-
# MAGIC **
|
|
5
|
+
# MAGIC **14 risky changes, about 3 minutes, nothing outside a scratch schema touched.** This notebook runs the same
|
|
6
6
|
# MAGIC validation battery we publish in [VALIDATION.md](https://github.com/bricksentry/bricksentry/blob/main/VALIDATION.md),
|
|
7
7
|
# MAGIC so you can check the results yourself instead of taking our word for them.
|
|
8
8
|
# MAGIC
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bricksentry"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.27"
|
|
8
8
|
description = "Change impact analysis and deployment guardrails for data changes on Databricks, for pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
10
|
"websiteUrl": "https://bricksentry.org",
|
|
11
|
-
"version": "0.1.
|
|
11
|
+
"version": "0.1.27",
|
|
12
12
|
"packages": [
|
|
13
13
|
{
|
|
14
14
|
"registryType": "pypi",
|
|
15
15
|
"identifier": "bricksentry-mcp",
|
|
16
|
-
"version": "0.1.
|
|
16
|
+
"version": "0.1.27",
|
|
17
17
|
"runtimeHint": "uvx",
|
|
18
18
|
"transport": {
|
|
19
19
|
"type": "stdio"
|
|
@@ -12,6 +12,7 @@ from __future__ import annotations
|
|
|
12
12
|
import functools
|
|
13
13
|
from typing import Annotated, Any
|
|
14
14
|
|
|
15
|
+
from bricksentry import agent_view
|
|
15
16
|
from bricksentry.assess import Sentry
|
|
16
17
|
from bricksentry.explain import explain_diff as _explain_diff
|
|
17
18
|
|
|
@@ -47,7 +48,11 @@ def _safe(fn):
|
|
|
47
48
|
try:
|
|
48
49
|
return fn(*args, **kwargs)
|
|
49
50
|
except Exception as e:
|
|
50
|
-
|
|
51
|
+
text = str(e).strip()
|
|
52
|
+
line = text.splitlines()[0] if text else ""
|
|
53
|
+
if len(line) > 300:
|
|
54
|
+
line = line[:297] + "..."
|
|
55
|
+
return {"error": agent_view.redact_values(f"{type(e).__name__}: {line}")}
|
|
51
56
|
|
|
52
57
|
return wrapper
|
|
53
58
|
|
|
@@ -79,6 +84,9 @@ def whats_downstream(
|
|
|
79
84
|
s = get_sentry()
|
|
80
85
|
nodes = s.downstream(table, depth)
|
|
81
86
|
owner, tags = s.lineage.owner_and_tags(table)
|
|
87
|
+
if not nodes and not owner and not tags and not s.backend.table_exists(table):
|
|
88
|
+
# An empty answer for a mistyped name would read as "nothing is downstream".
|
|
89
|
+
raise LookupError(_not_found(table))
|
|
82
90
|
out: dict[str, Any] = {
|
|
83
91
|
"table": table,
|
|
84
92
|
"owner": owner,
|
|
@@ -120,8 +128,13 @@ def assess_change(
|
|
|
120
128
|
notify, rule_hits, tables: [{table, verdict, summary, diff, downstream,
|
|
121
129
|
changed_columns, column_tags, column_downstream,
|
|
122
130
|
rollback}]}. Pass `id` to safe_to_ship (and optionally explain_diff)."""
|
|
123
|
-
|
|
124
|
-
|
|
131
|
+
s = get_sentry()
|
|
132
|
+
tables = list(tables)
|
|
133
|
+
_gate(s, "assess_change", tables)
|
|
134
|
+
a = s.assess(tables, candidates=candidates, pr=pr)
|
|
135
|
+
out = agent_view.for_agent(a, s)
|
|
136
|
+
agent_view.audit(s, "assess_change", tables, out)
|
|
137
|
+
return out
|
|
125
138
|
|
|
126
139
|
|
|
127
140
|
@_safe
|
|
@@ -148,7 +161,13 @@ def preview_write(
|
|
|
148
161
|
|
|
149
162
|
Returns the same shape as assess_change (with an `id` for safe_to_ship), or
|
|
150
163
|
{error} if the statement is refused or fails."""
|
|
151
|
-
|
|
164
|
+
s = get_sentry()
|
|
165
|
+
_gate(s, "preview_write", [target])
|
|
166
|
+
raw = s.preview_write(sql, target, keys=keys)
|
|
167
|
+
a = s.get_assessment(raw["id"])
|
|
168
|
+
out = agent_view.for_agent(a, s, {"preview": raw.get("preview")}) if a else agent_view.scrub(raw)
|
|
169
|
+
agent_view.audit(s, "preview_write", [target], out)
|
|
170
|
+
return out
|
|
152
171
|
|
|
153
172
|
|
|
154
173
|
@_safe
|
|
@@ -174,12 +193,14 @@ def explain_diff(
|
|
|
174
193
|
a = s.get_assessment(assessment_id)
|
|
175
194
|
if a is None:
|
|
176
195
|
return {"error": f"unknown assessment id {assessment_id}"}
|
|
177
|
-
|
|
196
|
+
safe = agent_view.for_agent(a, s)
|
|
197
|
+
return {"assessment_id": a.id, "explanations": {t["table"]: t["summary"] for t in safe["tables"]}}
|
|
178
198
|
if table:
|
|
179
199
|
d = s.get_diff(table)
|
|
180
200
|
if d is None:
|
|
181
201
|
return {"error": f"no diff for {table} yet; call assess_change or preview_write first"}
|
|
182
|
-
return {"table": table,
|
|
202
|
+
return {"table": table,
|
|
203
|
+
"explanation": _explain_diff(d, s.config.spec(table).measures, for_agent=True)}
|
|
183
204
|
return {"error": "pass assessment_id or table"}
|
|
184
205
|
|
|
185
206
|
|
|
@@ -214,7 +235,7 @@ def safe_to_ship(
|
|
|
214
235
|
"safe_to_ship": v in ("pass", "warn"),
|
|
215
236
|
"verdict": v,
|
|
216
237
|
"risk_tier": a.verdict.risk_tier,
|
|
217
|
-
"rule_hits": [h.to_dict() for h in a.hits],
|
|
238
|
+
"rule_hits": agent_view.scrub([h.to_dict() for h in a.hits], "rule_hits"),
|
|
218
239
|
"notify": a.notify,
|
|
219
240
|
"next_step": next_step,
|
|
220
241
|
}
|
|
@@ -233,12 +254,28 @@ def rollback_plan(
|
|
|
233
254
|
Returns {table, current_version, rollback_sql}, e.g. "RESTORE TABLE
|
|
234
255
|
main.sales.orders TO VERSION AS OF 42", or {error}."""
|
|
235
256
|
s = get_sentry()
|
|
257
|
+
version = s.backend.current_version(table)
|
|
258
|
+
if version is None and not s.backend.table_exists(table):
|
|
259
|
+
raise LookupError(_not_found(table))
|
|
236
260
|
return {
|
|
237
261
|
"table": table,
|
|
238
|
-
"current_version":
|
|
262
|
+
"current_version": version,
|
|
239
263
|
"rollback_sql": s.rollback_plan(table),
|
|
240
264
|
}
|
|
241
265
|
|
|
242
266
|
|
|
267
|
+
def _gate(s: Sentry, tool: str, tables: list[str]) -> None:
|
|
268
|
+
try:
|
|
269
|
+
agent_view.check_allowed(s, tables)
|
|
270
|
+
except PermissionError as e:
|
|
271
|
+
agent_view.audit(s, tool, tables, refused=str(e))
|
|
272
|
+
raise
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _not_found(table: str) -> str:
|
|
276
|
+
return (f"Table {table} not found. Check the catalog, schema and table name (they must match "
|
|
277
|
+
"Unity Catalog exactly) and that you have SELECT on it.")
|
|
278
|
+
|
|
279
|
+
|
|
243
280
|
TOOLS = [whats_downstream, assess_change, preview_write, explain_diff, safe_to_ship, rollback_plan]
|
|
244
281
|
READ_ONLY = {"whats_downstream", "assess_change", "explain_diff", "safe_to_ship", "rollback_plan"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""What an AI agent is allowed to see.
|
|
2
|
+
|
|
3
|
+
bricksentry usually runs with more read access than the agent calling it (the MCP
|
|
4
|
+
server or a job identity can read production; the agent should not). So everything
|
|
5
|
+
returned to an agent goes through :func:`for_agent`:
|
|
6
|
+
|
|
7
|
+
* no row values: ``samples`` (before -> after values) are removed;
|
|
8
|
+
* no absolute totals: ``base_sum`` / ``candidate_sum`` are removed and the percentage
|
|
9
|
+
change is rounded to one decimal (a total over a few rows *is* the values);
|
|
10
|
+
* no segment values: segments keep their column and row count, not the value;
|
|
11
|
+
* engine errors lose quoted literals (``The value '123-45-6789' cannot be cast``);
|
|
12
|
+
* summaries are rebuilt without values.
|
|
13
|
+
|
|
14
|
+
Counts, column names, schema, verdicts and rule reasons stay: the agent needs them to
|
|
15
|
+
act. Counts can still be used as an oracle (preview ``DELETE ... WHERE ssn LIKE '1%'``
|
|
16
|
+
and read the row count), which no masking can stop, so ``agent_tables`` in
|
|
17
|
+
bricksentry.yml limits which tables an agent may assess or preview at all.
|
|
18
|
+
Humans (CLI, reports, pull-request comments) keep the full detail, except values in
|
|
19
|
+
pii-tagged tables and columns, which reports never show.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import fnmatch
|
|
25
|
+
import json
|
|
26
|
+
import logging
|
|
27
|
+
import time
|
|
28
|
+
from typing import TYPE_CHECKING, Any
|
|
29
|
+
|
|
30
|
+
from bricksentry.explain import explain_diff, redact_values
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from bricksentry.assess import Sentry
|
|
34
|
+
from bricksentry.models import Assessment
|
|
35
|
+
|
|
36
|
+
log = logging.getLogger("bricksentry.audit")
|
|
37
|
+
|
|
38
|
+
_DROP = {"samples", "base_sum", "candidate_sum"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def for_agent(a: Assessment, sentry: Sentry, extra: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
42
|
+
"""The agent-safe dict of an assessment."""
|
|
43
|
+
out = a.to_dict()
|
|
44
|
+
for t_obj, t in zip(a.tables, out.get("tables") or [], strict=False):
|
|
45
|
+
if t_obj.diff is not None:
|
|
46
|
+
measures = sentry.config.spec(t_obj.table).measures
|
|
47
|
+
human = explain_diff(t_obj.diff, measures)
|
|
48
|
+
rest = t_obj.summary[len(human):] if t_obj.summary.startswith(human) else ""
|
|
49
|
+
t["summary"] = explain_diff(t_obj.diff, measures, for_agent=True) + rest
|
|
50
|
+
if extra:
|
|
51
|
+
out.update(extra)
|
|
52
|
+
return scrub(out)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def scrub(x: Any, key: str | None = None) -> Any:
|
|
56
|
+
"""Remove values from any result dict (see the module docstring)."""
|
|
57
|
+
if isinstance(x, dict):
|
|
58
|
+
out: dict[str, Any] = {}
|
|
59
|
+
for k, v in x.items():
|
|
60
|
+
if k in _DROP:
|
|
61
|
+
continue
|
|
62
|
+
if k == "sum_change_pct" and isinstance(v, (int, float)):
|
|
63
|
+
out[k] = round(v, 1)
|
|
64
|
+
elif k == "segments" and isinstance(v, list):
|
|
65
|
+
out[k] = [{"column": s.get("column"), "affected_rows": s.get("affected_rows")}
|
|
66
|
+
for s in v if isinstance(s, dict)]
|
|
67
|
+
else:
|
|
68
|
+
out[k] = scrub(v, k)
|
|
69
|
+
return out
|
|
70
|
+
if isinstance(x, list):
|
|
71
|
+
return [scrub(v, key) for v in x]
|
|
72
|
+
if isinstance(x, str) and key in ("error", "notes", "reason", "summary", "rollback_warning"):
|
|
73
|
+
return redact_values(x)
|
|
74
|
+
return x
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def allowed(sentry: Sentry, table: str) -> bool:
|
|
78
|
+
"""Whether ``agent_tables`` (glob patterns, any case) lets an agent assess or preview ``table``.
|
|
79
|
+
Unset means every table, as before 0.1.27."""
|
|
80
|
+
patterns = sentry.config.agent_tables
|
|
81
|
+
if patterns is None:
|
|
82
|
+
return True
|
|
83
|
+
name = table.lower()
|
|
84
|
+
return any(fnmatch.fnmatchcase(name, p.lower()) for p in patterns)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def check_allowed(sentry: Sentry, tables: list[str]) -> None:
|
|
88
|
+
refused = [t for t in tables if not allowed(sentry, t)]
|
|
89
|
+
if refused:
|
|
90
|
+
raise PermissionError(
|
|
91
|
+
f"Not allowed for agents: {', '.join(refused)}. This bricksentry only lets agents assess "
|
|
92
|
+
"or preview the tables listed under agent_tables in bricksentry.yml."
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def audit(sentry: Sentry, tool: str, tables: list[str], result: dict[str, Any] | None = None,
|
|
97
|
+
refused: str | None = None) -> None:
|
|
98
|
+
"""One line per agent assess or preview: who, which tables, what came back.
|
|
99
|
+
Logged to ``bricksentry.audit`` and appended to ``audit.jsonl`` in the assessment store."""
|
|
100
|
+
from bricksentry.assess import _actor
|
|
101
|
+
|
|
102
|
+
rows = {}
|
|
103
|
+
for t in (result or {}).get("tables") or []:
|
|
104
|
+
d = t.get("diff") or {}
|
|
105
|
+
rows[t.get("table")] = {k: d.get(k) for k in ("added_rows", "removed_rows", "changed_rows")}
|
|
106
|
+
entry = {
|
|
107
|
+
"time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
108
|
+
"tool": tool,
|
|
109
|
+
"actor": _actor(),
|
|
110
|
+
"tables": tables,
|
|
111
|
+
"verdict": (result or {}).get("verdict"),
|
|
112
|
+
"assessment_id": (result or {}).get("id"),
|
|
113
|
+
"rows": rows or None,
|
|
114
|
+
"refused": refused,
|
|
115
|
+
}
|
|
116
|
+
log.info(json.dumps(entry))
|
|
117
|
+
folder = sentry.config.store_dir()
|
|
118
|
+
if folder is None:
|
|
119
|
+
return
|
|
120
|
+
try:
|
|
121
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
with (folder / "audit.jsonl").open("a") as f:
|
|
123
|
+
f.write(json.dumps(entry) + "\n")
|
|
124
|
+
except OSError:
|
|
125
|
+
pass
|
|
@@ -54,6 +54,7 @@ class Sentry:
|
|
|
54
54
|
segment_by=spec.segment_by,
|
|
55
55
|
max_samples=self.config.max_samples,
|
|
56
56
|
sample_guard=self.config.sample_guard,
|
|
57
|
+
float_tolerance=self.config.float_tolerance,
|
|
57
58
|
)
|
|
58
59
|
self._diffs[d.table] = d
|
|
59
60
|
return d
|
|
@@ -212,9 +213,20 @@ class Sentry:
|
|
|
212
213
|
schema = ".".join(clone.split(".")[:-1])
|
|
213
214
|
if schema:
|
|
214
215
|
self.backend.ensure_schema(schema)
|
|
215
|
-
self.backend.clone(target, clone)
|
|
216
216
|
try:
|
|
217
|
-
self.backend.
|
|
217
|
+
self.backend.clone(target, clone)
|
|
218
|
+
except Exception as e:
|
|
219
|
+
raise RuntimeError(
|
|
220
|
+
f"Could not clone {target} to preview the write: {_first_line(e)}. Check the table name "
|
|
221
|
+
f"and that you can create tables in {schema or 'the sandbox schema'}."
|
|
222
|
+
) from None
|
|
223
|
+
try:
|
|
224
|
+
try:
|
|
225
|
+
self.backend.execute(rewritten)
|
|
226
|
+
except Exception as e:
|
|
227
|
+
raise RuntimeError(
|
|
228
|
+
f"The statement failed on the preview clone, so production was not touched: {_first_line(e)}"
|
|
229
|
+
) from None
|
|
218
230
|
diff = self.diff(target, clone, keys=keys, table=target)
|
|
219
231
|
assessment = self.assess([target], diffs={target: diff})
|
|
220
232
|
finally:
|
|
@@ -295,3 +307,10 @@ def changed_columns(diff: TableDiff | None) -> list[str]:
|
|
|
295
307
|
out.append(c.column)
|
|
296
308
|
out += list(diff.schema.removed) + list(diff.schema.type_changed)
|
|
297
309
|
return list(dict.fromkeys(out))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _first_line(e: BaseException) -> str:
|
|
313
|
+
"""The useful part of an engine error: its first line, trimmed."""
|
|
314
|
+
text = str(e).strip()
|
|
315
|
+
line = text.splitlines()[0] if text else type(e).__name__
|
|
316
|
+
return line if len(line) <= 300 else line[:297] + "..."
|
|
@@ -39,6 +39,20 @@ class Backend(ABC):
|
|
|
39
39
|
def qualified(self, table: str) -> str:
|
|
40
40
|
return ".".join(self.quote(p) for p in table.split("."))
|
|
41
41
|
|
|
42
|
+
def columns_at(self, table: str, version: int | None) -> dict[str, str]:
|
|
43
|
+
"""Like :meth:`columns`, for ``table`` at ``version``."""
|
|
44
|
+
return self.columns(table)
|
|
45
|
+
|
|
46
|
+
def canon(self, expr: str, type_name: str) -> str:
|
|
47
|
+
"""An expression for ``expr`` that can be compared and hashed (e.g. a MAP as
|
|
48
|
+
key-sorted JSON on engines that can't compare maps). Identity by default."""
|
|
49
|
+
return expr
|
|
50
|
+
|
|
51
|
+
def at_version(self, table: str, version: int | None) -> str:
|
|
52
|
+
"""``table`` as it was at ``version`` (for a FROM clause). Engines without
|
|
53
|
+
time travel read the table as it is."""
|
|
54
|
+
return self.qualified(table)
|
|
55
|
+
|
|
42
56
|
@property
|
|
43
57
|
def string_type(self) -> str:
|
|
44
58
|
return "STRING"
|
|
@@ -47,14 +61,14 @@ class Backend(ABC):
|
|
|
47
61
|
def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
|
|
48
62
|
"""Deterministic hash sample on the key columns, identical on both sides."""
|
|
49
63
|
|
|
50
|
-
def row_checksum(self, columns: list[str]) -> str | None:
|
|
64
|
+
def row_checksum(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
|
|
51
65
|
"""SQL aggregate: an order-independent checksum over ``columns`` for every row.
|
|
52
66
|
|
|
53
67
|
Used to check a sampled diff against the whole table. ``None`` means the
|
|
54
68
|
backend has no cheap row hash, and the guard is skipped."""
|
|
55
69
|
return None
|
|
56
70
|
|
|
57
|
-
def row_hash(self, columns: list[str]) -> str | None:
|
|
71
|
+
def row_hash(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
|
|
58
72
|
"""SQL for a hash of one row's ``columns``; orders copies of a duplicated key
|
|
59
73
|
so identical copies pair up. ``None`` means unsupported (copies are paired in
|
|
60
74
|
no particular order)."""
|
|
@@ -123,9 +137,24 @@ def make_backend(spec: dict[str, Any] | None) -> Backend:
|
|
|
123
137
|
if kind == "duckdb":
|
|
124
138
|
from bricksentry.backends.duckdb_backend import DuckDBBackend
|
|
125
139
|
|
|
126
|
-
return DuckDBBackend(**spec)
|
|
140
|
+
return DuckDBBackend(**_known_keys(DuckDBBackend, kind, spec))
|
|
127
141
|
if kind == "databricks":
|
|
128
142
|
from bricksentry.backends.databricks_backend import DatabricksBackend
|
|
129
143
|
|
|
130
|
-
return DatabricksBackend(**spec)
|
|
144
|
+
return DatabricksBackend(**_known_keys(DatabricksBackend, kind, spec))
|
|
131
145
|
raise ValueError(f"Unknown backend type: {kind!r} (expected 'databricks' or 'duckdb')")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _known_keys(cls: type, kind: str, spec: dict[str, Any]) -> dict[str, Any]:
|
|
150
|
+
"""Reject misspelled `backend:` keys instead of silently ignoring them (a `path:`
|
|
151
|
+
meant as `database:` would quietly connect to an empty in-memory database)."""
|
|
152
|
+
import inspect
|
|
153
|
+
|
|
154
|
+
params = inspect.signature(cls.__init__).parameters
|
|
155
|
+
known = [n for n, p in params.items() if n != "self" and p.kind not in (p.VAR_KEYWORD, p.VAR_POSITIONAL)]
|
|
156
|
+
unknown = sorted(set(spec) - set(known))
|
|
157
|
+
if unknown:
|
|
158
|
+
raise ValueError(f"Unknown key(s) under backend: {', '.join(unknown)} for type {kind}. "
|
|
159
|
+
f"Valid keys: type, {', '.join(k for k in known if k != 'client' and k != 'connection')}.")
|
|
160
|
+
return spec
|