bricksentry 0.1.18__tar.gz → 0.1.20__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 (83) hide show
  1. {bricksentry-0.1.18 → bricksentry-0.1.20}/CHANGELOG.md +20 -0
  2. {bricksentry-0.1.18 → bricksentry-0.1.20}/PKG-INFO +3 -3
  3. {bricksentry-0.1.18 → bricksentry-0.1.20}/README.md +2 -2
  4. bricksentry-0.1.20/deploy/databricks-app/requirements.txt +1 -0
  5. {bricksentry-0.1.18 → bricksentry-0.1.20}/pyproject.toml +1 -1
  6. {bricksentry-0.1.18 → bricksentry-0.1.20}/scripts/render_demo_image.py +2 -0
  7. {bricksentry-0.1.18 → bricksentry-0.1.20}/server.json +2 -2
  8. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/__init__.py +1 -1
  9. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/cli.py +2 -0
  10. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/demo.py +12 -1
  11. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/history.py +61 -3
  12. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/job.py +2 -0
  13. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/job_demo.py +6 -1
  14. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/models.py +3 -0
  15. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/notify.py +6 -0
  16. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/report.py +2 -0
  17. bricksentry-0.1.20/templates/job-check/README.md +31 -0
  18. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/databricks_template_schema.json +22 -21
  19. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/README.md.tmpl +5 -2
  20. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/resources/bricksentry_check.job.yml.tmpl +2 -0
  21. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_0114.py +61 -21
  22. bricksentry-0.1.20/tests/test_0120.py +81 -0
  23. bricksentry-0.1.18/deploy/databricks-app/requirements.txt +0 -1
  24. bricksentry-0.1.18/templates/job-check/README.md +0 -13
  25. {bricksentry-0.1.18 → bricksentry-0.1.20}/.gitignore +0 -0
  26. {bricksentry-0.1.18 → bricksentry-0.1.20}/CONTRIBUTING.md +0 -0
  27. {bricksentry-0.1.18 → bricksentry-0.1.20}/LICENSE +0 -0
  28. {bricksentry-0.1.18 → bricksentry-0.1.20}/SECURITY.md +0 -0
  29. {bricksentry-0.1.18 → bricksentry-0.1.20}/action.yml +0 -0
  30. {bricksentry-0.1.18 → bricksentry-0.1.20}/deploy/databricks-app/README.md +0 -0
  31. {bricksentry-0.1.18 → bricksentry-0.1.20}/deploy/databricks-app/app.yaml +0 -0
  32. {bricksentry-0.1.18 → bricksentry-0.1.20}/deploy/databricks-app/bricksentry.yml +0 -0
  33. {bricksentry-0.1.18 → bricksentry-0.1.20}/deploy/databricks-app/databricks.yml +0 -0
  34. {bricksentry-0.1.18 → bricksentry-0.1.20}/deploy/databricks-app/grants.sql +0 -0
  35. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry.yml +0 -0
  36. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  37. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_check_my_table.py +0 -0
  38. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_hr_walkthrough.ipynb +0 -0
  39. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_hr_walkthrough.py +0 -0
  40. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  41. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/bricksentry_quickstart.py +0 -0
  42. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/github-workflow.yml +0 -0
  43. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/databricks/policy.yml +0 -0
  44. {bricksentry-0.1.18 → bricksentry-0.1.20}/examples/demo/agent_loop_demo.py +0 -0
  45. {bricksentry-0.1.18 → bricksentry-0.1.20}/scripts/build_notebook.py +0 -0
  46. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/__main__.py +0 -0
  47. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/agent_tools.py +0 -0
  48. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/assess.py +0 -0
  49. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/backends/__init__.py +0 -0
  50. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/backends/base.py +0 -0
  51. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/backends/databricks_backend.py +0 -0
  52. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/backends/duckdb_backend.py +0 -0
  53. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/changes.py +0 -0
  54. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/config.py +0 -0
  55. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/diff.py +0 -0
  56. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/explain.py +0 -0
  57. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/github.py +0 -0
  58. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/lineage.py +0 -0
  59. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/mcp_server.py +0 -0
  60. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/measures.py +0 -0
  61. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/policy.py +0 -0
  62. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/policy_templates.py +0 -0
  63. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/preview.py +0 -0
  64. {bricksentry-0.1.18 → bricksentry-0.1.20}/src/bricksentry/py.typed +0 -0
  65. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/.gitignore +0 -0
  66. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/databricks.yml.tmpl +0 -0
  67. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/src/bricksentry_check.py +0 -0
  68. {bricksentry-0.1.18 → bricksentry-0.1.20}/templates/job-check/template/{{.project_name}}/src/bricksentry_demo.py +0 -0
  69. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/conftest.py +0 -0
  70. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_0110.py +0 -0
  71. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_0112.py +0 -0
  72. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_018.py +0 -0
  73. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_019.py +0 -0
  74. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_assess_policy.py +0 -0
  75. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_check_notebook.py +0 -0
  76. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_databricks_and_uc.py +0 -0
  77. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_demo.py +0 -0
  78. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_diff.py +0 -0
  79. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_hr_notebook.py +0 -0
  80. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_notebook.py +0 -0
  81. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_notify_templates.py +0 -0
  82. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_preview_agents.py +0 -0
  83. {bricksentry-0.1.18 → bricksentry-0.1.20}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.20 (2026-11-13)
4
+
5
+ From a question on X: what happens to a valid write that lands after the bad change you want to undo?
6
+
7
+ - **"Newer data changes exist" warning.** `check-last-change` reads the table history again after the check. If data changes were committed after the checked version (because you passed `--version`, or a write landed while the check ran), it warns right above the `RESTORE` that restoring also undoes them, and lists them. The warning appears in the CLI, the job task log, the pull-request report, Slack and Teams alerts, and the JSON (`rollback_warning` on each table, `newer_changes` on the change). OPTIMIZE and VACUUM don't count.
8
+ - README: before acting on an older alert, run `check-last-change --version N` again to see what was written since.
9
+
10
+ ## 0.1.19 (2026-11-12)
11
+
12
+ - `bricksentry demo` showed black boxes instead of colored verdict labels in macOS Terminal, which doesn't support 24-bit color. Terminals that don't set `COLORTERM=truecolor` now get the standard named colors; the others keep the website's colors.
13
+ - When the scratch schema's catalog doesn't exist, `check-last-change`, the job task and the demo task say so and how to fix it, instead of a raw `NO_SUCH_CATALOG` error.
14
+ - README: how to run the demo inside a Databricks or Jupyter notebook (`%pip install`, then `run_demo()`).
15
+ - The job template pins 0.1.19 by default.
16
+
17
+ Bundle template changes, already live because `bundle init` reads the template from GitHub:
18
+
19
+ - `tables` is optional: leave it empty to deploy only the demo job and see a block before choosing your own tables. The only input without a default is now `warehouse_id`. The demo question comes first.
20
+ - The template README documents non-interactive init (`--config-file`) for CI, scripts and AI agents.
21
+ - `scratch_schema` defaults to `<your default catalog>.bricksentry_scratch` instead of `main.bricksentry_scratch`. Workspaces without a `main` catalog had their first demo run fail with "catalog not found" instead of the intended BLOCK.
22
+
3
23
  ## 0.1.18 (2026-11-12)
