bricksentry 0.1.28__tar.gz → 0.1.30__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 (96) hide show
  1. {bricksentry-0.1.28 → bricksentry-0.1.30}/CHANGELOG.md +16 -0
  2. {bricksentry-0.1.28 → bricksentry-0.1.30}/PKG-INFO +43 -9
  3. {bricksentry-0.1.28 → bricksentry-0.1.30}/README.md +41 -7
  4. bricksentry-0.1.30/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.28 → bricksentry-0.1.30}/pyproject.toml +2 -2
  6. {bricksentry-0.1.28 → bricksentry-0.1.30}/server.json +2 -2
  7. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/__init__.py +1 -1
  8. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/agent_tools.py +20 -1
  9. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/agent_view.py +112 -4
  10. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/assess.py +24 -2
  11. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/backends/base.py +18 -2
  12. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/backends/databricks_backend.py +82 -1
  13. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/backends/duckdb_backend.py +26 -0
  14. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/diff.py +26 -18
  15. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/explain.py +7 -1
  16. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/databricks_template_schema.json +2 -2
  17. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0127.py +3 -3
  18. bricksentry-0.1.30/tests/test_0129.py +235 -0
  19. bricksentry-0.1.30/tests/test_0130.py +52 -0
  20. bricksentry-0.1.28/deploy/databricks-app/requirements.txt +0 -1
  21. {bricksentry-0.1.28 → bricksentry-0.1.30}/.gitignore +0 -0
  22. {bricksentry-0.1.28 → bricksentry-0.1.30}/CONTRIBUTING.md +0 -0
  23. {bricksentry-0.1.28 → bricksentry-0.1.30}/LICENSE +0 -0
  24. {bricksentry-0.1.28 → bricksentry-0.1.30}/SECURITY.md +0 -0
  25. {bricksentry-0.1.28 → bricksentry-0.1.30}/action.yml +0 -0
  26. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/container/Dockerfile +0 -0
  27. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/databricks-app/README.md +0 -0
  28. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/databricks-app/app.yaml +0 -0
  29. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/databricks-app/bricksentry.yml +0 -0
  30. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/databricks-app/databricks.yml +0 -0
  31. {bricksentry-0.1.28 → bricksentry-0.1.30}/deploy/databricks-app/grants.sql +0 -0
  32. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry.yml +0 -0
  33. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  34. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_check_my_table.py +0 -0
  35. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  36. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  37. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  38. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_quickstart.py +0 -0
  39. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_validation.ipynb +0 -0
  40. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/bricksentry_validation.py +0 -0
  41. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/github-workflow.yml +0 -0
  42. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/databricks/policy.yml +0 -0
  43. {bricksentry-0.1.28 → bricksentry-0.1.30}/examples/demo/agent_loop_demo.py +0 -0
  44. {bricksentry-0.1.28 → bricksentry-0.1.30}/scripts/build_notebook.py +0 -0
  45. {bricksentry-0.1.28 → bricksentry-0.1.30}/scripts/render_demo_image.py +0 -0
  46. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/__main__.py +0 -0
  47. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/backends/__init__.py +0 -0
  48. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/changes.py +0 -0
  49. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/cli.py +0 -0
  50. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/config.py +0 -0
  51. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/demo.py +0 -0
  52. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/github.py +0 -0
  53. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/history.py +0 -0
  54. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/job.py +0 -0
  55. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/job_demo.py +0 -0
  56. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/lineage.py +0 -0
  57. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/mcp_server.py +0 -0
  58. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/measures.py +0 -0
  59. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/models.py +0 -0
  60. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/netguard.py +0 -0
  61. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/notify.py +0 -0
  62. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/policy.py +0 -0
  63. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/policy_templates.py +0 -0
  64. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/preview.py +0 -0
  65. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/py.typed +0 -0
  66. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/report.py +0 -0
  67. {bricksentry-0.1.28 → bricksentry-0.1.30}/src/bricksentry/validation.py +0 -0
  68. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/README.md +0 -0
  69. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  70. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/README.md.tmpl +0 -0
  71. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  72. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +0 -0
  73. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  74. {bricksentry-0.1.28 → bricksentry-0.1.30}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  75. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/conftest.py +0 -0
  76. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0110.py +0 -0
  77. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0112.py +0 -0
  78. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0114.py +0 -0
  79. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0120.py +0 -0
  80. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0121.py +0 -0
  81. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0122.py +0 -0
  82. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0123.py +0 -0
  83. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0126.py +0 -0
  84. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_0128.py +0 -0
  85. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_018.py +0 -0
  86. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_019.py +0 -0
  87. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_assess_policy.py +0 -0
  88. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_check_notebook.py +0 -0
  89. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_databricks_and_uc.py +0 -0
  90. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_demo.py +0 -0
  91. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_diff.py +0 -0
  92. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_hr_notebook.py +0 -0
  93. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_notebook.py +0 -0
  94. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_notify_templates.py +0 -0
  95. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_preview_agents.py +0 -0
  96. {bricksentry-0.1.28 → bricksentry-0.1.30}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.30 (2026-11-18)
