bricksentry 0.1.26__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.
Files changed (93) hide show
  1. {bricksentry-0.1.26 → bricksentry-0.1.27}/CHANGELOG.md +12 -0
  2. {bricksentry-0.1.26 → bricksentry-0.1.27}/PKG-INFO +29 -3
  3. {bricksentry-0.1.26 → bricksentry-0.1.27}/README.md +28 -2
  4. bricksentry-0.1.27/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_validation.ipynb +1 -1
  6. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_validation.py +1 -1
  7. {bricksentry-0.1.26 → bricksentry-0.1.27}/pyproject.toml +1 -1
  8. {bricksentry-0.1.26 → bricksentry-0.1.27}/server.json +2 -2
  9. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/__init__.py +1 -1
  10. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/agent_tools.py +29 -7
  11. bricksentry-0.1.27/src/bricksentry/agent_view.py +125 -0
  12. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/assess.py +1 -0
  13. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/backends/base.py +16 -2
  14. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/backends/databricks_backend.py +34 -6
  15. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/backends/duckdb_backend.py +14 -5
  16. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/config.py +27 -1
  17. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/diff.py +155 -21
  18. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/explain.py +22 -4
  19. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/models.py +4 -0
  20. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/policy.py +18 -2
  21. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/report.py +20 -2
  22. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/validation.py +42 -1
  23. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/databricks_template_schema.json +2 -2
  24. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0123.py +1 -1
  25. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0126.py +1 -1
  26. bricksentry-0.1.27/tests/test_0127.py +267 -0
  27. bricksentry-0.1.26/deploy/databricks-app/requirements.txt +0 -1
  28. {bricksentry-0.1.26 → bricksentry-0.1.27}/.gitignore +0 -0
  29. {bricksentry-0.1.26 → bricksentry-0.1.27}/CONTRIBUTING.md +0 -0
  30. {bricksentry-0.1.26 → bricksentry-0.1.27}/LICENSE +0 -0
  31. {bricksentry-0.1.26 → bricksentry-0.1.27}/SECURITY.md +0 -0
  32. {bricksentry-0.1.26 → bricksentry-0.1.27}/action.yml +0 -0
  33. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/container/Dockerfile +0 -0
  34. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/databricks-app/README.md +0 -0
  35. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/databricks-app/app.yaml +0 -0
  36. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/databricks-app/bricksentry.yml +0 -0
  37. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/databricks-app/databricks.yml +0 -0
  38. {bricksentry-0.1.26 → bricksentry-0.1.27}/deploy/databricks-app/grants.sql +0 -0
  39. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry.yml +0 -0
  40. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  41. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_check_my_table.py +0 -0
  42. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  43. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  44. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  45. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/bricksentry_quickstart.py +0 -0
  46. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/github-workflow.yml +0 -0
  47. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/databricks/policy.yml +0 -0
  48. {bricksentry-0.1.26 → bricksentry-0.1.27}/examples/demo/agent_loop_demo.py +0 -0
  49. {bricksentry-0.1.26 → bricksentry-0.1.27}/scripts/build_notebook.py +0 -0
  50. {bricksentry-0.1.26 → bricksentry-0.1.27}/scripts/render_demo_image.py +0 -0
  51. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/__main__.py +0 -0
  52. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/backends/__init__.py +0 -0
  53. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/changes.py +0 -0
  54. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/cli.py +0 -0
  55. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/demo.py +0 -0
  56. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/github.py +0 -0
  57. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/history.py +0 -0
  58. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/job.py +0 -0
  59. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/job_demo.py +0 -0
  60. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/lineage.py +0 -0
  61. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/mcp_server.py +0 -0
  62. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/measures.py +0 -0
  63. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/netguard.py +0 -0
  64. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/notify.py +0 -0
  65. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/policy_templates.py +0 -0
  66. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/preview.py +0 -0
  67. {bricksentry-0.1.26 → bricksentry-0.1.27}/src/bricksentry/py.typed +0 -0
  68. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/README.md +0 -0
  69. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  70. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  71. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  72. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  73. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  74. {bricksentry-0.1.26 → bricksentry-0.1.27}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  75. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/conftest.py +0 -0
  76. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0110.py +0 -0
  77. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0112.py +0 -0
  78. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0114.py +0 -0
  79. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0120.py +0 -0
  80. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0121.py +0 -0
  81. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_0122.py +0 -0
  82. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_018.py +0 -0
  83. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_019.py +0 -0
  84. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_assess_policy.py +0 -0
  85. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_check_notebook.py +0 -0
  86. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_databricks_and_uc.py +0 -0
  87. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_demo.py +0 -0
  88. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_diff.py +0 -0
  89. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_hr_notebook.py +0 -0
  90. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_notebook.py +0 -0
  91. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_notify_templates.py +0 -0
  92. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_preview_agents.py +0 -0
  93. {bricksentry-0.1.26 → bricksentry-0.1.27}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,17 @@
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
+
3
15
  ## 0.1.26 (2026-11-17)