4
24
 
5
25
  See a block in your own workspace within minutes of `bundle init`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.18
3
+ Version: 0.1.20
4
4
  Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
5
5
  Project-URL: Homepage, https://bricksentry.org
6
6
  Project-URL: Documentation, https://bricksentry.org/docs
@@ -69,7 +69,7 @@ Built by Brahmareddy, Databricks Champion. Open source under Apache-2.0.
69
69
  uvx --from "bricksentry[duckdb]" bricksentry demo
70
70
  ```
71
71
 
72
- (Or `pip install "bricksentry[duckdb]"` and then `bricksentry demo`.) No Databricks account and nothing leaves your machine: it runs on a 20,000-row revenue table in local DuckDB. An AI agent previews a DELETE on a clone (production untouched), gets its pull request **blocked** for a join that duplicates 40 orders, fixes it, and is routed to the owners of a certified table downstream. Then a nightly pipeline commits a bad MERGE anyway: bricksentry finds it in the table history, skips the OPTIMIZE after it, **blocks** it for 25 duplicate keys, prints the `RESTORE` and applies it.
72
+ (Or `pip install "bricksentry[duckdb]"` and then `bricksentry demo`. In a Databricks or Jupyter notebook, run `%pip install "bricksentry[duckdb]"` in one cell, then `from bricksentry.demo import run_demo; run_demo()` in the next; on Databricks, add `dbutils.library.restartPython()` after the install.) No Databricks account and nothing leaves your machine: it runs on a 20,000-row revenue table in local DuckDB. An AI agent previews a DELETE on a clone (production untouched), gets its pull request **blocked** for a join that duplicates 40 orders, fixes it, and is routed to the owners of a certified table downstream. Then a nightly pipeline commits a bad MERGE anyway: bricksentry finds it in the table history, skips the OPTIMIZE after it, **blocks** it for 25 duplicate keys, prints the `RESTORE` and applies it.
73
73
 
74
74
  ![bricksentry demo: an agent's change is previewed, blocked, fixed and routed to the owners; then a bad pipeline commit is caught from table history and undone](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
75
75
 
@@ -115,7 +115,7 @@ bricksentry check-last-change main.sales.orders --version 42 # a specific ver
115
115
  bricksentry check-last-change main.sales.orders --since 2026-11-11T09:00:00Z --fail-on needs_human
116
116
  ```
117
117
 
118
- Keys come from `bricksentry.yml`, `--key`, or the table's `PRIMARY KEY` constraint. OPTIMIZE and VACUUM commits are skipped because they don't change data.
118
+ Keys come from `bricksentry.yml`, `--key`, or the table's `PRIMARY KEY` constraint. OPTIMIZE and VACUUM commits are skipped because they don't change data. If data changes landed after the version you check, the output warns you right above the `RESTORE`, because restoring would undo them too. Acting on an alert later? Run `check-last-change --version N` again first: it lists anything written since.
119
119
 
120
120
  ### Every feature on an HR pipeline
121
121
 
@@ -22,7 +22,7 @@ Built by Brahmareddy, Databricks Champion. Open source under Apache-2.0.
22
22
  uvx --from "bricksentry[duckdb]" bricksentry demo
23
23
  ```
24
24
 
25
- (Or `pip install "bricksentry[duckdb]"` and then `bricksentry demo`.) No Databricks account and nothing leaves your machine: it runs on a 20,000-row revenue table in local DuckDB. An AI agent previews a DELETE on a clone (production untouched), gets its pull request **blocked** for a join that duplicates 40 orders, fixes it, and is routed to the owners of a certified table downstream. Then a nightly pipeline commits a bad MERGE anyway: bricksentry finds it in the table history, skips the OPTIMIZE after it, **blocks** it for 25 duplicate keys, prints the `RESTORE` and applies it.
25
+ (Or `pip install "bricksentry[duckdb]"` and then `bricksentry demo`. In a Databricks or Jupyter notebook, run `%pip install "bricksentry[duckdb]"` in one cell, then `from bricksentry.demo import run_demo; run_demo()` in the next; on Databricks, add `dbutils.library.restartPython()` after the install.) No Databricks account and nothing leaves your machine: it runs on a 20,000-row revenue table in local DuckDB. An AI agent previews a DELETE on a clone (production untouched), gets its pull request **blocked** for a join that duplicates 40 orders, fixes it, and is routed to the owners of a certified table downstream. Then a nightly pipeline commits a bad MERGE anyway: bricksentry finds it in the table history, skips the OPTIMIZE after it, **blocks** it for 25 duplicate keys, prints the `RESTORE` and applies it.
26
26
 
27
27
  ![bricksentry demo: an agent's change is previewed, blocked, fixed and routed to the owners; then a bad pipeline commit is caught from table history and undone](https://raw.githubusercontent.com/bricksentry/bricksentry/main/docs/images/demo.png)
28
28
 
@@ -68,7 +68,7 @@ bricksentry check-last-change main.sales.orders --version 42 # a specific ver
68
68
  bricksentry check-last-change main.sales.orders --since 2026-11-11T09:00:00Z --fail-on needs_human
69
69
  ```
70
70
 
71
- Keys come from `bricksentry.yml`, `--key`, or the table's `PRIMARY KEY` constraint. OPTIMIZE and VACUUM commits are skipped because they don't change data.
71
+ Keys come from `bricksentry.yml`, `--key`, or the table's `PRIMARY KEY` constraint. OPTIMIZE and VACUUM commits are skipped because they don't change data. If data changes landed after the version you check, the output warns you right above the `RESTORE`, because restoring would undo them too. Acting on an alert later? Run `check-last-change --version N` again first: it lists anything written since.
72
72
 
