bricksentry 0.1.28__tar.gz → 0.1.29__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 (95) hide show
  1. {bricksentry-0.1.28 → bricksentry-0.1.29}/CHANGELOG.md +9 -0
  2. {bricksentry-0.1.28 → bricksentry-0.1.29}/PKG-INFO +21 -6
  3. {bricksentry-0.1.28 → bricksentry-0.1.29}/README.md +19 -4
  4. bricksentry-0.1.29/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.28 → bricksentry-0.1.29}/pyproject.toml +2 -2
  6. {bricksentry-0.1.28 → bricksentry-0.1.29}/server.json +2 -2
  7. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/__init__.py +1 -1
  8. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/agent_tools.py +20 -1
  9. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/agent_view.py +112 -4
  10. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/backends/base.py +18 -2
  11. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/backends/databricks_backend.py +82 -1
  12. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/backends/duckdb_backend.py +26 -0
  13. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/diff.py +26 -18
  14. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/databricks_template_schema.json +2 -2
  15. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0127.py +3 -3
  16. bricksentry-0.1.29/tests/test_0129.py +235 -0
  17. bricksentry-0.1.28/deploy/databricks-app/requirements.txt +0 -1
  18. {bricksentry-0.1.28 → bricksentry-0.1.29}/.gitignore +0 -0
  19. {bricksentry-0.1.28 → bricksentry-0.1.29}/CONTRIBUTING.md +0 -0
  20. {bricksentry-0.1.28 → bricksentry-0.1.29}/LICENSE +0 -0
  21. {bricksentry-0.1.28 → bricksentry-0.1.29}/SECURITY.md +0 -0
  22. {bricksentry-0.1.28 → bricksentry-0.1.29}/action.yml +0 -0
  23. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/container/Dockerfile +0 -0
  24. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/databricks-app/README.md +0 -0
  25. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/databricks-app/app.yaml +0 -0
  26. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/databricks-app/bricksentry.yml +0 -0
  27. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/databricks-app/databricks.yml +0 -0
  28. {bricksentry-0.1.28 → bricksentry-0.1.29}/deploy/databricks-app/grants.sql +0 -0
  29. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry.yml +0 -0
  30. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  31. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_check_my_table.py +0 -0
  32. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  33. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  34. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  35. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_quickstart.py +0 -0
  36. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_validation.ipynb +0 -0
  37. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/bricksentry_validation.py +0 -0
  38. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/github-workflow.yml +0 -0
  39. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/databricks/policy.yml +0 -0
  40. {bricksentry-0.1.28 → bricksentry-0.1.29}/examples/demo/agent_loop_demo.py +0 -0
  41. {bricksentry-0.1.28 → bricksentry-0.1.29}/scripts/build_notebook.py +0 -0
  42. {bricksentry-0.1.28 → bricksentry-0.1.29}/scripts/render_demo_image.py +0 -0
  43. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/__main__.py +0 -0
  44. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/assess.py +0 -0
  45. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/backends/__init__.py +0 -0
  46. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/changes.py +0 -0
  47. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/cli.py +0 -0
  48. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/config.py +0 -0
  49. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/demo.py +0 -0
  50. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/explain.py +0 -0
  51. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/github.py +0 -0
  52. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/history.py +0 -0
  53. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/job.py +0 -0
  54. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/job_demo.py +0 -0
  55. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/lineage.py +0 -0
  56. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/mcp_server.py +0 -0
  57. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/measures.py +0 -0
  58. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/models.py +0 -0
  59. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/netguard.py +0 -0
  60. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/notify.py +0 -0
  61. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/policy.py +0 -0
  62. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/policy_templates.py +0 -0
  63. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/preview.py +0 -0
  64. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/py.typed +0 -0
  65. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/report.py +0 -0
  66. {bricksentry-0.1.28 → bricksentry-0.1.29}/src/bricksentry/validation.py +0 -0
  67. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/README.md +0 -0
  68. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  69. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  70. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  71. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  72. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  73. {bricksentry-0.1.28 → bricksentry-0.1.29}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  74. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/conftest.py +0 -0
  75. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0110.py +0 -0
  76. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0112.py +0 -0
  77. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0114.py +0 -0
  78. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0120.py +0 -0
  79. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0121.py +0 -0
  80. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0122.py +0 -0
  81. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0123.py +0 -0
  82. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0126.py +0 -0
  83. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_0128.py +0 -0
  84. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_018.py +0 -0
  85. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_019.py +0 -0
  86. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_assess_policy.py +0 -0
  87. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_check_notebook.py +0 -0
  88. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_databricks_and_uc.py +0 -0
  89. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_demo.py +0 -0
  90. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_diff.py +0 -0
  91. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_hr_notebook.py +0 -0
  92. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_notebook.py +0 -0
  93. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_notify_templates.py +0 -0
  94. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_preview_agents.py +0 -0
  95. {bricksentry-0.1.28 → bricksentry-0.1.29}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.29 (2026-11-17)
4
+
5
+ Closes the last known way around `agent_tables`, and bricksentry enters public beta. Verified on Databricks before release: every view and function attack refused (a view over a forbidden table, a view over that view, a function with and without a schema, a view as candidate), legitimate views, functions, MERGE, UPDATE and INSERT previews ran with exact counts, and the 15-scenario battery passed 15 of 15.
6
+
7
+ - **Views and SQL functions are held to `agent_tables`.** A listed view over an unlisted table, or a SQL function whose body reads one (`SET x = get_secret()`), let an agent's preview read that table and learn its row counts (values stayed hidden). bricksentry now reads every view's definition and every user function's body from Unity Catalog (`system.information_schema.views` and `.routines`) and checks the tables inside, recursively; an unqualified function name is matched in every schema. A definition that can't be read, or a catalog that can't be read, means the preview is refused. Found in the pre-release check of the plan check below, which can't see inside views or functions on serverless.
8
+ - **A second opinion from the engine's query plan.** On Databricks, before an agent's preview runs, bricksentry also runs `EXPLAIN EXTENDED` (planning only); if the plan names a table that isn't in `agent_tables`, the preview is refused. Plan formats vary on serverless (compact plans; tables inside views and functions aren't shown), so a plan that can't be read doesn't block a preview: the parser and the view and function definitions are the boundary. Found in the pre-release check: a hard plan gate refused legitimate agent MERGEs.
9
+ - **Faster pinned diffs.** Reading the schema at the pinned version now doubles as the time-travel probe, and only the candidate's version is re-checked afterwards (a pinned base can't affect the result), so each diff runs three fewer metadata queries. A base that moves during the check is no longer noted, because its pinned reads are unaffected.
10
+ - bricksentry is now in **public beta**: the package is marked Beta, and the README says what you can rely on during the beta and what may still change before 1.0.
11
+
3
12
  ## 0.1.28 (2026-11-17)
4
13
 
5
14
  Security fixes from live-test round 9 on 0.1.27 (MERGE, allowlist bypasses, metadata injection, remote access, governance features). Agents still never received production values; these close the remaining ways to learn about tables they shouldn't. Every round-9 attack was re-run on the fixes and refused or handled; the 15-scenario battery passed 15 of 15 on Databricks, and a live Unity Catalog row filter gave `needs_human` instead of a silent pass.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.28
3
+ Version: 0.1.29
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
@@ -11,7 +11,7 @@ Author: Brahma
11
11
  License-Expression: Apache-2.0
12
12
  License-File: LICENSE
13
13
  Keywords: ai-agents,change-impact-analysis,ci,data-diff,data-engineering,data-quality,databricks,delta-lake,deployment-guardrails,impact-analysis,lineage,mcp,rollback,unity-catalog
14
- Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Development Status :: 4 - Beta
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: Operating System :: OS Independent
17
17
  Classifier: Programming Language :: Python :: 3
@@ -50,7 +50,7 @@ Description-Content-Type: text/markdown
50
50
 
51
51
  <!-- mcp-name: io.github.bricksentry/bricksentry -->
52
52
 