4
+
5
+ A patch from the first real use of bricksentry as an assistant's safety gate: an assistant built a Bronze/Silver/Gold HR pipeline, then changed the Gold logic only after `whats_downstream`, `rollback_plan`, `preview_write` and `safe_to_ship`. Verified on Databricks before release: the CTAS preview that failed now runs with exact counts, a CTAS reading the table it replaces works, nothing is left in the sandbox, production stays at its version, and the battery passed 15 of 15.
6
+
7
+ - **`CREATE OR REPLACE TABLE` previews work on serverless.** The preview replaced the shallow clone itself, which serverless refuses (`CLUSTER BY AUTO is only supported on UC Managed tables`, because new tables get automatic clustering by default). The statement's result now goes into a fresh sandbox table, the clone stays for reading the target (`CREATE OR REPLACE TABLE t AS SELECT ... FROM t`), and both are dropped afterwards. Other writes still run on the clone. Found while an assistant built and changed an HR pipeline with bricksentry as its gate.
8
+ - Agent errors keep quoted text that has no letters or digits, such as Delta's list of characters a column name can't contain (` ,;{}()\n\t=`), so an agent can see it needs a column alias. Quoted values are still hidden.
9
+
10
+ ## 0.1.29 (2026-11-17)
11
+
12
+ 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.
13
+
14
+ - **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.
15
+ - **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.
16
+ - **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.
17
+ - 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.
18
+
3
19
  ## 0.1.28 (2026-11-17)
4
20
 
5
21
  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.30
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
@@ -46,15 +46,22 @@ Provides-Extra: mcp
46
46
  Requires-Dist: mcp>=1.10; extra == 'mcp'
47
47
  Description-Content-Type: text/markdown
48
48
 
49
- # Welcome to bricksentry
49
+ # bricksentry
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
- ***The safety check for data changes in the AI era.***
55
+ ***See what a data change does before it ships.***
56
56
 
57
- Change-safety for Databricks pipelines and the AI agents that edit them: know what a change does to your data before it ships.
57
+ A pipeline change or an AI agent's MERGE can look right, pass every test and still quietly duplicate or drop rows. bricksentry checks the data itself before the change reaches production: it compares the rows the change would produce with what's there now, shows what's downstream in Unity Catalog lineage, and gives a verdict from your own policy: **pass**, **needs a human**, or **block**.
58
+
59
+ - **Real data, not a guess.** Agent previews run the statement on a disposable shallow clone; PR checks compare the tables your branch built. Rows added, removed and changed, column by column, exact to the row.
60
+ - **Fails closed.** If something can't be verified (a failed diff, a masked column, a table rewritten mid-check), it asks a human. It never treats "couldn't check" as a pass.
61
+ - **Agents see counts, never values,** and only for the tables you allow, including tables reached through views and SQL functions.
62
+ - **Fits how you work:** a GitHub PR check, a Databricks job task, a CLI, Python, or an MCP server for AI agents (with token auth over the network). Rollback plans come with every verdict.
63
+
64
+ *Public beta: tested in [ten adversarial rounds](VALIDATION.md), with every finding fixed and published.*
58
65
 
