bricksentry 0.1.7__tar.gz → 0.1.8__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 (54) hide show
  1. {bricksentry-0.1.7 → bricksentry-0.1.8}/CHANGELOG.md +12 -0
  2. {bricksentry-0.1.7 → bricksentry-0.1.8}/PKG-INFO +22 -5
  3. {bricksentry-0.1.7 → bricksentry-0.1.8}/README.md +21 -4
  4. {bricksentry-0.1.7 → bricksentry-0.1.8}/pyproject.toml +1 -1
  5. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/__init__.py +1 -1
  6. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/agent_tools.py +1 -1
  7. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/assess.py +3 -2
  8. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/cli.py +50 -7
  9. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/config.py +69 -1
  10. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/explain.py +7 -2
  11. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/mcp_server.py +9 -1
  12. bricksentry-0.1.8/src/bricksentry/measures.py +63 -0
  13. bricksentry-0.1.8/src/bricksentry/notify.py +362 -0
  14. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/policy.py +9 -2
  15. bricksentry-0.1.8/tests/test_018.py +288 -0
  16. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_notify_templates.py +29 -2
  17. bricksentry-0.1.7/src/bricksentry/notify.py +0 -156
  18. {bricksentry-0.1.7 → bricksentry-0.1.8}/.gitignore +0 -0
  19. {bricksentry-0.1.7 → bricksentry-0.1.8}/CONTRIBUTING.md +0 -0
  20. {bricksentry-0.1.7 → bricksentry-0.1.8}/LICENSE +0 -0
  21. {bricksentry-0.1.7 → bricksentry-0.1.8}/SECURITY.md +0 -0
  22. {bricksentry-0.1.7 → bricksentry-0.1.8}/action.yml +0 -0
  23. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/databricks/bricksentry.yml +0 -0
  24. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  25. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/databricks/bricksentry_quickstart.py +0 -0
  26. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/databricks/github-workflow.yml +0 -0
  27. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/databricks/policy.yml +0 -0
  28. {bricksentry-0.1.7 → bricksentry-0.1.8}/examples/demo/agent_loop_demo.py +0 -0
  29. {bricksentry-0.1.7 → bricksentry-0.1.8}/packages/bricksentry-mcp/LICENSE +0 -0
  30. {bricksentry-0.1.7 → bricksentry-0.1.8}/packages/bricksentry-mcp/README.md +0 -0
  31. {bricksentry-0.1.7 → bricksentry-0.1.8}/packages/bricksentry-mcp/src/bricksentry_mcp/__init__.py +0 -0
  32. {bricksentry-0.1.7 → bricksentry-0.1.8}/scripts/build_notebook.py +0 -0
  33. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/backends/__init__.py +0 -0
  34. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/backends/base.py +0 -0
  35. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/backends/databricks_backend.py +0 -0
  36. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/backends/duckdb_backend.py +0 -0
  37. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/changes.py +0 -0
  38. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/demo.py +0 -0
  39. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/diff.py +0 -0
  40. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/github.py +0 -0
  41. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/lineage.py +0 -0
  42. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/models.py +0 -0
  43. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/policy_templates.py +0 -0
  44. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/preview.py +0 -0
  45. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/py.typed +0 -0
  46. {bricksentry-0.1.7 → bricksentry-0.1.8}/src/bricksentry/report.py +0 -0
  47. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/conftest.py +0 -0
  48. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_assess_policy.py +0 -0
  49. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_databricks_and_uc.py +0 -0
  50. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_demo.py +0 -0
  51. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_diff.py +0 -0
  52. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_notebook.py +0 -0
  53. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_preview_agents.py +0 -0
  54. {bricksentry-0.1.7 → bricksentry-0.1.8}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.8 (2026-11-11)