53
- [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
53
+ [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Status](https://img.shields.io/badge/status-public%20beta-orange)](#project-status-public-beta)
54
54
 
55
55
  ***The safety check for data changes in the AI era.***
56
56
 
@@ -219,7 +219,7 @@ The new value is hidden too, because an agent can write `SET note = ssn` and rea
219
219
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
220
220
  ```
221
221
 
222
- The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Without `agent_tables`, agents can check any table bricksentry can read.
222
+ The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Views and SQL functions are checked through their definitions: bricksentry reads each view's query and each SQL function's body from Unity Catalog (`system.information_schema`) and holds every table inside them to the list too, recursively. A view or function whose definition can't be read is refused, and so is every agent preview if the catalog can't be read at all. A listed view over an unlisted table counts as the unlisted table. On Databricks, the statement's query plan (`EXPLAIN`, which runs nothing) is a second opinion: an unlisted table in it means refusal, but because plan formats vary on serverless, a plan that can't be read doesn't block anything. Without `agent_tables`, agents can check any table bricksentry can read.
223
223
 
224
224
  **Metadata is data, not instructions.** Tag names and values and owners reach agents only when short and plain (`pii`, `true`, `finance-team`); longer or free text, which anyone who can tag a table could write, shows as `[text hidden: N chars]`. Policies still see the full tags. 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.
225
225
 
@@ -483,18 +483,33 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
483
483
 
484
484
  ## What a check costs
485
485
 
486
- 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`.
486
+ The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four 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`.
487
487
 
488
488
  ## Audit trail
489
489
 
490
490
  Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 fingerprint of the policy rules that produced the verdict, and who triggered it (`BRICKSENTRY_ACTOR`, or the GitHub actor in GitHub Actions). They're in the JSON and in the footer of the pull-request report, so a verdict can be traced to the exact rules behind it. Assessments are saved as JSON under `assessment_store`; point it at a shared, access-controlled folder to keep a history.
491
491
 
492
+ ## Project status: public beta
493
+
494
+ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by its author, on Databricks Free Edition: nine adversarial rounds with every serious finding fixed and re-verified ([VALIDATION.md](VALIDATION.md)). It has not yet run on other teams' production pipelines, other clouds or classic compute, which is what the beta is for.
495
+
496
+ **What you can rely on in the beta:**
497
+
498
+ - **The safety direction.** When bricksentry can't verify something (a failed diff, a missing candidate, a masked column, a row filter, a table rewritten during the check), it asks a human. It never turns "couldn't check" into a pass.
499
+ - **Production is never written** by `preview_write` or any check: previews run on disposable shallow clones, and refused statements stay refused.
500
+ - **What agents see:** counts, columns and verdicts, never production values, and only for the tables in `agent_tables`.
501
+ - **Your files keep working.** `bricksentry.yml`, policy files and saved assessments from earlier 0.1.x releases load in later ones (checked back to 0.1.15). Any change in behavior is marked **Behavior change** in the [changelog](CHANGELOG.md).
502
+
503
+ **What may still change before 1.0:** default policy rules, the wording of reasons and summaries, fields added to JSON output (fields aren't removed or renamed without a changelog note), and defaults such as whether `agent_tables` is required for agents.
504
+
505
+ **1.0** comes when two or three outside teams have run it on real pipelines for a month without a serious finding, with validation reports from at least two clouds. If you'd like to be one of them, [open an issue](https://github.com/bricksentry/bricksentry/issues) or run the [validation notebook](examples/databricks/bricksentry_validation.py) and [share the report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml).
506
+
492
507
  ## Known limits (v0.1.x)
493
508
 
494
509
  - **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.
495
510
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
496
511
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
497
- - **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.28 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, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. 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.
512
+ - **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.28 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, 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, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. 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.
498
513
 
499
514
  ## Roadmap
500
515
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  <!-- mcp-name: io.github.bricksentry/bricksentry -->
4
4
 
5
- [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
5
+ [![PyPI](https://img.shields.io/pypi/v/bricksentry)](https://pypi.org/project/bricksentry/) [![Python](https://img.shields.io/pypi/pyversions/bricksentry)](https://pypi.org/project/bricksentry/) [![Tests](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![Lint](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml/badge.svg)](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [![Coverage](https://img.shields.io/badge/coverage-%E2%89%A575%25%20enforced-brightgreen)](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Status](https://img.shields.io/badge/status-public%20beta-orange)](#project-status-public-beta)
6
6
 
7
7
  ***The safety check for data changes in the AI era.***
8
8
 
@@ -171,7 +171,7 @@ The new value is hidden too, because an agent can write `SET note = ssn` and rea
171
171
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
172
172
  ```
173
173
 
174
- The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Without `agent_tables`, agents can check any table bricksentry can read.
174
+ The list covers every table an agent touches: the target, every table its statement reads (subqueries, joins, CTEs, `MERGE ... USING`), and any candidate it names. Statements that can't be checked by name are refused: table functions such as `table_changes()` or `read_files()`, `IDENTIFIER(...)`, path-based tables and SQL that doesn't parse. Write full names (`main.sales.orders`) when your patterns have three parts. Sources count too: for an agent to preview `MERGE INTO {{target}} USING main.sales.updates ...`, list `main.sales.updates` (or a pattern covering it) as well; a source left off the list, or written without its catalog, is refused. Views and SQL functions are checked through their definitions: bricksentry reads each view's query and each SQL function's body from Unity Catalog (`system.information_schema`) and holds every table inside them to the list too, recursively. A view or function whose definition can't be read is refused, and so is every agent preview if the catalog can't be read at all. A listed view over an unlisted table counts as the unlisted table. On Databricks, the statement's query plan (`EXPLAIN`, which runs nothing) is a second opinion: an unlisted table in it means refusal, but because plan formats vary on serverless, a plan that can't be read doesn't block anything. Without `agent_tables`, agents can check any table bricksentry can read.
175
175
 
176
176
  **Metadata is data, not instructions.** Tag names and values and owners reach agents only when short and plain (`pii`, `true`, `finance-team`); longer or free text, which anyone who can tag a table could write, shows as `[text hidden: N chars]`. Policies still see the full tags. 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.
177
177
 
@@ -435,18 +435,33 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
435
435
 
436
436
  ## What a check costs
437
437
 
438
- 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`.
438
+ The work runs on your SQL warehouse as plain SQL; nothing large is copied out. One table diff runs about five queries (plus three or four 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`.
439
439
 
440
440
  ## Audit trail
441
441
 
442
442
  Every assessment records when it ran (UTC), the bricksentry version, a SHA-256 fingerprint of the policy rules that produced the verdict, and who triggered it (`BRICKSENTRY_ACTOR`, or the GitHub actor in GitHub Actions). They're in the JSON and in the footer of the pull-request report, so a verdict can be traced to the exact rules behind it. Assessments are saved as JSON under `assessment_store`; point it at a shared, access-controlled folder to keep a history.
443
443
 
444
+ ## Project status: public beta
445
+
446
+ bricksentry is in **public beta** (0.1.x). It has been tested hard but only by its author, on Databricks Free Edition: nine adversarial rounds with every serious finding fixed and re-verified ([VALIDATION.md](VALIDATION.md)). It has not yet run on other teams' production pipelines, other clouds or classic compute, which is what the beta is for.
447
+
448
+ **What you can rely on in the beta:**
449
+
450
+ - **The safety direction.** When bricksentry can't verify something (a failed diff, a missing candidate, a masked column, a row filter, a table rewritten during the check), it asks a human. It never turns "couldn't check" into a pass.
451
+ - **Production is never written** by `preview_write` or any check: previews run on disposable shallow clones, and refused statements stay refused.
452
+ - **What agents see:** counts, columns and verdicts, never production values, and only for the tables in `agent_tables`.
453
+ - **Your files keep working.** `bricksentry.yml`, policy files and saved assessments from earlier 0.1.x releases load in later ones (checked back to 0.1.15). Any change in behavior is marked **Behavior change** in the [changelog](CHANGELOG.md).
454
+
455
+ **What may still change before 1.0:** default policy rules, the wording of reasons and summaries, fields added to JSON output (fields aren't removed or renamed without a changelog note), and defaults such as whether `agent_tables` is required for agents.
456
+
457
+ **1.0** comes when two or three outside teams have run it on real pipelines for a month without a serious finding, with validation reports from at least two clouds. If you'd like to be one of them, [open an issue](https://github.com/bricksentry/bricksentry/issues) or run the [validation notebook](examples/databricks/bricksentry_validation.py) and [share the report](https://github.com/bricksentry/bricksentry/issues/new?template=validation_report.yml).
458
+
444
459
  ## Known limits (v0.1.x)
445
460
 
446
461
  - **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.
447
462
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
448
463
  - **Changed-table detection uses path globs** from config. It doesn't parse Asset Bundles yet.
449
- - **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.28 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, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. 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.
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.28 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, 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, a round of leak, data-shape and race tests whose four findings were fixed in 0.1.27, and a round on MERGE, allowlist bypasses, metadata injection, remote access and governance features whose findings were fixed in 0.1.28. 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.
450
465
 
451
466
  ## Roadmap
452
467
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.29
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.28"
7
+ version = "0.1.29"
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"
@@ -16,7 +16,7 @@ keywords = [
16
16
  "change-impact-analysis", "deployment-guardrails", "rollback",
17
17
  ]
18
18
  classifiers = [
19
- "Development Status :: 3 - Alpha",
19
+ "Development Status :: 4 - Beta",
20
20
  "Intended Audience :: Developers",
21
21
  "Programming Language :: Python :: 3",
22
22
  "Programming Language :: Python :: 3.10",
@@ -8,12 +8,12 @@
8
8
  "source": "github"
9
9
  },
10
10
  "websiteUrl": "https://bricksentry.org",
11
- "version": "0.1.28",
11
+ "version": "0.1.29",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.28",
16
+ "version": "0.1.29",
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.28"
26
+ __version__ = "0.1.29"
@@ -132,7 +132,9 @@ def assess_change(
132
132
  tables = list(tables)
133
133
  # Candidates an agent names are checked too: pointing an allowed table's candidate
134
134
  # at a forbidden table would otherwise diff the forbidden one.
135
- _gate(s, "assess_change", tables + [c for c in (candidates or {}).values() if c])
135
+ named = tables + [c for c in (candidates or {}).values() if c]
136
+ _gate(s, "assess_change", named)
137
+ _gate_views(s, "assess_change", named) # a listed view over an unlisted table counts as that table
136
138
  a = s.assess(tables, candidates=candidates, pr=pr)
137
139
  out = agent_view.for_agent(a, s)
138
140
  agent_view.audit(s, "assess_change", tables, out)
@@ -168,6 +170,7 @@ def preview_write(
168
170
  # Every table the statement reads must be allowed too (a subquery, MERGE USING, a
169
171
  # join or a CTE could otherwise turn the counts into facts about a forbidden table).
170
172
  _gate_sql(s, "preview_write", [target], sql.replace("{{target}}", target))
173
+ _gate_plan(s, "preview_write", target, sql.replace("{{target}}", target))
171
174
  raw = s.preview_write(sql, target, keys=keys)
172
175
  a = s.get_assessment(raw["id"])
173
176
  out = agent_view.for_agent(a, s, {"preview": raw.get("preview")}) if a else agent_view.scrub(raw)
@@ -281,6 +284,22 @@ def _gate_sql(s: Sentry, tool: str, tables: list[str], sql: str) -> None:
281
284
  raise
282
285
 
283
286
 
287
+ def _gate_views(s: Sentry, tool: str, tables: list[str]) -> None:
288
+ try:
289
+ agent_view.check_definitions(s, tables, [])
290
+ except PermissionError as e:
291
+ agent_view.audit(s, tool, tables, refused=str(e))
292
+ raise
293
+
294
+
295
+ def _gate_plan(s: Sentry, tool: str, target: str, sql: str) -> None:
296
+ try:
297
+ agent_view.check_plan(s, sql, target)
298
+ except PermissionError as e:
299
+ agent_view.audit(s, tool, [target], refused=str(e))
300
+ raise
301
+
302
+
284
303
  def _gate(s: Sentry, tool: str, tables: list[str]) -> None:
285
304
  try:
286
305
  agent_view.check_allowed(s, tables)
@@ -179,7 +179,11 @@ def allowed(sentry: Sentry, table: str) -> bool:
179
179
 
180
180
 
181
181
  def tables_read(sql: str, dialect: str) -> list[str]:
182
- """Every table a statement touches, as written (``catalog.schema.table``), via a real
182
+ return statement_refs(sql, dialect)[0]
183
+
184
+
185
+ def statement_refs(sql: str, dialect: str) -> tuple[list[str], list[str]]:
186
+ """Tables and user functions a statement uses. Every table a statement touches, as written (``catalog.schema.table``), via a real
183
187
  SQL parser. Raises PermissionError for anything that can't be checked by name:
184
188
  unparseable SQL, table functions (``table_changes(...)``, ``read_files(...)``,
185
189
  ``IDENTIFIER(...)``) and path-based tables (``delta.`/path```)."""
@@ -213,7 +217,16 @@ def tables_read(sql: str, dialect: str) -> list[str]:
213
217
  if "/" in name or ":" in name:
214
218
  raise PermissionError(f"Path-based tables ({name}) are refused for agents. Use a Unity Catalog table name.")
215
219
  out.append(name)
216
- return out
220
+ funcs: list[str] = []
221
+ for a in tree.find_all(exp.Anonymous): # functions sqlglot doesn't know: possibly UDFs
222
+ parts, p = [a.name], a.parent
223
+ while isinstance(p, exp.Dot):
224
+ parts.insert(0, p.this.sql(dialect=dialect).replace("`", ""))
225
+ p = p.parent
226
+ name = ".".join(parts)
227
+ if name.lower() not in [f.lower() for f in funcs]:
228
+ funcs.append(name)
229
+ return out, funcs
217
230
 
218
231
 
219
232
  def check_statement(sentry: Sentry, sql: str) -> None:
@@ -222,8 +235,103 @@ def check_statement(sentry: Sentry, sql: str) -> None:
222
235
  doesn't match: write the full name."""
223
236
  if sentry.config.agent_tables is None:
224
237
  return
225
- dialect = "duckdb" if getattr(sentry.backend, "name", "") == "duckdb" else "databricks"
226
- check_allowed(sentry, tables_read(sql, dialect))
238
+ tables, funcs = statement_refs(sql, _dialect(sentry))
239
+ check_allowed(sentry, tables)
240
+ check_definitions(sentry, tables, funcs)
241
+
242
+
243
+ def _dialect(sentry: Sentry) -> str:
244
+ return "duckdb" if getattr(sentry.backend, "name", "") == "duckdb" else "databricks"
245
+
246
+
247
+ _MAX_DEPTH = 5
248
+
249
+
250
+ def check_definitions(sentry: Sentry, tables: list[str], funcs: list[str], depth: int = 0) -> None:
251
+ """Views and SQL functions read tables the statement doesn't name. Read their
252
+ definitions from the catalog and hold every table inside to ``agent_tables`` too,
253
+ recursively (a view over a view, a function calling a function). A definition that
254
+ can't be read is refused. The engine's query plan can't be relied on for this:
255
+ serverless plans don't show tables inside views or functions."""
256
+ if sentry.config.agent_tables is None or (not tables and not funcs):
257
+ return
258
+ if depth > _MAX_DEPTH:
259
+ raise PermissionError("Views or functions nest too deeply to check, so the statement is refused for agents.")
260
+ try:
261
+ views = sentry.backend.view_definitions(tables) if tables else {}
262
+ bodies = sentry.backend.function_bodies(funcs) if funcs else []
263
+ except Exception as e:
264
+ raise PermissionError(
265
+ "Couldn't read view and function definitions from the catalog to check what they read, so the "
266
+ f"statement is refused for agents ({_first(e)})."
267
+ ) from None
268
+ for name, (definition, cat, schema) in views.items():
269
+ if not definition:
270
+ raise PermissionError(f"Can't read the definition of view {name} to check which tables it reads, so it's "
271
+ "refused for agents.")
272
+ inner, inner_funcs = _refs_of_body(sentry, definition, f"view {name}")
273
+ inner = [_qualify(t, cat, schema) for t in inner]
274
+ check_allowed(sentry, inner)
275
+ check_definitions(sentry, inner, inner_funcs, depth + 1)
276
+ for name, body, language, cat, schema in bodies:
277
+ if str(language).upper() != "SQL":
278
+ continue # Python and other external functions can't query tables
279
+ if not body:
280
+ raise PermissionError(f"Can't read the body of function {name} to check which tables it reads, so it's "
281
+ "refused for agents.")
282
+ inner, inner_funcs = _refs_of_body(sentry, body, f"function {name}")
283
+ inner = [_qualify(t, cat, schema) for t in inner]
284
+ check_allowed(sentry, inner)
285
+ check_definitions(sentry, inner, inner_funcs, depth + 1)
286
+
287
+
288
+ def _refs_of_body(sentry: Sentry, text: str, what: str) -> tuple[list[str], list[str]]:
289
+ d = _dialect(sentry)
290
+ for candidate in (text, f"SELECT {text}"): # a view is a query; a function body may be an expression
291
+ try:
292
+ return statement_refs(candidate, d)
293
+ except PermissionError as e:
294
+ if "parse" not in str(e).lower():
295
+ raise
296
+ raise PermissionError(f"Couldn't parse the {what} to check which tables it reads, so it's refused for agents.")
297
+
298
+
299
+ def _qualify(name: str, catalog: str | None, schema: str | None) -> str:
300
+ """Names inside a view or function resolve against its own catalog and schema."""
301
+ parts = name.split(".")
302
+ if len(parts) == 1 and schema:
303
+ parts = [schema] + parts
304
+ if len(parts) == 2 and catalog:
305
+ parts = [catalog] + parts
306
+ return ".".join(parts)
307
+
308
+
309
+ def _first(e: BaseException) -> str:
310
+ t = str(e).strip()
311
+ return redact_values(t.splitlines()[0][:200]) if t else type(e).__name__
312
+
313
+
314
+ def check_plan(sentry: Sentry, sql: str, target: str) -> None:
315
+ """A second opinion from the engine's own query plan (``EXPLAIN``, which runs
316
+ nothing): if the plan names a table that isn't in ``agent_tables``, refuse. The
317
+ boundary itself is the parser and the view and function definitions; plan formats
318
+ vary on serverless (compact plans, tables inside views and functions not shown), so
319
+ a plan that can't be read is no reason to refuse and no proof of safety."""
320
+ if sentry.config.agent_tables is None:
321
+ return
322
+ try:
323
+ names = sentry.backend.plan_tables(sql)
324
+ except Exception:
325
+ return
326
+ if not names:
327
+ return
328
+ check_allowed(sentry, [n for n in names if not _same(n, target)])
329
+
330
+
331
+ def _same(a: str, b: str) -> bool:
332
+ """Same table: equal names, or one ends with the other (``spark_catalog.s.t`` vs ``s.t``)."""
333
+ a, b = a.lower(), b.lower()
334
+ return a == b or a.endswith("." + b) or b.endswith("." + a)
227
335
 
228
336
 
229
337
  def check_allowed(sentry: Sentry, tables: list[str]) -> None:
@@ -39,13 +39,29 @@ 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 view_definitions(self, tables: list[str]) -> dict[str, tuple[str | None, str | None, str | None]]:
43
+ """For the names that are views: ``{name: (definition SQL, catalog, schema)}``.
44
+ Tables aren't listed. Raises if the catalog can't be read."""
45
+ return {}
46
+
47
+ def function_bodies(self, names: list[str]) -> list[tuple[str, str | None, str, str | None, str | None]]:
48
+ """User functions matching ``names`` (an unqualified name matches any schema):
49
+ ``[(full name, body, language, catalog, schema)]``. Built-ins aren't listed."""
50
+ return []
51
+
52
+ def plan_tables(self, sql: str) -> list[str] | None:
53
+ """Every table the engine's own query plan for ``sql`` reads, without running it.
54
+ ``None`` when the engine offers no plan to check (DuckDB)."""
55
+ return None
56
+
42
57
  def protections(self, tables: list[str]) -> dict[str, dict[str, Any]]:
43
58
  """Column masks and row filters per table: ``{table: {"masked": [cols], "row_filter": bool}}``.
44
59
  Engines without them return nothing."""
45
60
  return {}
46
61
 
47
- def columns_at(self, table: str, version: int | None) -> dict[str, str]:
48
- """Like :meth:`columns`, for ``table`` at ``version``."""
62
+ def columns_at(self, table: str, version: int | None, strict: bool = False) -> dict[str, str]:
63
+ """Like :meth:`columns`, for ``table`` at ``version``. With ``strict``, raise if the
64
+ version can't be read (engines without time travel just read the table)."""
49
65
  return self.columns(table)
50
66
 
51
67
  def canon(self, expr: str, type_name: str) -> str:
@@ -7,6 +7,7 @@ OAuth, Azure/GCP identity...). Nothing in bricksentry handles credentials itself
7
7
  from __future__ import annotations
8
8
 
9
9
  import os
10
+ import re
10
11
  import time
11
12
  from typing import Any
12
13
 
@@ -147,6 +148,51 @@ class DatabricksBackend(Backend):
147
148
  f"CREATE OR REPLACE TABLE {self.qualified(target)} SHALLOW CLONE {self.qualified(source)}"
148
149
  )
149
150
 
151
+ def _name_filter(self, names: list[str], cat_col: str, schema_col: str, name_col: str, loose_single: bool):
152
+ conds = []
153
+ for n in names:
154
+ parts = [p.strip("`").lower() for p in n.split(".")]
155
+ cat = self._lit(parts[0]) if len(parts) == 3 else "lower(current_catalog())"
156
+ if len(parts) >= 2:
157
+ conds.append(f"(lower({cat_col}) = {cat} AND lower({schema_col}) = {self._lit(parts[-2])} "
158
+ f"AND lower({name_col}) = {self._lit(parts[-1])})")
159
+ elif loose_single: # an unqualified function name: any schema, to be safe
160
+ conds.append(f"lower({name_col}) = {self._lit(parts[0])}")
161
+ else:
162
+ conds.append(f"(lower({cat_col}) = lower(current_catalog()) AND lower({schema_col}) = "
163
+ f"lower(current_schema()) AND lower({name_col}) = {self._lit(parts[0])})")
164
+ return " OR ".join(conds) or "FALSE"
165
+
166
+ def view_definitions(self, tables: list[str]) -> dict[str, tuple[str | None, str | None, str | None]]:
167
+ # system.information_schema covers every catalog the identity can see.
168
+ where = self._name_filter(tables, "table_catalog", "table_schema", "table_name", loose_single=False)
169
+ rows = self.query("SELECT table_catalog, table_schema, table_name, view_definition "
170
+ f"FROM system.information_schema.views WHERE {where}")
171
+ out: dict[str, tuple[str | None, str | None, str | None]] = {}
172
+ for t in tables:
173
+ parts = [p.strip("`").lower() for p in t.split(".")]
174
+ for r in rows:
175
+ got = [str(r.get(k, "")).lower() for k in ("table_catalog", "table_schema", "table_name")]
176
+ if got[-len(parts):] == parts:
177
+ out[t] = (r.get("view_definition"), r.get("table_catalog"), r.get("table_schema"))
178
+ return out
179
+
180
+ def function_bodies(self, names: list[str]) -> list[tuple[str, str | None, str, str | None, str | None]]:
181
+ where = self._name_filter(names, "routine_catalog", "routine_schema", "routine_name", loose_single=True)
182
+ rows = self.query("SELECT routine_catalog, routine_schema, routine_name, routine_body, routine_definition "
183
+ f"FROM system.information_schema.routines WHERE {where}")
184
+ return [(f"{r.get('routine_catalog')}.{r.get('routine_schema')}.{r.get('routine_name')}",
185
+ r.get("routine_definition"), str(r.get("routine_body") or ""), r.get("routine_catalog"),
186
+ r.get("routine_schema")) for r in rows]
187
+
188
+ def plan_tables(self, sql: str) -> list[str] | None:
189
+ # EXPLAIN EXTENDED plans the statement without running it. The analyzed plan names
190
+ # every relation Spark resolved, including inside SQL functions and views, which
191
+ # no SQL parser can see. Planning errors come back as text, not exceptions.
192
+ rows = self.query(f"EXPLAIN EXTENDED {sql}")
193
+ text = "\n".join(str(v) for r in rows for v in r.values() if v is not None)
194
+ return parse_plan_tables(text)
195
+
150
196
  def protections(self, tables: list[str]) -> dict[str, dict[str, Any]]:
151
197
  # Unity Catalog lists masks and row filters in each catalog's information_schema.
152
198
  # One query per catalog. If it can't be read (no UC, no access), say nothing:
@@ -182,15 +228,19 @@ class DatabricksBackend(Backend):
182
228
  def _lit(v: str) -> str:
183
229
  return "'" + v.replace("\\", "\\\\").replace("'", "\\'") + "'"
184
230
 
185
- def columns_at(self, table: str, version: int | None) -> dict[str, str]:
231
+ def columns_at(self, table: str, version: int | None, strict: bool = False) -> dict[str, str]:
186
232
  if version is None:
187
233
  return self.columns(table)
188
234
  try:
189
235
  rows = self.query(f"DESCRIBE QUERY SELECT * FROM {self.at_version(table, version)}")
190
236
  except Exception:
237
+ if strict:
238
+ raise
191
239
  return self.columns(table)
192
240
  out = {(r.get("col_name") or "").strip(): str(r.get("data_type", "")).lower() for r in rows}
193
241
  out.pop("", None)
242
+ if not out and strict:
243
+ raise RuntimeError(f"no columns for {table} at version {version}")
194
244
  return out or self.columns(table)
195
245
 
196
246
  def at_version(self, table: str, version: int | None) -> str:
@@ -275,3 +325,34 @@ def _convert(v: Any, t: str) -> Any:
275
325
  except (TypeError, ValueError):
276
326
  return v
277
327
  return v
328
+
329
+
330
+ class PlanError(RuntimeError):
331
+ pass
332
+
333
+
334
+ _PLAN_NAMES = [
335
+ # serverless "Edge" plans print fully quoted names: `catalog`.`schema`.`table`
336
+ re.compile(r"(`[^`]+`\.`[^`]+`(?:\.`[^`]+`)?)"),
337
+ re.compile(r"\bRelation\s+([^\s\[]+)\["),
338
+ re.compile(r"\bSubqueryAlias\s+([^\s]+)"),
339
+ re.compile(r"\bView\s+\(\s*`?([^,`)]+)`?\s*,"),
340
+ ]
341
+
342
+
343
+ def parse_plan_tables(text: str) -> list[str]:
344
+ """Table names (two or more parts) from Spark's EXPLAIN EXTENDED output, analyzed plan first."""
345
+ low = text.lower()
346
+ if "error occurred during query planning" in low or "analysisexception" in low or "== analyzed logical plan ==" not in low:
347
+ first = next((ln.strip() for ln in text.splitlines() if "error" in ln.lower()), "no analyzed plan")
348
+ raise PlanError(f"Spark couldn't plan the statement ({first[:200]})")
349
+ start = low.index("== analyzed logical plan ==")
350
+ end = low.find("== optimized logical plan ==", start)
351
+ section = text[start:end if end > 0 else None]
352
+ out: list[str] = []
353
+ for rx in _PLAN_NAMES:
354
+ for m in rx.finditer(section):
355
+ name = m.group(1).replace("`", "").strip().rstrip(",")
356
+ if name.count(".") >= 1 and name.lower() not in [o.lower() for o in out]:
357
+ out.append(name)
358
+ return out
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from typing import Any
6
7
 
7
8
  from bricksentry.backends.base import Backend
@@ -66,3 +67,28 @@ class DuckDBBackend(Backend):
66
67
  self.execute(
67
68
  f"CREATE OR REPLACE TABLE {self.qualified(target)} AS SELECT * FROM {self.qualified(source)}"
68
69
  )
70
+
71
+ def view_definitions(self, tables):
72
+ rows = self.query("SELECT schema_name, view_name, sql FROM duckdb_views() WHERE NOT internal")
73
+ out = {}
74
+ for t in tables:
75
+ parts = [p.strip('"').lower() for p in t.split(".")]
76
+ schema, name = (parts[-2] if len(parts) >= 2 else "main"), parts[-1]
77
+ for r in rows:
78
+ if str(r["schema_name"]).lower() == schema and str(r["view_name"]).lower() == name:
79
+ m = re.search(r"\bAS\b\s*(.*)$", r["sql"] or "", re.S | re.I)
80
+ out[t] = ((m.group(1).strip().rstrip(";") if m else None), None, r["schema_name"])
81
+ return out
82
+
83
+ def function_bodies(self, names):
84
+ rows = self.query("SELECT schema_name, function_name, macro_definition FROM duckdb_functions() "
85
+ "WHERE function_type IN ('macro', 'table_macro') AND NOT internal")
86
+ out = []
87
+ for n in names:
88
+ parts = n.lower().split(".")
89
+ for r in rows:
90
+ if str(r["function_name"]).lower() == parts[-1] and (len(parts) < 2 or str(r["schema_name"]).lower() == parts[-2]):
91
+ out.append((f"{r['schema_name']}.{r['function_name']}", r["macro_definition"], "SQL", None,
92
+ r["schema_name"]))
93
+ return out
94
+