59
66
  **[Try it in 30 seconds](#1-try-it-in-30-seconds-on-your-laptop)** · **[Check every change on Databricks](#2-check-every-change-to-your-tables-on-databricks)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[Validated live: what we tested and found](VALIDATION.md)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
60
67
 
@@ -219,7 +226,7 @@ The new value is hidden too, because an agent can write `SET note = ssn` and rea
219
226
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
220
227
  ```
221
228
 
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.
229
+ 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
230
 
224
231
  **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
232
 
@@ -483,18 +490,45 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
483
490
 
484
491
  ## What a check costs
485
492
 
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`.
493
+ 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
494
 
488
495
  ## Audit trail
489
496
 
490
497
  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
498
 
499
+ ## Project status: public beta
500
+
501
+ 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.
502
+
503
+ **What you can rely on in the beta:**
504
+
505
+ - **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.
506
+ - **Production is never written** by `preview_write` or any check: previews run on disposable shallow clones, and refused statements stay refused.
507
+ - **What agents see:** counts, columns and verdicts, never production values, and only for the tables in `agent_tables`.
508
+ - **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).
509
+
510
+ **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.
511
+
512
+ **Before 1.0**, these need proving in environments other than the author's:
513
+
514
+ | What | How it gets checked |
515
+ |---|---|
516
+ | Separate identities: an agent identity that isn't bricksentry's, and people exempt from column masks | A team with service principals runs the validation notebook under a second identity |
517
+ | Classic compute (clusters and classic SQL warehouses), including its query-plan format | A validation report from classic compute |
518
+ | AWS, Azure and GCP workspaces | Validation reports from at least two clouds |
519
+ | The added time of the query-plan check on each agent preview, with several agents at once | Measured live |
520
+ | Pull-request comments and `--from-git` on the current code | Re-run on a real repository |
521
+ | The MCP server over weeks: long runs and restarts | A team running it day to day |
522
+ | Count probing on listed tables (documented above) | Kept as documented, or an optional per-table limit if users ask for one |
523
+
524
+ **1.0** comes when those are done and two or three outside teams have run it on real pipelines for a month without a serious finding. 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).
525
+
492
526
  ## Known limits (v0.1.x)
493
527
 
494
528
  - **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
529
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
496
530
  - **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.
531
+ - **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
532
 
499
533
  ## Roadmap
500
534
 
@@ -1,12 +1,19 @@
1
- # Welcome to bricksentry
1
+ # bricksentry
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
- ***The safety check for data changes in the AI era.***
7
+ ***See what a data change does before it ships.***
8
8
 
9
- Change-safety for Databricks pipelines and the AI agents that edit them: know what a change does to your data before it ships.
9
+ A pipeline change or an AI agent's MERGE can look right, pass every test and still quietly duplicate or drop rows. bricksentry checks the data itself before the change reaches production: it compares the rows the change would produce with what's there now, shows what's downstream in Unity Catalog lineage, and gives a verdict from your own policy: **pass**, **needs a human**, or **block**.
10
+
11
+ - **Real data, not a guess.** Agent previews run the statement on a disposable shallow clone; PR checks compare the tables your branch built. Rows added, removed and changed, column by column, exact to the row.
12
+ - **Fails closed.** If something can't be verified (a failed diff, a masked column, a table rewritten mid-check), it asks a human. It never treats "couldn't check" as a pass.
13
+ - **Agents see counts, never values,** and only for the tables you allow, including tables reached through views and SQL functions.
14
+ - **Fits how you work:** a GitHub PR check, a Databricks job task, a CLI, Python, or an MCP server for AI agents (with token auth over the network). Rollback plans come with every verdict.
15
+
16
+ *Public beta: tested in [ten adversarial rounds](VALIDATION.md), with every finding fixed and published.*
10
17
 
11
18
  **[Try it in 30 seconds](#1-try-it-in-30-seconds-on-your-laptop)** · **[Check every change on Databricks](#2-check-every-change-to-your-tables-on-databricks)** · **[Docs: bricksentry.org](https://bricksentry.org)** · **[Validated live: what we tested and found](VALIDATION.md)** · **[LinkedIn](https://www.linkedin.com/company/bricksentry-org/)**
12
19
 
@@ -171,7 +178,7 @@ The new value is hidden too, because an agent can write `SET note = ssn` and rea
171
178
  agent_tables: ["main.sales_dev.*", "main.sales.orders"] # globs, any case; others are refused
172
179
  ```
173
180
 
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.
181
+ 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
182
 
176
183
  **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
184
 
@@ -435,18 +442,45 @@ Without lineage access bricksentry still diffs, and adds a `lineage-unavailable`
435
442
 
436
443
  ## What a check costs
437
444
 
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`.
445
+ 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
446
 
440
447
  ## Audit trail
441
448
 
442
449
  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
450
 
451
+ ## Project status: public beta
452
+
453
+ 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.
454
+
455
+ **What you can rely on in the beta:**
456
+
457
+ - **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.
458
+ - **Production is never written** by `preview_write` or any check: previews run on disposable shallow clones, and refused statements stay refused.
459
+ - **What agents see:** counts, columns and verdicts, never production values, and only for the tables in `agent_tables`.
460
+ - **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).
461
+
462
+ **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.
463
+
464
+ **Before 1.0**, these need proving in environments other than the author's:
465
+
466
+ | What | How it gets checked |
467
+ |---|---|
468
+ | Separate identities: an agent identity that isn't bricksentry's, and people exempt from column masks | A team with service principals runs the validation notebook under a second identity |
469
+ | Classic compute (clusters and classic SQL warehouses), including its query-plan format | A validation report from classic compute |
470
+ | AWS, Azure and GCP workspaces | Validation reports from at least two clouds |
471
+ | The added time of the query-plan check on each agent preview, with several agents at once | Measured live |
472
+ | Pull-request comments and `--from-git` on the current code | Re-run on a real repository |
473
+ | The MCP server over weeks: long runs and restarts | A team running it day to day |
474
+ | Count probing on listed tables (documented above) | Kept as documented, or an optional per-table limit if users ask for one |
475
+
476
+ **1.0** comes when those are done and two or three outside teams have run it on real pipelines for a month without a serious finding. 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).
477
+
444
478
  ## Known limits (v0.1.x)