4
+
5
+ From the first real Slack alert sent from a Databricks workspace:
6
+
7
+ - Totals checks skip columns where a total means nothing. `numeric-total-moved` and diff summaries now ignore keys and columns that look like IDs, codes, years and other date parts, coordinates, ratings, scores or rates, so a real move in `sum(bed_count)` is no longer buried under `sum(established_year)`. Choose exactly with `measures: [...]` per table, or `measures: all` for the old behaviour. Rules that name a column still check it.
8
+ - Slack alerts can @-mention reviewers: map owners to Slack member or group ids under `notify.mentions`.
9
+ - Alerts link back to the run: the Databricks job run when the check runs in a job (new), the PR or Actions run in GitHub, or any URL in `BRICKSENTRY_RUN_URL` / `notify.run_url`.
10
+ - New `bricksentry test-alert` sends a clearly labelled sample alert to check the webhook setup (`--verdict`, `--owner`). Exits 1 if delivery fails.
11
+ - More robust delivery: one retry when Slack or Teams answers 429 or 5xx or the connection fails; clear messages for revoked webhooks (404/410); the webhook URL never appears in an error; Slack text is escaped so table names or values can't break or inject formatting; long reasons are clipped. Teams cards use plain text runs, so names like `my_table_name` show exactly. Bad `notify.on` or `mentions` values give a clear error.
12
+ - Config typos are reported. Unknown keys in bricksentry.yml (top level, `tables`, `notify`, `lineage`) print a warning with the closest valid key; also warns about tables without keys, short table names on Databricks, and webhook URLs written into the file.
13
+ - `bricksentry-mcp --help` shows `Usage: bricksentry-mcp [OPTIONS]`, and the MCP server reports the bricksentry version to clients (the version used to be empty).
14
+
3
15
  ## 0.1.7 (2026-11-11)
4
16
 
5
17
  - New companion package `bricksentry-mcp`: `uvx bricksentry-mcp --config /full/path/bricksentry.yml` starts the MCP server with everything it needs. Before, `uvx bricksentry mcp` installed the package without its MCP extra and failed, and that is what MCP Registry clients ran. The registry listing now points at `bricksentry-mcp`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.7
3
+ Version: 0.1.8
4
4
  Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
5
5
  Project-URL: Homepage, https://bricksentry.org
6
6
  Project-URL: Documentation, https://bricksentry.org/docs
@@ -194,7 +194,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
194
194
  Or use the bundled GitHub Action, which also writes the report to the job summary:
195
195
 
196
196
  ```yaml
197
- - uses: bricksentry/bricksentry@v0.1.7
197
+ - uses: bricksentry/bricksentry@v0.1.8
198
198
  with:
199
199
  config: bricksentry.yml
200
200
  fail-on: needs_human
@@ -219,7 +219,7 @@ jobs:
219
219
  fetch-depth: 0
220
220
  # Build this PR's version of your pipeline into a per-PR schema first,
221
221
  # for example: databricks bundle deploy -t ci && databricks bundle run -t ci
222
- - uses: bricksentry/bricksentry@v0.1.7
222
+ - uses: bricksentry/bricksentry@v0.1.8
223
223
  with:
224
224
  config: bricksentry.yml
225
225
  fail-on: needs_human
@@ -236,7 +236,7 @@ To make the check binding, mark this job as a required status check in your bran
236
236
 
237
237
  ### Alerts in Slack and Teams
238
238
 
239
- When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link to the PR.
239
+ When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link back to where the check ran.
240
240
 
241
241
  ```yaml
242
242
  # bricksentry.yml
@@ -244,9 +244,21 @@ notify:
244
244
  on: needs_human # alert at this verdict or worse
245
245
  slack_webhook: env:SLACK_WEBHOOK_URL # Slack incoming webhook
246
246
  teams_webhook: env:TEAMS_WEBHOOK_URL # Teams Workflows "webhook request" URL
247
+ mentions: # optional: @-mention reviewers in Slack
248
+ finance-analytics: S0123ABCD # a user group id (starts with S)
249
+ jane@acme.com: U0456EFGH # a member id (starts with U)
247
250
  ```
248
251
 
249
- Keep webhook URLs in secrets or environment variables, never in the file. `BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too. `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off), and in Python call `sentry.notify(assessment)`. A failed webhook is reported but never changes the verdict or fails the run.
252
+ Then check the setup with one command. It sends a clearly labelled sample alert and reads no tables:
253
+
254
+ ```bash
255
+ bricksentry test-alert
256
+ ```
257
+
258
+ - **Keep webhook URLs secret.** Put them in CI secrets or environment variables (`BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too), never in the file; bricksentry warns if it finds one there.
259
+ - **Links back to the run.** In GitHub Actions the alert links to the PR or run. In a Databricks job it links to the job run. Anywhere else, set `BRICKSENTRY_RUN_URL` (or `notify.run_url`).
260
+ - **Mentions.** Owners come from Unity Catalog. Map them to Slack ids under `mentions` and the alert @-mentions them; unmapped owners are shown as text. Find an id in Slack under a person's profile or a user group's menu, "Copy member ID" / "Copy group ID".
261
+ - **Never breaks a run.** `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off); in Python call `sentry.notify(assessment)`. If Slack or Teams is busy the alert is retried once, a failure is reported without the webhook URL, and the verdict always stands.
250
262
 
251
263
  ## Python API
252
264
 
@@ -274,10 +286,15 @@ tables:
274
286
  main.sales.orders:
275
287
  keys: [order_id]
276
288
  segment_by: [region]
289
+ measures: [amount, quantity] # totals worth checking (see below)
277
290
  paths: ["src/pipelines/orders/**", "resources/orders_job.yml"]
278
291
  policy: policy.yml # or builtin:<template>, see "Policy templates" below
279
292
  ```
280
293
 
294
+ 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.
295
+
296
+ **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.
297
+
281
298
  ### Policy example
282
299
 
283
300
  A small `policy.yml` with one rule per severity. `pass` is the default: a change gets it when no rule matches.
@@ -147,7 +147,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
147
147
  Or use the bundled GitHub Action, which also writes the report to the job summary:
148
148
 
149
149
  ```yaml
150
- - uses: bricksentry/bricksentry@v0.1.7
150
+ - uses: bricksentry/bricksentry@v0.1.8
151
151
  with:
152
152
  config: bricksentry.yml
153
153
  fail-on: needs_human
@@ -172,7 +172,7 @@ jobs:
172
172
  fetch-depth: 0
173
173
  # Build this PR's version of your pipeline into a per-PR schema first,
174
174
  # for example: databricks bundle deploy -t ci && databricks bundle run -t ci
175
- - uses: bricksentry/bricksentry@v0.1.7
175
+ - uses: bricksentry/bricksentry@v0.1.8
176
176
  with:
177
177
  config: bricksentry.yml
178
178
  fail-on: needs_human
@@ -189,7 +189,7 @@ To make the check binding, mark this job as a required status check in your bran
189
189
 
190
190
  ### Alerts in Slack and Teams
191
191
 
192
- When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link to the PR.
192
+ When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link back to where the check ran.
193
193
 
194
194
  ```yaml
195
195
  # bricksentry.yml
@@ -197,9 +197,21 @@ notify:
197
197
  on: needs_human # alert at this verdict or worse
198
198
  slack_webhook: env:SLACK_WEBHOOK_URL # Slack incoming webhook
199
199
  teams_webhook: env:TEAMS_WEBHOOK_URL # Teams Workflows "webhook request" URL
200
+ mentions: # optional: @-mention reviewers in Slack
201
+ finance-analytics: S0123ABCD # a user group id (starts with S)
202
+ jane@acme.com: U0456EFGH # a member id (starts with U)
200
203
  ```
201
204
 
202
- Keep webhook URLs in secrets or environment variables, never in the file. `BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too. `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off), and in Python call `sentry.notify(assessment)`. A failed webhook is reported but never changes the verdict or fails the run.
205
+ Then check the setup with one command. It sends a clearly labelled sample alert and reads no tables:
206
+
207
+ ```bash
208
+ bricksentry test-alert
209
+ ```
210
+
211
+ - **Keep webhook URLs secret.** Put them in CI secrets or environment variables (`BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too), never in the file; bricksentry warns if it finds one there.
212
+ - **Links back to the run.** In GitHub Actions the alert links to the PR or run. In a Databricks job it links to the job run. Anywhere else, set `BRICKSENTRY_RUN_URL` (or `notify.run_url`).
213
+ - **Mentions.** Owners come from Unity Catalog. Map them to Slack ids under `mentions` and the alert @-mentions them; unmapped owners are shown as text. Find an id in Slack under a person's profile or a user group's menu, "Copy member ID" / "Copy group ID".
214
+ - **Never breaks a run.** `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off); in Python call `sentry.notify(assessment)`. If Slack or Teams is busy the alert is retried once, a failure is reported without the webhook URL, and the verdict always stands.
203
215
 
204
216
  ## Python API
205
217
 
@@ -227,10 +239,15 @@ tables:
227
239
  main.sales.orders:
228
240
  keys: [order_id]
229
241
  segment_by: [region]
242
+ measures: [amount, quantity] # totals worth checking (see below)
230
243
  paths: ["src/pipelines/orders/**", "resources/orders_job.yml"]
231
244
  policy: policy.yml # or builtin:<template>, see "Policy templates" below
232
245
  ```
233
246
 
247
+ 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.
248
+
249
+ **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.
250
+
234
251
  ### Policy example
235
252
 
236
253
  A small `policy.yml` with one rule per severity. `pass` is the default: a change gets it when no rule matches.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.7"
7
+ version = "0.1.8"
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"
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.7"
26
+ __version__ = "0.1.8"
@@ -163,7 +163,7 @@ def explain_diff(
163
163
  d = s.get_diff(table)
164
164
  if d is None:
165
165
  return {"error": f"no diff for {table} yet; call assess_change or preview_write first"}
166
- return {"table": table, "explanation": _explain_diff(d)}
166
+ return {"table": table, "explanation": _explain_diff(d, s.config.spec(table).measures)}
167
167
  return {"error": "pass assessment_id or table"}
168
168
 
169
169
 
@@ -102,8 +102,9 @@ class Sentry:
102
102
  nodes = []
103
103
  err = err or f"lineage lookup failed: {e}"
104
104
  owner, tags = self.lineage.owner_and_tags(table)
105
- verdict, hits = self.policy.evaluate(table, diff, nodes, tags, diff_error=err)
106
- summary = (explain_diff(diff) if diff else f"{table}: diff unavailable ({err}).") + " " + explain_impact(table, nodes)
105
+ measures = self.config.spec(table).measures
106
+ verdict, hits = self.policy.evaluate(table, diff, nodes, tags, diff_error=err, measures=measures)
107
+ summary = (explain_diff(diff, measures) if diff else f"{table}: diff unavailable ({err}).") + " " + explain_impact(table, nodes)
107
108
  ta = TableAssessment(
108
109
  table=table,
109
110
  diff=diff,
@@ -18,10 +18,17 @@ from bricksentry.config import Config
18
18
  from bricksentry.models import Verdict
19
19
 
20
20
 
21
+ def _config(config_path) -> Config:
22
+ cfg = Config.load(config_path, warn=False)
23
+ for w in cfg.warnings:
24
+ click.echo(click.style("warning: ", fg="yellow") + w, err=True)
25
+ return cfg
26
+
27
+
21
28
  def _sentry(config_path):
22
29
  from bricksentry.assess import Sentry
23
30
 
24
- return Sentry(Config.load(config_path))
31
+ return Sentry(_config(config_path))
25
32
 
26
33
 
27
34
  def _emit(obj, fmt: str, markdown_fn=None):
@@ -65,7 +72,7 @@ def diff(base, candidate, keys, sample_pct, fmt, config_path):
65
72
 
66
73
  s = _sentry(config_path)
67
74
  d = s.diff(base, candidate, keys=list(keys) or None, table=base, sample_pct=sample_pct)
68
- _emit(d.to_dict() if fmt == "json" else explain_diff(d), fmt)
75
+ _emit(d.to_dict() if fmt == "json" else explain_diff(d, s.config.spec(base).measures), fmt)
69
76
 
70
77
 
71
78
  @main.command()
@@ -220,10 +227,13 @@ candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
220
227
  # sample_pct: 10 # diff a deterministic 10% key sample on big tables
221
228
 
222
229
  # Optional Slack / Teams alerts. Keep webhook URLs in environment variables or CI secrets.
230
+ # Test with: bricksentry test-alert
223
231
  # notify:
224
232
  # on: needs_human
225
233
  # slack_webhook: env:SLACK_WEBHOOK_URL
226
234
  # teams_webhook: env:TEAMS_WEBHOOK_URL
235
+ # mentions: # owner -> Slack id, so reviewers get @-mentioned
236
+ # finance-analytics: S0123ABCD
227
237
 
228
238
  lineage:
229
239
  depth: 3
@@ -233,6 +243,7 @@ tables:
233
243
  main.sales.orders:
234
244
  keys: [order_id]
235
245
  segment_by: [region]
246
+ measures: [amount, quantity] # totals worth checking; IDs, years and ratings are skipped by default
236
247
  paths: ["src/pipelines/orders/**", "resources/orders_job.yml"]
237
248
 
238
249
  policy: policy.yml
@@ -292,10 +303,38 @@ def policies(name):
292
303
  click.echo("\nUse one with `policy: builtin:<name>` in bricksentry.yml, or `bricksentry init --policy <name>`.")
293
304
 
294
305
 
295
- def entry() -> None:
296
- """Console entry point: turn unexpected errors into a clean message and exit code 2."""
306
+ @main.command("test-alert")
307
+ @click.option("--verdict", type=click.Choice([v.value for v in Verdict]), default="needs_human", show_default=True,
308
+ help="Verdict of the sample alert")
309
+ @click.option("--owner", default=None,
310
+ help="Reviewer to show. Use a name from notify.mentions to check that @-mentions work.")
311
+ @config_opt
312
+ def test_alert(verdict, owner, config_path):
313
+ """Send a clearly labelled sample alert to your Slack / Teams webhooks.
314
+
315
+ Reads no tables. Exits 1 if a webhook failed or none is configured."""
316
+ from bricksentry.notify import NotifySettings, sample_assessment, send
317
+
318
+ cfg = _config(config_path)
319
+ try:
320
+ settings = NotifySettings.from_config(cfg.notify)
321
+ except ValueError as e:
322
+ raise click.UsageError(str(e)) from e
323
+ if not settings.enabled:
324
+ raise click.ClickException(
325
+ "no webhook configured: set BRICKSENTRY_SLACK_WEBHOOK or BRICKSENTRY_TEAMS_WEBHOOK, "
326
+ "or add notify: to bricksentry.yml"
327
+ )
328
+ lines = send(sample_assessment(Verdict(verdict), owner), settings, force=True)
329
+ for line in lines:
330
+ click.echo(line)
331
+ if any(not line.endswith(": sent") for line in lines):
332
+ sys.exit(1)
333
+
334
+
335
+ def _run(cmd: click.Command, prog_name: str | None = None) -> None:
297
336
  try:
298
- main(standalone_mode=False)
337
+ cmd.main(prog_name=prog_name, standalone_mode=False)
299
338
  except click.exceptions.Exit as e:
300
339
  sys.exit(e.exit_code)
301
340
  except click.ClickException as e:
@@ -310,10 +349,14 @@ def entry() -> None:
310
349
  sys.exit(2)
311
350
 
312
351
 
352
+ def entry() -> None:
353
+ """Console entry point: turn unexpected errors into a clean message and exit code 2."""
354
+ _run(main)
355
+
356
+
313
357
  def mcp_entry() -> None:
314
358
  """Console entry for the ``bricksentry-mcp`` package: same as ``bricksentry mcp``."""
315
- sys.argv = [sys.argv[0], "mcp", *sys.argv[1:]]
316
- entry()
359
+ _run(mcp, prog_name="bricksentry-mcp")
317
360
 
318
361
 
319
362
  if __name__ == "__main__": # pragma: no cover
@@ -17,6 +17,7 @@ Example::
17
17
  main.sales.orders:
18
18
  keys: [order_id]
19
19
  segment_by: [region]
20
+ measures: [amount, quantity] # totals worth checking (default: numeric columns that aren't IDs, years, ratings...)
20
21
  paths: ["pipelines/orders/**", "resources/orders_job.yml"]
21
22
  policy: policy.yml # a file, an inline mapping, or builtin:<name> (see `bricksentry policies`)
22
23
  notify: # optional Slack / Teams alerts
@@ -27,7 +28,9 @@ Example::
27
28
 
28
29
  from __future__ import annotations
29
30
 
31
+ import difflib
30
32
  import os
33
+ import warnings
31
34
  from dataclasses import dataclass, field
32
35
  from pathlib import Path
33
36
  from typing import Any
@@ -36,6 +39,57 @@ import yaml
36
39
 
37
40
  DEFAULT_CONFIG_NAMES = ("bricksentry.yml", "bricksentry.yaml", ".bricksentry.yml")
38
41
 
42
+ TOP_LEVEL_KEYS = {
43
+ "backend", "sandbox_schema", "candidate_pattern", "sample_pct", "sample_guard",
44
+ "assessment_store", "max_samples", "lineage", "tables", "policy", "notify",
45
+ }
46
+ TABLE_KEYS = {"keys", "key", "segment_by", "paths", "candidate", "measures"}
47
+ NOTIFY_KEYS = {"on", "slack_webhook", "teams_webhook", "mentions", "run_url"}
48
+ LINEAGE_KEYS = {"depth", "lookback_days"}
49
+
50
+
51
+ def _unknown(where: str, given: Any, known: set[str]) -> list[str]:
52
+ """Warnings for keys bricksentry would silently ignore (usually a typo)."""
53
+ if not isinstance(given, dict):
54
+ return []
55
+ out = []
56
+ for k in given:
57
+ if k in known:
58
+ continue
59
+ near = difflib.get_close_matches(str(k), sorted(known), n=1, cutoff=0.6)
60
+ out.append(f"{where}: unknown key {k!r} is ignored" + (f" (did you mean {near[0]!r}?)" if near else ""))
61
+ return out
62
+
63
+
64
+ def config_warnings(data: dict[str, Any]) -> list[str]:
65
+ """Typos and misplaced keys in a bricksentry.yml mapping. Never raises."""
66
+ if not isinstance(data, dict):
67
+ return ["bricksentry.yml should be a mapping of settings"]
68
+ w = _unknown("bricksentry.yml", data, TOP_LEVEL_KEYS)
69
+ w += _unknown("notify", data.get("notify"), NOTIFY_KEYS)
70
+ w += _unknown("lineage", data.get("lineage"), LINEAGE_KEYS)
71
+ for name, spec in (data.get("tables") or {}).items() if isinstance(data.get("tables"), dict) else []:
72
+ w += _unknown(f"tables.{name}", spec, TABLE_KEYS)
73
+ if isinstance(spec, dict) and not (spec.get("keys") or spec.get("key")):
74
+ w.append(f"tables.{name}: no keys set, so rows can't be matched (diffs will need --key)")
75
+ if str(name).count(".") != 2 and str((data.get("backend") or {}).get("type", "")).lower() == "databricks":
76
+ w.append(f"tables.{name}: use the full catalog.schema.table name")
77
+ n = data.get("notify")
78
+ if isinstance(n, dict):
79
+ for k in ("slack_webhook", "teams_webhook"):
80
+ v = str(n.get(k) or "")
81
+ if v.startswith("https://"):
82
+ w.append(f"notify.{k}: the webhook URL is written in the file; it is a secret, use env:NAME instead")
83
+ return w
84
+
85
+
86
+ def _measures(v: Any) -> list[str] | str | None:
87
+ if v is None or v == []:
88
+ return None
89
+ if isinstance(v, str):
90
+ return "all" if v.strip().lower() == "all" else [v]
91
+ return [str(x) for x in v]
92
+
39
93
 
40
94
  @dataclass
41
95
  class TableSpec:
@@ -44,6 +98,7 @@ class TableSpec:
44
98
  segment_by: list[str] = field(default_factory=list)
45
99
  paths: list[str] = field(default_factory=list)
46
100
  candidate: str | None = None # explicit candidate table, overrides candidate_pattern
101
+ measures: list[str] | str | None = None # columns whose totals matter; "all" for every numeric column
47
102
 
48
103
 
49
104
  @dataclass
@@ -60,6 +115,7 @@ class Config:
60
115
  policy: dict[str, Any] | None = None
61
116
  notify: dict[str, Any] = field(default_factory=dict)
62
117
  root: Path = field(default_factory=Path.cwd)
118
+ warnings: list[str] = field(default_factory=list)
63
119
 
64
120
  @classmethod
65
121
  def from_dict(cls, data: dict[str, Any], root: Path | None = None) -> Config:
@@ -79,6 +135,7 @@ class Config:
79
135
  segment_by=list(seg),
80
136
  paths=list(spec.get("paths") or []),
81
137
  candidate=spec.get("candidate"),
138
+ measures=_measures(spec.get("measures")),
82
139
  )
83
140
  policy = data.get("policy")
84
141
  if isinstance(policy, str):
@@ -101,10 +158,21 @@ class Config:
101
158
  policy=policy,
102
159
  notify=data.get("notify") or {},
103
160
  root=root,
161
+ warnings=config_warnings(data),
104
162
  )
105
163
 
106
164
  @classmethod
107
- def load(cls, path: str | os.PathLike | None = None) -> Config:
165
+ def load(cls, path: str | os.PathLike | None = None, warn: bool = True) -> Config:
166
+ """Load bricksentry.yml. Typos and ignored keys are reported as Python warnings
167
+ (``warn=False`` to skip that and read ``config.warnings`` yourself)."""
168
+ cfg = cls._load(path)
169
+ if warn:
170
+ for w in cfg.warnings:
171
+ warnings.warn(f"bricksentry config: {w}", UserWarning, stacklevel=2)
172
+ return cfg
173
+
174
+ @classmethod
175
+ def _load(cls, path: str | os.PathLike | None = None) -> Config:
108
176
  if path is None:
109
177
  path = os.environ.get("BRICKSENTRY_CONFIG")
110
178
  if path is None:
@@ -6,6 +6,7 @@ but the verdict never depends on it.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ from bricksentry.measures import is_measure
9
10
  from bricksentry.models import ImpactNode, TableDiff
10
11
 
11
12
 
@@ -13,7 +14,7 @@ def _n(x: int) -> str:
13
14
  return f"{x:,}"
14
15
 
15
16
 
16
- def explain_diff(d: TableDiff) -> str:
17
+ def explain_diff(d: TableDiff, measures: list[str] | str | None = None) -> str:
17
18
  if d.error:
18
19
  return f"{d.table}: the diff could not run ({d.error})."
19
20
  if d.is_identical:
@@ -46,7 +47,11 @@ def explain_diff(d: TableDiff) -> str:
46
47
  if top:
47
48
  s += ". Most changed: " + ", ".join(f"{c.column} ({_n(c.changed_rows)})" for c in top)
48
49
 
49
- moved = [c for c in d.columns if c.sum_change_pct is not None and abs(c.sum_change_pct) >= 0.01]
50
+ moved = [
51
+ c for c in d.columns
52
+ if c.sum_change_pct is not None and abs(c.sum_change_pct) >= 0.01
53
+ and is_measure(c.column, d.keys, measures)
54
+ ]
50
55
  moved.sort(key=lambda c: -abs(c.sum_change_pct or 0))
51
56
  if moved:
52
57
  s += ". Totals: " + ", ".join(f"sum({c.column}) {c.sum_change_pct:+.2f}%" for c in moved[:3])
@@ -33,7 +33,15 @@ def build_server():
33
33
  except ImportError: # pragma: no cover
34
34
  ToolAnnotations = None
35
35
 
36
- server = Server(name="bricksentry", instructions=INSTRUCTIONS)
36
+ from bricksentry import __version__
37
+
38
+ try: # mcp >= 2 takes the version directly
39
+ server = Server(name="bricksentry", instructions=INSTRUCTIONS, version=__version__)
40
+ except TypeError: # mcp 1.x: set it on the underlying low-level server
41
+ server = Server(name="bricksentry", instructions=INSTRUCTIONS)
42
+ low = getattr(server, "_mcp_server", None)
43
+ if low is not None and hasattr(low, "version"):
44
+ low.version = __version__
37
45
  for fn in agent_tools.TOOLS:
38
46
  ann = None
39
47
  if ToolAnnotations is not None:
@@ -0,0 +1,63 @@
1
+ """Which numeric columns are *measures*, i.e. columns where a change in the total means something.
2
+
3
+ Summing an ID, a year or a rating gives a number, but a 10% move in
4
+ ``sum(established_year)`` only says that rows were removed. Those totals add
5
+ noise to verdicts and alerts and hide the one that matters (``sum(revenue)``).
6
+
7
+ Rules, in order:
8
+
9
+ 1. ``tables.<name>.measures`` in ``bricksentry.yml`` is a list of columns: only
10
+ those count. ``measures: all`` counts every numeric column (the 0.1.7 behaviour).
11
+ 2. Otherwise every numeric column counts, except key columns and columns whose
12
+ name looks like an identifier, code, date part, coordinate, rating, score,
13
+ rate or version (``customer_id``, ``zip``, ``order_year``, ``rating``, ``lat``...).
14
+
15
+ A policy rule that names a column (``when: {column: rating, sum_change_pct_gt: 1}``)
16
+ always checks that column, whatever this module says.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from collections.abc import Iterable
23
+
24
+ _NOT_A_MEASURE = {
25
+ # identifiers and codes
26
+ "id", "ids", "key", "sk", "pk", "fk", "uuid", "guid", "code", "zip", "zipcode",
27
+ "postal", "postcode", "phone", "fax", "ssn", "ein", "npi", "isbn", "sku", "hash",
28
+ "seq", "sequence", "index", "idx", "version", "ver", "revision", "build",
29
+ # date parts and times
30
+ "year", "yr", "yyyy", "month", "mm", "day", "dd", "dow", "week", "wk", "quarter",
31
+ "qtr", "hour", "hr", "minute", "second", "date", "dt", "ts", "time", "timestamp",
32
+ "epoch", "fiscal",
33
+ # places
34
+ "lat", "latitude", "lon", "lng", "long", "longitude", "geo", "fips",
35
+ # ratios and grades: their sum has no meaning
36
+ "rating", "rank", "ranking", "score", "grade", "tier", "level", "pct", "percent",
37
+ "percentage", "ratio", "rate", "share", "prob", "probability", "flag", "bool",
38
+ }
39
+
40
+ _CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
41
+
42
+
43
+ def _words(column: str) -> list[str]:
44
+ return [w for w in re.split(r"[^a-z0-9]+", _CAMEL.sub("_", column).lower()) if w]
45
+
46
+
47
+ def looks_like_measure(column: str) -> bool:
48
+ """Name heuristic only: False for ``customer_id``, ``orderYear``, ``rating``; True for ``amount``."""
49
+ words = _words(column)
50
+ return bool(words) and not any(w in _NOT_A_MEASURE for w in words)
51
+
52
+
53
+ def is_measure(column: str, keys: Iterable[str] = (), measures: list[str] | str | None = None) -> bool:
54
+ """Should a change in ``sum(column)`` be reported and checked by default?"""
55
+ if isinstance(measures, str):
56
+ if measures.strip().lower() == "all":
57
+ return True
58
+ measures = [measures]
59
+ if measures:
60
+ return column.lower() in {m.lower() for m in measures}
61
+ if column.lower() in {k.lower() for k in keys}:
62
+ return False
63
+ return looks_like_measure(column)