4
16
 
5
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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.26
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
@@ -452,7 +478,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
452
478
 
453
479
  ## What a check costs
454
480
 
455
- 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`.
456
482
 
457
483
  ## Audit trail
458
484
 
@@ -463,7 +489,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
463
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.
464
490
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
465
491
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
466
- - **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.26 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. 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.
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.
467
493
 
468
494
  ## Roadmap
469
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
@@ -405,7 +431,7 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
405
431
 
406
432
  ## What a check costs
407
433
 
408
- 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`.
409
435
 
410
436
  ## Audit trail
411
437
 
@@ -416,7 +442,7 @@ Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 f
416
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.
417
443
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
418
444
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
419
- - **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.26 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. 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.
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.
420
446
 
421
447
  ## Roadmap
422
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
- "**12 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same\n",
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 **12 risky changes, about 2 minutes, nothing outside a scratch schema touched.** This notebook runs the same
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.26"
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.26",
11
+ "version": "0.1.27",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.26",
16
+ "version": "0.1.27",
17
17
  "runtimeHint": "uvx",
18
18
  "transport": {
19
19
  "type": "stdio"
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.26"
26
+ __version__ = "0.1.27"
@@ -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
 
@@ -51,7 +52,7 @@ def _safe(fn):
51
52
  line = text.splitlines()[0] if text else ""
52
53
  if len(line) > 300:
53
54
  line = line[:297] + "..."
54
- return {"error": f"{type(e).__name__}: {line}"}
55
+ return {"error": agent_view.redact_values(f"{type(e).__name__}: {line}")}
55
56
 
56
57
  return wrapper
57
58
 
@@ -127,8 +128,13 @@ def assess_change(
127
128
  notify, rule_hits, tables: [{table, verdict, summary, diff, downstream,
128
129
  changed_columns, column_tags, column_downstream,
129
130
  rollback}]}. Pass `id` to safe_to_ship (and optionally explain_diff)."""
130
- a = get_sentry().assess(list(tables), candidates=candidates, pr=pr)
131
- return a.to_dict()
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
132
138
 
133
139
 
134
140
  @_safe
@@ -155,7 +161,13 @@ def preview_write(
155
161
 
156
162
  Returns the same shape as assess_change (with an `id` for safe_to_ship), or
157
163
  {error} if the statement is refused or fails."""
158
- return get_sentry().preview_write(sql, target, keys=keys)
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
159
171
 
160
172
 
161
173
  @_safe
@@ -181,12 +193,14 @@ def explain_diff(
181
193
  a = s.get_assessment(assessment_id)
182
194
  if a is None:
183
195
  return {"error": f"unknown assessment id {assessment_id}"}
184
- return {"assessment_id": a.id, "explanations": {t.table: t.summary for t in a.tables}}
196
+ safe = agent_view.for_agent(a, s)
197
+ return {"assessment_id": a.id, "explanations": {t["table"]: t["summary"] for t in safe["tables"]}}
185
198
  if table:
186
199
  d = s.get_diff(table)
187
200
  if d is None:
188
201
  return {"error": f"no diff for {table} yet; call assess_change or preview_write first"}
189
- return {"table": table, "explanation": _explain_diff(d, s.config.spec(table).measures)}
202
+ return {"table": table,
203
+ "explanation": _explain_diff(d, s.config.spec(table).measures, for_agent=True)}
190
204
  return {"error": "pass assessment_id or table"}
191
205
 
192
206
 
@@ -221,7 +235,7 @@ def safe_to_ship(
221
235
  "safe_to_ship": v in ("pass", "warn"),
222
236
  "verdict": v,
223
237
  "risk_tier": a.verdict.risk_tier,
224
- "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"),
225
239
  "notify": a.notify,
226
240
  "next_step": next_step,
227
241
  }
@@ -250,6 +264,14 @@ def rollback_plan(
250
264
  }
251
265
 
252
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
+
253
275
  def _not_found(table: str) -> str:
254
276
  return (f"Table {table} not found. Check the catalog, schema and table name (they must match "
255
277
  "Unity Catalog exactly) and that you have SELECT on it.")
@@ -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
@@ -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)."""
@@ -105,12 +105,24 @@ class DatabricksBackend(Backend):
105
105
  def quote(self, ident: str) -> str:
106
106
  return "`" + ident.replace("`", "``") + "`"
107
107
 
108
- def row_checksum(self, columns: list[str]) -> str | None:
109
- cols = ", ".join(self.quote(c) for c in columns)
110
- return f"SUM(CAST(xxhash64({cols}) AS DECIMAL(38, 0)))"
111
-
112
- def row_hash(self, columns: list[str]) -> str | None:
113
- return f"xxhash64({', '.join(self.quote(c) for c in columns)})"
108
+ def row_checksum(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
109
+ return f"SUM(CAST({self.row_hash(columns, types)} AS DECIMAL(38, 0)))"
110
+
111
+ def row_hash(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
112
+ types = types or {}
113
+ return f"xxhash64({', '.join(self.canon(self.quote(c), types.get(c, '')) for c in columns)})"
114
+
115
+ def canon(self, expr: str, type_name: str) -> str:
116
+ # Spark can't compare or hash MAP values. Compare a map as its entries sorted by
117
+ # key, as JSON (to_json alone keeps insertion order, so equal maps could differ).
118
+ # Maps nested in structs or arrays are compared as JSON: equal maps written in a
119
+ # different order may show as changed (over-reports, never hides a change).
120
+ t = (type_name or "").lower()
121
+ if t.startswith("map<"):
122
+ return f"to_json(array_sort(map_entries({expr})))"
123
+ if "map<" in t:
124
+ return f"to_json({expr})"
125
+ return expr
114
126
 
115
127
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
116
128
  pre = f"{alias}." if alias else ""
@@ -135,6 +147,22 @@ class DatabricksBackend(Backend):
135
147
  f"CREATE OR REPLACE TABLE {self.qualified(target)} SHALLOW CLONE {self.qualified(source)}"
136
148
  )
137
149
 
150
+ def columns_at(self, table: str, version: int | None) -> dict[str, str]:
151
+ if version is None:
152
+ return self.columns(table)
153
+ try:
154
+ rows = self.query(f"DESCRIBE QUERY SELECT * FROM {self.at_version(table, version)}")
155
+ except Exception:
156
+ return self.columns(table)
157
+ out = {(r.get("col_name") or "").strip(): str(r.get("data_type", "")).lower() for r in rows}
158
+ out.pop("", None)
159
+ return out or self.columns(table)
160
+
161
+ def at_version(self, table: str, version: int | None) -> str:
162
+ if version is None:
163
+ return self.qualified(table)
164
+ return f"{self.qualified(table)} VERSION AS OF {int(version)}"
165
+
138
166
  def current_version(self, table: str) -> int | None:
139
167
  try:
140
168
  rows = self.query(f"DESCRIBE HISTORY {self.qualified(table)} LIMIT 1")
@@ -34,12 +34,21 @@ class DuckDBBackend(Backend):
34
34
  def string_type(self) -> str:
35
35
  return "VARCHAR"
36
36
 
37
- def row_checksum(self, columns: list[str]) -> str | None:
38
- cols = ", ".join(self.quote(c) for c in columns)
39
- return f"SUM(CAST(hash({cols}) AS HUGEINT))"
37
+ def row_checksum(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
38
+ return f"SUM(CAST({self.row_hash(columns, types)} AS HUGEINT))"
40
39
 
41
- def row_hash(self, columns: list[str]) -> str | None:
42
- return f"hash({', '.join(self.quote(c) for c in columns)})"
40
+ def row_hash(self, columns: list[str], types: dict[str, str] | None = None) -> str | None:
41
+ types = types or {}
42
+ return f"hash({', '.join(self.canon(self.quote(c), types.get(c, '')) for c in columns)})"
43
+
44
+ def canon(self, expr: str, type_name: str) -> str:
45
+ # Maps compare in insertion order; compare their entries sorted by key instead.
46
+ t = (type_name or "").lower()
47
+ if t.startswith("map("):
48
+ return f"list_sort(map_entries({expr}))"
49
+ if "map(" in t:
50
+ return f"CAST({expr} AS VARCHAR)"
51
+ return expr
43
52
 
44
53
  def sample_predicate(self, keys: list[str], pct: float, alias: str | None = None) -> str:
45
54
  pre = f"{alias}." if alias else ""
@@ -41,7 +41,7 @@ DEFAULT_CONFIG_NAMES = ("bricksentry.yml", "bricksentry.yaml", ".bricksentry.yml
41
41
 
42
42
  TOP_LEVEL_KEYS = {
43
43
  "backend", "sandbox_schema", "candidate_pattern", "sample_pct", "sample_guard",
44
- "assessment_store", "max_samples", "lineage", "tables", "policy", "notify",
44
+ "assessment_store", "max_samples", "lineage", "tables", "policy", "notify", "agent_tables", "float_tolerance",
45
45
  }
46
46
  TABLE_KEYS = {"keys", "key", "segment_by", "paths", "candidate", "measures"}
47
47
  NOTIFY_KEYS = {"on", "slack_webhook", "teams_webhook", "mentions", "run_url"}
@@ -52,6 +52,28 @@ LINEAGE_KEYS = {
52
52
  }
53
53
 
54
54
 
55
+ def _agent_tables(v: Any) -> list[str] | None:
56
+ if v is None:
57
+ return None
58
+ if isinstance(v, str):
59
+ v = [v]
60
+ if not isinstance(v, list) or not all(isinstance(x, str) for x in v):
61
+ raise ValueError("agent_tables must be a list of table names or patterns, e.g. ['main.sales_dev.*']")
62
+ return list(v)
63
+
64
+
65
+ def _tolerance(v: Any) -> float | None:
66
+ if v in (None, False, 0):
67
+ return None
68
+ try:
69
+ t = float(v)
70
+ except (TypeError, ValueError):
71
+ raise ValueError(f"float_tolerance must be a number like 1e-9, not {v!r}") from None
72
+ if not 0 < t < 1:
73
+ raise ValueError(f"float_tolerance must be between 0 and 1 (a relative tolerance like 1e-9), not {v!r}")
74
+ return t
75
+
76
+
55
77
  def _unknown(where: str, given: Any, known: set[str]) -> list[str]:
56
78
  """Warnings for keys bricksentry would silently ignore (usually a typo)."""
57
79
  if not isinstance(given, dict):
@@ -137,6 +159,8 @@ class Config:
137
159
  tables: dict[str, TableSpec] = field(default_factory=dict)
138
160
  policy: dict[str, Any] | None = None
139
161
  notify: dict[str, Any] = field(default_factory=dict)
162
+ agent_tables: list[str] | None = None # tables an agent may assess or preview (globs); None = all
163
+ float_tolerance: float | None = None # opt-in relative tolerance for FLOAT/DOUBLE compares
140
164
  root: Path = field(default_factory=Path.cwd)
141
165
  warnings: list[str] = field(default_factory=list)
142
166
 
@@ -180,6 +204,8 @@ class Config:
180
204
  tables=tables,
181
205
  policy=policy,
182
206
  notify=_notify(data.get("notify")),
207
+ agent_tables=_agent_tables(data.get("agent_tables")),
208
+ float_tolerance=_tolerance(data.get("float_tolerance")),
183
209
  root=root,
184
210
  warnings=config_warnings(data),
185
211
  )