73
73
  ### Every feature on an HR pipeline
74
74
 
@@ -0,0 +1 @@
1
+ bricksentry[databricks,mcp]==0.1.20
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.18"
7
+ version = "0.1.20"
8
8
  description = "Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import html
11
11
  import io
12
+ import os
12
13
  import re
13
14
  import sys
14
15
  from contextlib import redirect_stdout
@@ -25,6 +26,7 @@ BASIC = {30: "#1e293b", 31: "#e5484d", 32: "#22c55e", 33: "#e5a93b", 34: "#60a5f
25
26
  def capture() -> str:
26
27
  import click
27
28
 
29
+ os.environ["COLORTERM"] = "truecolor" # keep the website's exact verdict colors in the image
28
30
  from bricksentry.demo import run_demo
29
31
 
30
32
  buf = io.StringIO()
@@ -8,12 +8,12 @@
8
8
  "source": "github"
9
9
  },
10
10
  "websiteUrl": "https://bricksentry.org",
11
- "version": "0.1.18",
11
+ "version": "0.1.20",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "pypi",
15
15
  "identifier": "bricksentry-mcp",
16
- "version": "0.1.18",
16
+ "version": "0.1.20",
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.18"
26
+ __version__ = "0.1.20"
@@ -248,6 +248,8 @@ def check_last_change(table, keys, version, since, sample_pct, allow_no_change,
248
248
  click.echo(f"- {t.summary}")
249
249
  for h in t.hits:
250
250
  click.echo(f" [{h.verdict.value}] {h.rule}: {h.reason}")
251
+ if t.rollback_warning:
252
+ click.echo(click.style("Warning before you undo: ", fg="yellow", bold=True) + t.rollback_warning)
251
253
  click.echo(f"Undo: {t.rollback}")
252
254
  if a.notify:
253
255
  click.echo(f"Notify: {', '.join(a.notify)}")
@@ -10,6 +10,7 @@ versions itself; on Databricks the same check reads Delta history.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
+ import os
13
14
  from pathlib import Path
14
15
  from typing import Any
15
16
 
@@ -78,7 +79,17 @@ SELECT order_id, region, round(amount * 1.05, 2), status FROM sales.orders WHERE
78
79
  """
79
80
 
80
81
  # Same verdict colors as the website: pass green, warn amber, needs_human orange, block red.
81
- _COLORS: dict[str, Any] = {"pass": (29, 160, 100), "warn": (214, 160, 40), "needs_human": (235, 115, 40), "block": (210, 40, 50)}
82
+ _RGB_COLORS: dict[str, Any] = {"pass": (29, 160, 100), "warn": (214, 160, 40), "needs_human": (235, 115, 40), "block": (210, 40, 50)}
83
+ # Terminals without 24-bit color (macOS Terminal.app) misread RGB codes, e.g. as a black
84
+ # background, so they get the standard named colors instead.
85
+ _NAMED_COLORS: dict[str, Any] = {"pass": "green", "warn": "yellow", "needs_human": "bright_yellow", "block": "red"}
86
+
87
+
88
+ def _truecolor() -> bool:
89
+ return os.environ.get("COLORTERM", "").lower() in ("truecolor", "24bit")
90
+
91
+
92
+ _COLORS: dict[str, Any] = _RGB_COLORS if _truecolor() else _NAMED_COLORS
82
93
 
83
94
 
84
95
  def _verdict(v: str) -> str:
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import re
12
12
  import uuid
13
- from dataclasses import dataclass
13
+ from dataclasses import dataclass, field
14
14
  from datetime import datetime, timezone
15
15
  from typing import TYPE_CHECKING, Any
16
16
 
@@ -42,6 +42,8 @@ class Change:
42
42
  operation: str
43
43
  timestamp: str
44
44
  versions: list[int] # every data-changing version folded into this check
45
+ # Data changes committed after ``version``: restoring to ``base_version`` undoes them too.
46
+ newer: list[dict[str, Any]] = field(default_factory=list)
45
47
 
46
48
  def to_dict(self) -> dict[str, Any]:
47
49
  return {
@@ -51,6 +53,7 @@ class Change:
51
53
  "operation": self.operation,
52
54
  "timestamp": self.timestamp,
53
55
  "versions": self.versions,
56
+ "newer_changes": self.newer,
54
57
  }
55
58
 
56
59
 
@@ -58,6 +61,33 @@ def is_data_op(operation: Any) -> bool:
58
61
  return str(operation or "").strip().upper() in DATA_OPS
59
62
 
60
63
 
64
+ def newer_data_changes(history: list[dict[str, Any]], version: int) -> list[dict[str, Any]]:
65
+ """Data changes committed after ``version``, oldest first (OPTIMIZE, VACUUM ... left out)."""
66
+ out = []
67
+ for h in history:
68
+ v = h.get("version")
69
+ if v is None or int(v) <= version or not is_data_op(h.get("operation")):
70
+ continue
71
+ out.append({"version": int(v), "operation": str(h.get("operation")), "timestamp": str(h.get("timestamp") or "")})
72
+ return sorted(out, key=lambda h: h["version"])
73
+
74
+
75
+ def rollback_warning(change: Change, max_listed: int = 3) -> str | None:
76
+ """The warning to show next to the RESTORE when newer data changes exist, else None."""
77
+ if not change.newer:
78
+ return None
79
+ listed = ", ".join(
80
+ f"v{h['version']} ({h['operation']}{', ' + h['timestamp'] if h['timestamp'] else ''})"
81
+ for h in change.newer[-max_listed:][::-1])
82
+ more = len(change.newer) - max_listed
83
+ if more > 0:
84
+ listed += f" and {more} more"
85
+ n = len(change.newer)
86
+ return (f"Newer data changes exist: {listed}. Restoring to v{change.base_version} also undoes "
87
+ f"{'it' if n == 1 else 'them'}. Re-run {'that write' if n == 1 else 'those writes'} after "
88
+ "restoring, or fix forward instead.")
89
+
90
+
61
91
  def _ts(value: Any) -> datetime | None:
62
92
  if value is None or value == "":
63
93
  return None
@@ -129,6 +159,24 @@ def _scratch_name(schema: str, table: str, version: int, run: str) -> str:
129
159
  return f"{schema}.bs_check_{short}_v{version}_{run}"
130
160
 
131
161
 
162
+ def _missing_catalog(e: Exception) -> bool:
163
+ m = str(e).upper()
164
+ return any(k in m for k in ("NO_SUCH_CATALOG", "CATALOG_NOT_FOUND", "CATALOG DOES NOT EXIST"))
165
+
166
+
167
+ def _ensure_scratch(db: Any, schema: str) -> None:
168
+ try:
169
+ db.ensure_schema(schema)
170
+ except Exception as e:
171
+ if _missing_catalog(e):
172
+ where = f"catalog {schema.split('.')[0]!r}" if "." in schema else "the default catalog"
173
+ raise RuntimeError(
174
+ f"The scratch schema {schema} is in {where}, which doesn't exist in this "
175
+ "workspace or you can't use it. Set the scratch schema (sandbox_schema, or --scratch-schema in a "
176
+ "job) to catalog.schema in a catalog you can create tables in.") from None
177
+ raise
178
+
179
+
132
180
  def check_change(
133
181
  sentry: Sentry,
134
182
  table: str,
@@ -147,7 +195,8 @@ def check_change(
147
195
  if not _NAME.fullmatch(table):
148
196
  raise ValueError(f"table must be schema.table or catalog.schema.table; got {table!r}")
149
197
 
150
- change = pick_change(table, db.history(table, history_limit), version=version, since=since)
198
+ history = db.history(table, history_limit)
199
+ change = pick_change(table, history, version=version, since=since)
151
200
  keys = keys or sentry.config.spec(table).keys or db.primary_key(table)
152
201
  if not keys:
153
202
  raise ValueError(
@@ -160,7 +209,7 @@ def check_change(
160
209
  run = uuid.uuid4().hex[:8]
161
210
  base = _scratch_name(scratch, table, change.base_version, run)
162
211
  cand = _scratch_name(scratch, table, change.version, run)
163
- db.ensure_schema(scratch)
212
+ _ensure_scratch(db, scratch)
164
213
  try:
165
214
  for target, v in ((base, change.base_version), (cand, change.version)):
166
215
  try:
@@ -179,9 +228,18 @@ def check_change(
179
228
  pass
180
229
 
181
230
  # The change already happened, so undoing it means going back to the version before it.
231
+ # That also undoes anything written after it, so read the history again (writes may have
232
+ # landed while the check ran) and warn about newer data changes next to the RESTORE.
233
+ try:
234
+ latest = db.history(table, history_limit)
235
+ except Exception: # pragma: no cover - keep the first read if a second one fails
236
+ latest = history
237
+ change.newer = newer_data_changes(latest, change.version)
238
+ warning = rollback_warning(change)
182
239
  undo = f"RESTORE TABLE {db.qualified(table)} TO VERSION AS OF {change.base_version}"
183
240
  for t in a.tables:
184
241
  t.rollback = undo
242
+ t.rollback_warning = warning
185
243
  t.summary = f"v{change.base_version} -> v{change.version} ({change.operation}): {t.summary}"
186
244
  sentry._save(a)
187
245
  return a, change
@@ -166,6 +166,8 @@ def run(argv: list[str] | None = None, backend: Any = None, out=print) -> int:
166
166
  out(f" {t.summary}")
167
167
  for h in t.hits:
168
168
  out(f" [{h.verdict.value}] {h.rule}: {h.reason}")
169
+ if t.rollback_warning:
170
+ out(f" WARNING before you undo: {t.rollback_warning}")
169
171
  out(f" Undo: {t.rollback}")
170
172
  for line in s.notify(a):
171
173
  out(f" notify {line}")
@@ -52,8 +52,13 @@ def run(argv: list[str] | None = None, backend: Any = None, out=print) -> int:
52
52
  from bricksentry.backends.databricks_backend import DatabricksBackend
53
53
 
54
54
  backend = DatabricksBackend(warehouse_id=args.warehouse_id)
55
+ from bricksentry.history import _ensure_scratch
56
+
55
57
  t = backend.qualified(args.table)
56
- backend.ensure_schema(".".join(args.table.split(".")[:2]))
58
+ try:
59
+ _ensure_scratch(backend, ".".join(args.table.split(".")[:2]))
60
+ except RuntimeError as e:
61
+ raise SystemExit(str(e)) from None
57
62
  backend.execute(SEED_SQL.format(t=t))
58
63
  out(f"Created {args.table}: 20,000 orders, one row per order_id.")
59
64
  backend.execute(BAD_MERGE_SQL.format(t=t))
@@ -215,6 +215,7 @@ class TableAssessment:
215
215
  changed_columns: list[str] = field(default_factory=list)
216
216
  column_tags: dict[str, dict[str, str]] = field(default_factory=dict) # tags on this table's changed columns
217
217
  column_downstream: list[ColumnImpact] = field(default_factory=list)
218
+ rollback_warning: str | None = None # e.g. newer data changes that the RESTORE would also undo
218
219
 
219
220
  def to_dict(self) -> dict[str, Any]:
220
221
  return {
@@ -231,6 +232,7 @@ class TableAssessment:
231
232
  "column_tags": self.column_tags,
232
233
  "column_downstream": [c.to_dict() for c in self.column_downstream],
233
234
  "rollback": self.rollback,
235
+ "rollback_warning": self.rollback_warning,
234
236
  }
235
237
 
236
238
  @classmethod
@@ -248,6 +250,7 @@ class TableAssessment:
248
250
  changed_columns=list(d.get("changed_columns") or []),
249
251
  column_tags={k: dict(v) for k, v in (d.get("column_tags") or {}).items()},
250
252
  column_downstream=[ColumnImpact(**c) for c in d.get("column_downstream") or []],
253
+ rollback_warning=d.get("rollback_warning"),
251
254
  )
252
255
 
253
256
 
@@ -192,6 +192,9 @@ def slack_payload(
192
192
  lines.append(f"`{h.verdict.value}` *{_slack_escape(h.rule)}* on {_slack_escape(h.table)}: {_slack_escape(_clip(h.reason))}")
193
193
  if len(a.hits) > max_reasons:
194
194
  lines.append(f"_…and {len(a.hits) - max_reasons} more_")
195
+ for t in a.tables:
196
+ if t.rollback_warning:
197
+ lines.append(f":warning: *Before you restore {_slack_escape(t.table)}:* {_slack_escape(t.rollback_warning)}")
195
198
  if a.notify:
196
199
  lines.append("*Review requested from:* " + ", ".join(_slack_mention(o, mentions) for o in a.notify))
197
200
  link = run_link(pr, run_url)
@@ -235,6 +238,9 @@ def teams_payload(
235
238
  body.append(_plain(f"[{h.verdict.value}] {h.rule} on {h.table}: {_clip(h.reason)}"))
236
239
  if len(a.hits) > max_reasons:
237
240
  body.append(_plain(f"…and {len(a.hits) - max_reasons} more"))
241
+ for t in a.tables:
242
+ if t.rollback_warning:
243
+ body.append(_plain(f"Before you restore {t.table}: {t.rollback_warning}"))
238
244
  if a.notify:
239
245
  body.append(_plain(f"Review requested from: {', '.join(a.notify)}"))
240
246
  body.append({"type": "RichTextBlock", "spacing": "Medium", "inlines": [
@@ -93,6 +93,8 @@ def _table_section(t: TableAssessment, max_downstream: int) -> list[str]:
93
93
  out.append(f"| … | {len(t.column_downstream) - max_downstream} more | | |")
94
94
  out += ["", "</details>", ""]
95
95
  if t.rollback and t.rollback.startswith("RESTORE"):
96
+ if t.rollback_warning:
97
+ out += [f"> :warning: **Before you restore:** {t.rollback_warning}", ""]
96
98
  out += ["**Rollback:**", "```sql", t.rollback, "```", ""]
97
99
  elif t.rollback:
98
100
  out += [f"**Rollback:** {t.rollback}", ""]
@@ -0,0 +1,31 @@
1
+ # Databricks Asset Bundle: check every pipeline run
2
+
3
+ ```bash
4
+ databricks bundle init https://github.com/bricksentry/bricksentry --template-dir templates/job-check
5
+ cd bricksentry_check && databricks bundle deploy
6
+ ```
7
+
8
+ You're asked for the tables to watch, a SQL warehouse ID, a scratch schema, the policy and
9
+ (optionally) a Slack webhook secret. The bundle deploys a serverless job with a table update
10
+ trigger: when a watched table changes, the job checks the change (`bricksentry.job`, which uses
11
+ `bricksentry check-last-change`), alerts, and prints the `RESTORE` that undoes it. The generated
12
+ README shows how to put the same check inside your own pipeline job so a `block` stops the
13
+ tasks downstream.
14
+
15
+ ## Without prompts (CI, scripts, AI agents)
16
+
17
+ `bundle init` asks its questions interactively. To answer them from a file instead:
18
+
19
+ ```bash
20
+ cat > bricksentry-init.json <<'JSON'
21
+ {"project_name": "bricksentry_check", "demo": "yes", "tables": "",
22
+ "warehouse_id": "<your SQL warehouse ID>"}
23
+ JSON
24
+ databricks bundle init https://github.com/bricksentry/bricksentry --template-dir templates/job-check \
25
+ --config-file bricksentry-init.json
26
+ ```
27
+
28
+ Every other input has a default. `scratch_schema` defaults to `<your default catalog>.bricksentry_scratch`;
29
+ set it if you want the scratch tables elsewhere. The full list with descriptions is in
30
+ [`databricks_template_schema.json`](databricks_template_schema.json). Leave `tables` empty to
31
+ deploy only the demo job.
@@ -9,44 +9,45 @@
9
9
  "pattern_match_failure_message": "Use letters, digits and underscores only.",
10
10
  "order": 1
11
11
  },
12
- "tables": {
12
+ "demo": {
13
13
  "type": "string",
14
- "description": "Tables to watch, comma-separated catalog.schema.table names (up to 10)",
15
- "pattern": "^[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+(\\s*,\\s*[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+){0,9}$",
16
- "pattern_match_failure_message": "Enter 1 to 10 full names like main.sales.orders, separated by commas.",
14
+ "default": "yes",
15
+ "enum": [
16
+ "yes",
17
+ "no"
18
+ ],
19
+ "description": "Add a demo job that makes a known-bad change to a demo table in your scratch schema, so your first run shows a block (recommended)",
17
20
  "order": 2
18
21
  },
22
+ "tables": {
23
+ "type": "string",
24
+ "description": "Tables to watch, comma-separated catalog.schema.table names (up to 10). Leave empty to try only the demo first; you can add tables later",
25
+ "pattern": "^([A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+(\\s*,\\s*[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+){0,9})?$",
26
+ "pattern_match_failure_message": "Enter 1 to 10 full names like main.sales.orders, separated by commas, or leave empty.",
27
+ "order": 3,
28
+ "default": ""
29
+ },
19
30
  "keys": {
20
31
  "type": "string",
21
32
  "default": "",
22
33
  "description": "Key columns for tables without a PRIMARY KEY: table=col1,col2 separated by ';' (e.g. main.sales.orders=order_id). Leave empty to use each table's PRIMARY KEY",
23
34
  "pattern": "^(\\s*[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\s*=\\s*[A-Za-z0-9_]+(\\s*,\\s*[A-Za-z0-9_]+)*\\s*(;|$))*$",
24
35
  "pattern_match_failure_message": "Use catalog.schema.table=col1,col2; separate tables with ';'. Or leave empty.",
25
- "order": 3
36
+ "order": 4
26
37
  },
27
38
  "warehouse_id": {
28
39
  "type": "string",
29
40
  "description": "SQL warehouse ID (SQL Warehouses -> your warehouse -> Connection details)",
30
41
  "pattern": "^[A-Za-z0-9]+$",
31
42
  "pattern_match_failure_message": "Paste the warehouse ID only, e.g. 1a2b3c4d5e6f7a8b.",
32
- "order": 4
43
+ "order": 5
33
44
  },
34
45
  "scratch_schema": {
35
46
  "type": "string",
36
- "default": "main.bricksentry_scratch",
37
- "description": "catalog.schema for the temporary shallow clones (created if missing; clones are dropped after each check)",
47
+ "default": "{{if eq (default_catalog) \"\"}}main{{else}}{{default_catalog}}{{end}}.bricksentry_scratch",
48
+ "description": "catalog.schema for the temporary shallow clones and the demo table (created if missing). Defaults to your workspace's default catalog",
38
49
  "pattern": "^[A-Za-z0-9_]+\\.[A-Za-z0-9_]+$",
39
50
  "pattern_match_failure_message": "Use catalog.schema.",
40
- "order": 5
41
- },
42
- "demo": {
43
- "type": "string",
44
- "default": "yes",
45
- "enum": [
46
- "yes",
47
- "no"
48
- ],
49
- "description": "Add a demo job that makes a known-bad change to a demo table in the scratch schema, so your first run shows a block (recommended)",
50
51
  "order": 6
51
52
  },
52
53
  "policy": {
@@ -85,12 +86,12 @@
85
86
  },
86
87
  "bricksentry_version": {
87
88
  "type": "string",
88
- "default": "0.1.18",
89
+ "default": "0.1.20",
89
90
  "description": "bricksentry version to install in the job (pinned; change it and redeploy to upgrade)",
90
91
  "pattern": "^\\d+\\.\\d+\\.\\d+$",
91
- "pattern_match_failure_message": "Use a version like 0.1.18.",
92
+ "pattern_match_failure_message": "Use a version like 0.1.20.",
92
93
  "order": 10
93
94
  }
94
95
  },
95
- "success_message": "\nCreated {{.project_name}}. Next:\n cd {{.project_name}}\n databricks bundle deploy\n{{if eq .demo \"yes\"}} databricks bundle run bricksentry_demo # about 2 minutes; ends red with BLOCK, which is the point\n{{end}}Then any change to the watched tables is checked automatically. See {{.project_name}}/README.md."
96
+ "success_message": "\nCreated {{.project_name}}. Next:\n cd {{.project_name}}\n databricks bundle deploy\n{{if eq .demo \"yes\"}} databricks bundle run bricksentry_demo # about 2 minutes; ends red with BLOCK, which is the point\n{{end}}{{if .tables}}Then any change to the watched tables is checked automatically. {{else}}To check your own tables, add them to resources/bricksentry_check.job.yml (see README.md). {{end}}See {{.project_name}}/README.md."
96
97
  }
@@ -1,10 +1,13 @@
1
1
  # {{.project_name}}: bricksentry checks for your tables
2
2
 
3
- This bundle deploys one serverless job, **bricksentry check ({{.project_name}})**. When any of
3
+ {{if .tables}}This bundle deploys a serverless job, **bricksentry check ({{.project_name}})**. When any of
4
4
  these tables changes, it runs and checks what changed:
5
5
 
6
6
  {{.tables}}
7
-
7
+ {{else}}This bundle has no tables to watch yet{{if eq .demo "yes"}}, only the demo job{{end}}. To check your own tables, re-run
8
+ `databricks bundle init` with them, or copy the `bricksentry_check` job from the bricksentry
9
+ template README (https://github.com/bricksentry/bricksentry/tree/main/templates/job-check).
10
+ {{end}}
8
11
  For each table it compares the version before the change with the version after it (two
9
12
  shallow clones in `{{.scratch_schema}}`, dropped after the check; your tables are only read).
10
13
  It reports rows added, removed and changed, duplicate or NULL keys, schema changes and totals
@@ -3,6 +3,7 @@
3
3
  # start a run; they have no data change, so the run just finishes ("nothing to check").
4
4
  resources:
5
5
  jobs:
6
+ {{- if .tables}}
6
7
  bricksentry_check:
7
8
  name: bricksentry check ({{.project_name}})
8
9
  max_concurrent_runs: 1
@@ -57,6 +58,7 @@ resources:
57
58
  # Pinned: serverless resolves the dependencies once and caches them, so a range
58
59
  # would not pick up new releases. To upgrade, change the version and redeploy.
59
60
  - bricksentry[databricks]=={{.bricksentry_version}}
61
+ {{- end}}
60
62
  {{- if eq .demo "yes"}}
61
63
 
62
64
  # Demo: makes a known-bad change to a demo table in {{.scratch_schema}}, then checks it.
@@ -306,7 +306,7 @@ def _render(text: str, values: dict) -> str:
306
306
  """Render the subset of Go templates the bundle uses: {{.x}}, {{`raw`}}, nested
307
307
  {{if .x}} / {{if eq .x "y"}} ... {{end}}, with optional {{- trimming."""
308
308
  text = re.sub(r"\{\{`(.*?)`\}\}", lambda m: m.group(1).replace("{{", "\x00").replace("}}", "\x01"), text)
309
- tok = re.compile(r"(\s*)\{\{(-?) ?(if (?:eq )?\.\w+(?: \"[^\"]*\")?|end)\}\}")
309
+ tok = re.compile(r"(\s*)\{\{(-?) ?(if (?:eq )?\.\w+(?: \"[^\"]*\")?|else|end)\}\}")
310
310
 
311
311
  def cond(expr: str) -> bool:
312
312
  m = re.fullmatch(r"if (eq )?\.(\w+)(?: \"([^\"]*)\")?", expr)
@@ -321,6 +321,8 @@ def _render(text: str, values: dict) -> str:
321
321
  expr = m.group(3)
322
322
  if expr == "end":
323
323
  stack.pop()
324
+ elif expr == "else":
325
+ stack[-1] = not stack[-1]
324
326
  else:
325
327
  stack.append(cond(expr))
326
328
  pos = m.end()
@@ -332,18 +334,28 @@ def _render(text: str, values: dict) -> str:
332
334
  return text.replace("\x00", "{{").replace("\x01", "}}")
333
335
 
334
336
 
335
- @pytest.mark.parametrize("slack,keys,demo", [("bricksentry/slack_webhook", "main.sales.orders=order_id", "yes"),
336
- ("", "", "no"), ("", "", "yes")])
337
- def test_bundle_template_renders(slack, keys, demo):
337
+ TABLES = "main.sales.orders, main.sales.customers"
338
+
339
+
340
+ @pytest.mark.parametrize("slack,keys,demo,tables", [
341
+ ("bricksentry/slack_webhook", "main.sales.orders=order_id", "yes", TABLES),
342
+ ("", "", "no", TABLES), ("", "", "yes", TABLES), ("", "", "yes", ""),
343
+ ])
344
+ def test_bundle_template_renders(slack, keys, demo, tables):
338
345
  from pathlib import Path
339
346
 
340
347
  import yaml
341
348
 
342
349
  root = Path(__file__).resolve().parents[1] / "templates" / "job-check"
343
350
  schema = json.loads((root / "databricks_template_schema.json").read_text())
351
+ # Databricks evaluates templated defaults at init; {{default_catalog}} is the workspace default
352
+ dc = 'if eq (default_catalog) ""}}main{{else}}{{default_catalog}}{{end}}'
353
+ assert schema["properties"]["scratch_schema"]["default"] == "{{" + dc + ".bricksentry_scratch"
344
354
  values = {k: p.get("default", "") for k, p in schema["properties"].items()}
355
+ values["scratch_schema"] = "main.bricksentry_scratch"
345
356
  assert values["bricksentry_version"] == __import__("bricksentry").__version__
346
- values.update(tables="main.sales.orders, main.sales.customers", warehouse_id="abc123", slack_secret=slack,
357
+ assert [k for k, p in schema["properties"].items() if "default" not in p] == ["warehouse_id"]
358
+ values.update(tables=tables, warehouse_id="abc123", slack_secret=slack,
347
359
  keys=keys, demo=demo)
348
360
  for k, p in schema["properties"].items():
349
361
  if "pattern" in p:
@@ -352,22 +364,25 @@ def test_bundle_template_renders(slack, keys, demo):
352
364
  bundle = yaml.safe_load(_render((proj / "databricks.yml.tmpl").read_text(), values))
353
365
  assert bundle["bundle"]["name"] == "bricksentry_check"
354
366
  job_yml = yaml.safe_load(_render((proj / "resources" / "bricksentry_check.job.yml.tmpl").read_text(), values))
355
- j = job_yml["resources"]["jobs"]["bricksentry_check"]
356
- assert j["trigger"]["table_update"]["table_names"] == ["main.sales.orders", "main.sales.customers"]
357
- task = j["tasks"][0]
358
- params = task["spark_python_task"]["parameters"]
359
- assert params[:2] == ["--tables", "{{job.trigger.table_update.updated_tables}}"]
360
- assert "{{workspace.url}}/jobs/{{job.id}}/runs/{{job.run_id}}" in params
361
- assert ("--slack-secret" in params) == bool(slack)
362
- assert ("--keys" in params) == bool(keys)
363
- assert task["max_retries"] == 0 and task["disable_auto_optimization"] is True
364
- assert j["environments"][0]["spec"]["dependencies"] == [f"bricksentry[databricks]=={values['bricksentry_version']}"]
365
- assert task["environment_key"] == j["environments"][0]["environment_key"]
366
- assert j["environments"][0]["spec"]["dependencies"][0].startswith("bricksentry[databricks]")
367
- # the job task's argv parses, and an unresolved trigger value falls back to --default-tables
368
- args = job.build_parser().parse_args(params)
369
- assert args.fail_on == "block" and args.since_minutes == 60
370
367
  jobs = job_yml["resources"]["jobs"]
368
+ assert ("bricksentry_check" in jobs) == bool(tables)
369
+ j = jobs.get("bricksentry_check")
370
+ if j:
371
+ assert j["trigger"]["table_update"]["table_names"] == ["main.sales.orders", "main.sales.customers"]
372
+ task = j["tasks"][0]
373
+ params = task["spark_python_task"]["parameters"]
374
+ assert params[:2] == ["--tables", "{{job.trigger.table_update.updated_tables}}"]
375
+ assert "{{workspace.url}}/jobs/{{job.id}}/runs/{{job.run_id}}" in params
376
+ assert ("--slack-secret" in params) == bool(slack)
377
+ assert ("--keys" in params) == bool(keys)
378
+ assert task["max_retries"] == 0 and task["disable_auto_optimization"] is True
379
+ assert j["environments"][0]["spec"]["dependencies"] == [f"bricksentry[databricks]=={values['bricksentry_version']}"]
380
+ assert task["environment_key"] == j["environments"][0]["environment_key"]
381
+ assert j["environments"][0]["spec"]["dependencies"][0].startswith("bricksentry[databricks]")
382
+ # the job task's argv parses, and an unresolved trigger value falls back to --default-tables
383
+ args = job.build_parser().parse_args(params)
384
+ assert args.fail_on == "block" and args.since_minutes == 60
385
+
371
386
  assert ("bricksentry_demo" in jobs) == (demo == "yes")
372
387
  if demo == "yes":
373
388
  dj = jobs["bricksentry_demo"]
@@ -379,11 +394,14 @@ def test_bundle_template_renders(slack, keys, demo):
379
394
  assert dargs.since is None and dargs.since_minutes is None and dargs.fail_on == "block"
380
395
  assert (dargs.slack_secret is not None) == bool(slack)
381
396
  assert all(t["max_retries"] == 0 and t["disable_auto_optimization"] for t in dj["tasks"])
382
- assert dj["environments"] == j["environments"]
397
+ assert dj["environments"][0]["spec"]["dependencies"] == [
398
+ f"bricksentry[databricks]=={values['bricksentry_version']}"]
383
399
  msg = _render(schema["success_message"], values)
384
400
  assert ("bundle run bricksentry_demo" in msg) == (demo == "yes")
385
401
  readme = _render((proj / "README.md.tmpl").read_text(), values)
386
402
  assert ("See a block first" in readme) == (demo == "yes")
403
+ assert ("no tables to watch yet" in readme) == (not tables)
404
+ assert ("Then any change" in msg) == bool(tables)
387
405
  assert "{{job.start_time.iso_datetime}}" in readme
388
406
  assert (proj / "src" / "bricksentry_check.py").exists()
389
407
 
@@ -475,3 +493,25 @@ def test_job_demo_change_is_blocked_end_to_end():
475
493
  text = "\n".join(lines)
476
494
  assert code == 1 and "BLOCK" in text and "duplicate-keys: 25" in text
477
495
  assert 'TO VERSION AS OF 1' in text
496
+
497
+
498
+ def test_missing_scratch_catalog_message():
499
+ from bricksentry import job_demo
500
+
501
+ class NoCatalog(FakeDelta):
502
+ def ensure_schema(self, schema):
503
+ raise RuntimeError("[NO_SUCH_CATALOG_EXCEPTION] Catalog 'main' was not found. SQLSTATE: 42704")
504
+
505
+ with pytest.raises(RuntimeError, match="scratch is in the default catalog, which doesn't exist"):
506
+ sentry(NoCatalog()).check_change("sales.orders")
507
+ b = RecordingBackend()
508
+ b.ensure_schema = NoCatalog.ensure_schema.__get__(b)
509
+ with pytest.raises(SystemExit, match="Set the scratch schema"):
510
+ job_demo.run(["--table", "main.scratch.bricksentry_demo_orders"], backend=b)
511
+
512
+ class Other(FakeDelta):
513
+ def ensure_schema(self, schema):
514
+ raise RuntimeError("PERMISSION_DENIED")
515
+
516
+ with pytest.raises(RuntimeError, match="PERMISSION_DENIED"):
517
+ sentry(Other()).check_change("sales.orders")
@@ -0,0 +1,81 @@
1
+ """0.1.20: warn when newer data changes exist, since the RESTORE would undo them too."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from click.testing import CliRunner
8
+ from test_0114 import HISTORY, FakeDelta, sentry
9
+
10
+ from bricksentry.cli import main
11
+ from bricksentry.history import Change, newer_data_changes, rollback_warning
12
+ from bricksentry.models import TableAssessment
13
+ from bricksentry.notify import slack_payload, teams_payload
14
+ from bricksentry.report import to_markdown
15
+
16
+
17
+ def test_newer_data_changes_skips_maintenance_and_sorts():
18
+ hist = [{"version": 7, "operation": "WRITE", "timestamp": "t7"}, {"version": 6, "operation": "OPTIMIZE"},
19
+ {"version": 5, "operation": "MERGE", "timestamp": "t5"}, {"version": 4, "operation": "WRITE"}]
20
+ assert [h["version"] for h in newer_data_changes(hist, 4)] == [5, 7]
21
+ assert newer_data_changes(hist, 7) == []
22
+
23
+
24
+ def test_warning_text_lists_newest_first_and_caps():
25
+ c = Change("t", 2, 1, "DELETE", "", [2], newer=[{"version": v, "operation": "WRITE", "timestamp": ""}
26
+ for v in range(3, 8)])
27
+ w = rollback_warning(c)
28
+ assert w.startswith("Newer data changes exist: v7 (WRITE), v6 (WRITE), v5 (WRITE) and 2 more.")
29
+ assert "Restoring to v1 also undoes them" in w
30
+ assert rollback_warning(Change("t", 2, 1, "DELETE", "", [2])) is None
31
+
32
+
33
+ def test_latest_change_has_no_warning():
34
+ a, change = sentry().check_change("sales.orders")
35
+ assert change.newer == [] and a.tables[0].rollback_warning is None
36
+ assert "Before you restore" not in to_markdown(a)
37
+
38
+
39
+ def test_older_version_warns_about_newer_change():
40
+ a, change = sentry().check_change("sales.orders", version=2)
41
+ t = a.tables[0]
42
+ assert [h["version"] for h in change.newer] == [3] # the OPTIMIZE at v4 is not a data change
43
+ assert t.rollback == 'RESTORE TABLE "sales"."orders" TO VERSION AS OF 1'
44
+ assert t.rollback_warning.startswith("Newer data changes exist: v3 (MERGE, 2026-11-11 10:00:00).")
45
+ assert "Restoring to v1 also undoes it. Re-run that write" in t.rollback_warning
46
+ md = to_markdown(a)
47
+ assert md.index("Before you restore") < md.index("RESTORE TABLE")
48
+ assert "Before you restore sales.orders" in json.dumps(slack_payload(a))
49
+ assert "Before you restore sales.orders" in json.dumps(teams_payload(a))
50
+ assert TableAssessment.from_dict(t.to_dict()).rollback_warning == t.rollback_warning
51
+
52
+
53
+ def test_write_landing_during_the_check_is_caught():
54
+ class Busy(FakeDelta):
55
+ reads = 0
56
+
57
+ def history(self, table, limit=50):
58
+ self.reads += 1
59
+ if self.reads == 1:
60
+ return HISTORY
61
+ return [{"version": 5, "timestamp": "2026-11-11 10:10:00", "operation": "WRITE"}, *HISTORY]
62
+
63
+ a, change = sentry(Busy()).check_change("sales.orders")
64
+ assert change.version == 3 and [h["version"] for h in change.newer] == [5]
65
+ assert "v5 (WRITE" in a.tables[0].rollback_warning
66
+
67
+
68
+ def test_cli_text_and_json(monkeypatch, tmp_path):
69
+ db = FakeDelta()
70
+ monkeypatch.setattr("bricksentry.assess.make_backend", lambda spec: db)
71
+ cfg = tmp_path / "bricksentry.yml"
72
+ cfg.write_text("sandbox_schema: scratch\nassessment_store: false\nlineage: {type: static}\n")
73
+ r = CliRunner().invoke(main, ["check-last-change", "sales.orders", "-c", str(cfg), "--no-notify",
74
+ "--version", "2"])
75
+ assert r.exit_code in (0, 1), r.output
76
+ assert r.output.index("Warning before you undo: Newer data changes exist: v3") < r.output.index("Undo: RESTORE")
77
+ r = CliRunner().invoke(main, ["check-last-change", "sales.orders", "-c", str(cfg), "--no-notify",
78
+ "--version", "2", "--format", "json"])
79
+ d = json.loads(r.output)
80
+ assert d["change"]["newer_changes"][0]["version"] == 3
81
+ assert d["tables"][0]["rollback_warning"].startswith("Newer data changes exist")
@@ -1 +0,0 @@
1
- bricksentry[databricks,mcp]==0.1.18
@@ -1,13 +0,0 @@
1
- # Databricks Asset Bundle: check every pipeline run
2
-
3
- ```bash
4
- databricks bundle init https://github.com/bricksentry/bricksentry --template-dir templates/job-check
5
- cd bricksentry_check && databricks bundle deploy
6
- ```
7
-
8
- You're asked for the tables to watch, a SQL warehouse ID, a scratch schema, the policy and
9
- (optionally) a Slack webhook secret. The bundle deploys a serverless job with a table update
10
- trigger: when a watched table changes, the job checks the change (`bricksentry.job`, which uses
11
- `bricksentry check-last-change`), alerts, and prints the `RESTORE` that undoes it. The generated
12
- README shows how to put the same check inside your own pipeline job so a `block` stops the
13
- tasks downstream.
File without changes
File without changes
File without changes
File without changes