445
479
 
446
480
  - **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
481
  - **Keys are required.** Tables without a stable key can't be diffed row by row yet (an aggregate-profile mode is planned).
448
482
  - **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.
483
+ - **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
484
 
451
485
  ## Roadmap
452
486
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.30
@@ -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.30"
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.30",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.28",
16
+ "version": "0.1.30",
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.30"
@@ -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:
@@ -220,6 +220,16 @@ class Sentry:
220
220
  f"Could not clone {target} to preview the write: {_first_line(e)}. Check the table name "
221
221
  f"and that you can create tables in {schema or 'the sandbox schema'}."
222
222
  ) from None
223
+ # CREATE OR REPLACE TABLE writes its result into a fresh sandbox table rather than
224
+ # replacing the clone: some engines refuse to replace a shallow clone (serverless
225
+ # applies CLUSTER BY AUTO to new tables, which a clone can't take). The clone stays,
226
+ # for statements that read the target (CREATE OR REPLACE TABLE t AS SELECT ... FROM t).
227
+ result = clone
228
+ m = _REPLACE_HEAD.match(rewritten)
229
+ if m:
230
+ result = clone + "_out"
231
+ rewritten = rewritten[: m.start("name")] + ".".join(
232
+ self.backend.quote(p) for p in result.split(".")) + rewritten[m.end("name"):]
223
233
  try:
224
234
  try:
225
235
  self.backend.execute(rewritten)
@@ -227,13 +237,18 @@ class Sentry:
227
237
  raise RuntimeError(
228
238
  f"The statement failed on the preview clone, so production was not touched: {_first_line(e)}"
229
239
  ) from None
230
- diff = self.diff(target, clone, keys=keys, table=target)
240
+ diff = self.diff(target, result, keys=keys, table=target)
231
241
  assessment = self.assess([target], diffs={target: diff})
232
242
  finally:
233
243
  if not keep:
234
244
  self.backend.drop(clone)
245
+ if result != clone:
246
+ try:
247
+ self.backend.drop(result)
248
+ except Exception:
249
+ pass
235
250
  out = assessment.to_dict()
236
- out["preview"] = {"sandbox_table": clone if keep else None, "executed_sql": rewritten}
251
+ out["preview"] = {"sandbox_table": result if keep else None, "executed_sql": rewritten}
237
252
  return out
238
253
 
239
254
  # --- alerts ---------------------------------------------------------------
@@ -309,6 +324,13 @@ def changed_columns(diff: TableDiff | None) -> list[str]:
309
324
  return list(dict.fromkeys(out))
310
325
 
311
326
 
327
+ _REPLACE_HEAD = re.compile(
328
+ r"^\s*(?:CREATE\s+OR\s+REPLACE\s+TABLE|REPLACE\s+TABLE)\s+(?P<name>(?:`[^`]+`|\"[^\"]+\"|[\w\-]+)"
329
+ r"(?:\.(?:`[^`]+`|\"[^\"]+\"|[\w\-]+))*)",
330
+ re.IGNORECASE,
331
+ )
332
+
333
+
312
334
  def _first_line(e: BaseException) -> str:
313
335
  """The useful part of an engine error: its first line, trimmed."""
314
336
  text = str(e).strip()
@@ -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: