Skip to content

Commit 136f025

Browse files
authored
Merge branch 'main' into docs/default-connection-fallback
2 parents c27ce15 + 7975a8d commit 136f025

53 files changed

Lines changed: 4278 additions & 559 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/dependabot.yml‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,30 @@ updates:
44
directory: '/'
55
schedule:
66
interval: 'weekly'
7+
groups:
8+
# Storybook add-ons declare a peer dependency on the matching `storybook`
9+
# release, so they have to move together. Bump them in a single PR.
10+
storybook:
11+
patterns:
12+
- 'storybook'
13+
- '@storybook/*'
14+
- '@chromatic-com/storybook'
15+
- 'eslint-plugin-storybook'
16+
update-types:
17+
- 'minor'
18+
- 'patch'
19+
ignore:
20+
# A Storybook major upgrade has to be done by hand as one coordinated
21+
# migration (e.g. @storybook/addon-vitest 10 requires vitest 4+), so don't
22+
# open per-package major-bump PRs, which break the Storybook build.
23+
- dependency-name: 'storybook'
24+
update-types: ['version-update:semver-major']
25+
- dependency-name: '@storybook/*'
26+
update-types: ['version-update:semver-major']
27+
- dependency-name: '@chromatic-com/storybook'
28+
update-types: ['version-update:semver-major']
29+
- dependency-name: 'eslint-plugin-storybook'
30+
update-types: ['version-update:semver-major']
731
- package-ecosystem: 'github-actions'
832
directory: '/'
933
schedule:

‎.github/workflows/pr.yaml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,10 @@ jobs:
150150
. ./venv/Scripts/activate
151151
python.exe -m pip install --upgrade pip
152152
make install-dev
153+
- name: Install DuckLake extension
154+
run: |
155+
. ./venv/Scripts/activate
156+
python -c "import duckdb; duckdb.connect().install_extension('ducklake')"
153157
- name: Run fast unit tests
154158
run: |
155159
. ./venv/Scripts/activate
@@ -267,6 +271,7 @@ jobs:
267271
trino,
268272
spark,
269273
clickhouse,
274+
clickhouse-datalake,
270275
risingwave,
271276
starrocks,
272277
]
@@ -293,6 +298,9 @@ jobs:
293298
run: |
294299
source .venv/bin/activate
295300
make ${{ matrix.engine }}-test
301+
- name: Stop DataLake services
302+
if: ${{ always() && matrix.engine == 'clickhouse-datalake' }}
303+
run: make clickhouse-datalake-down
296304
- name: Upload test results
297305
uses: actions/upload-artifact@v7
298306
if: ${{ !cancelled() }}

‎Makefile‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.PHONY: docs
2+
.PHONY: clickhouse-datalake-up clickhouse-datalake-test clickhouse-datalake-down
23

34
ifdef UV
45
PIP := uv pip
@@ -192,6 +193,21 @@ engine-%-up: engine-%-install engine-docker-%-up
192193
engine-%-down:
193194
docker compose -f ./tests/core/engine_adapter/integration/docker/compose.${*}.yaml down -v
194195

196+
CLICKHOUSE_DATALAKE_COMPOSE = docker compose --project-name sqlmesh-clickhouse-datalake -f ./tests/core/engine_adapter/integration/docker/compose.clickhouse-datalake.yaml
197+
198+
clickhouse-datalake-up:
199+
$(CLICKHOUSE_DATALAKE_COMPOSE) up -d --wait --wait-timeout 120 clickhouse minio-init rest
200+
$(CLICKHOUSE_DATALAKE_COMPOSE) run --build --rm seed
201+
202+
clickhouse-datalake-test:
203+
docker info >/dev/null
204+
$(MAKE) engine-clickhouse-install
205+
$(MAKE) clickhouse-datalake-up
206+
SQLMESH_RUN_CLICKHOUSE_DATALAKE=1 pytest -n 0 -m "docker and clickhouse_datalake" tests/core/engine_adapter/integration/test_integration_clickhouse_datalake.py --junitxml=test-results/junit-clickhouse-datalake.xml
207+
208+
clickhouse-datalake-down:
209+
$(CLICKHOUSE_DATALAKE_COMPOSE) down -v --remove-orphans
210+
195211
##################
196212
# Docker Engines #
197213
##################

‎docs/concepts/audits.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ MODEL (
477477
#### valid_uuid, valid_uuid_non_blocking
478478
Ensures that all non-NULL rows of a column contain a string with the UUID structure.
479479

480-
UUID structure determined by matching regular expression `'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`.
480+
UUID structure determined by matching regular expression `'^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`.
481481

482482
This example asserts that all `uuid` values have the UUID structure:
483483

‎docs/integrations/engines/clickhouse.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,57 @@ gateways:
470470

471471
With this configuration, ClickHouse models will appear as `ch_virtual.mydb.mytable` in plan output instead of `__clickhouse__.mydb.mytable`.
472472

473+
### Reading catalog-backed physical tables
474+
475+
When ClickHouse exposes a source catalog through a [`DataLakeCatalog`](https://clickhouse.com/docs/engines/database-engines/datalake), map that source catalog to its ClickHouse database in the connection configuration:
476+
477+
```yaml
478+
gateways:
479+
clickhouse:
480+
connection:
481+
type: clickhouse
482+
host: my-clickhouse-host
483+
username: default
484+
datalake_catalog_mapping:
485+
lake: iceberg
486+
```
487+
488+
SQLMesh renders `lake.analytics.orders` as `iceberg."analytics.orders"`. It combines the source
489+
schema and table into one quoted table name because ClickHouse uses a two-level namespace. The
490+
`iceberg` database must already exist and use the `DataLakeCatalog` engine. SQLMesh does not create
491+
the database or manage its metastore or storage permissions.
492+
493+
For parsed queries that read data without writing the result to a ClickHouse table, SQLMesh rewrites
494+
mapped source catalogs and passes other foreign catalog-qualified references through unchanged.
495+
During rendering, SQLMesh strips the configured virtual catalog prefix, even before injection. For
496+
`INSERT ... SELECT` and other query materializations, SQLMesh rewrites mapped sources and validates
497+
the remaining catalog-qualified sources. With a non-empty mapping, each source catalog must appear
498+
in the mapping. When SQLMesh has injected a virtual catalog, a source can also use that catalog.
499+
SQLMesh raises an error for other catalogs. Without a non-empty mapping or an injected virtual
500+
catalog, SQLMesh does not apply DataLake mapping or catalog validation during materialization.
501+
502+
This mapping rewrites parsed query sources. It does not rewrite table names used for metadata
503+
operations such as `columns()` or `table_exists()`. The `sqlmesh create_external_models` command also
504+
uses the source name as supplied when it fetches column types, so it cannot infer columns for a
505+
source named `lake.analytics.orders` through the mapping. In a ClickHouse-only project, registering
506+
that three-part logical name as an external model can also fail SQLMesh's schema nesting check,
507+
because ClickHouse project models use two-part names.
508+
509+
To register column metadata until mapped names are supported there, use ClickHouse's physical
510+
two-part name in both the external model and the query. For example, use
511+
`iceberg."analytics.orders"` for the table exposed by database `iceberg`. This matches ClickHouse's
512+
`database."schema.table"` name and keeps the model at ClickHouse's two-part nesting level. The
513+
mapping still lets SQLMesh render queries that use mapped logical names. Without registered
514+
column metadata, SQLMesh cannot fully optimize those queries or produce column-level lineage.
515+
516+
An injected virtual catalog takes precedence over a mapping key with the same name. SQLMesh treats
517+
that name as its virtual catalog. Use different names for the virtual catalog and DataLakeCatalog
518+
source catalogs. The mapping applies to query source references. It does not rewrite SQL strings
519+
passed directly to the ClickHouse adapter or map `INSERT` targets.
520+
521+
View creation rejects a source that uses another catalog when a virtual catalog is injected, even
522+
if the mapping includes that source. Mapped-source views work when no virtual catalog is injected.
523+
473524
## Local/Built-in Scheduler
474525

475526
**Engine Adapter Type**: `clickhouse`
@@ -498,3 +549,4 @@ With this configuration, ClickHouse models will appear as `ch_virtual.mydb.mytab
498549
| `connection_settings` | Additional [connection settings](https://clickhouse.com/docs/integrations/python#settings-argument) | dict | N |
499550
| `connection_pool_options` | Additional [options](https://clickhouse.com/docs/integrations/python#customizing-the-http-connection-pool) for the HTTP connection pool | dict | N |
500551
| `virtual_catalog` | Override the virtual catalog name used when ClickHouse runs alongside a catalog-aware gateway (e.g. Trino). Defaults to `__{gateway_name}__`. See [Multi-gateway setup](#multi-gateway-setup) for details. | string | N |
552+
| `datalake_catalog_mapping` | Map source catalogs to ClickHouse DataLakeCatalog databases. See [Reading catalog-backed physical tables](#reading-catalog-backed-physical-tables). | dict | N |
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
# Execution observations
2+
3+
Execution observations expose native SQLMesh work to Python integrations through
4+
an optional callback. They do not replace SQL generation, execution, retries,
5+
transactions, or `Console` progress reporting.
6+
7+
## Console observer registration
8+
9+
`Console.get_execution_observer()` returns `None` by default. A `Console`
10+
subclass can return an `Observer` callback from `sqlmesh.core.execution_observation`.
11+
The callback receives a
12+
phase, a read-only mapping of facts, and the original exception or `None`.
13+
For general Python integration details, see the [Python API reference](./python.md).
14+
15+
The following console prints the kind, action, and finish error for each observed
16+
operation. The example uses `examples/sushi` relative to the SQLMesh repository root:
17+
18+
```python
19+
from typing import Any, Literal, Mapping, Optional
20+
21+
from sqlmesh.core.console import TerminalConsole, set_console
22+
from sqlmesh.core.context import Context
23+
from sqlmesh.core.execution_observation import Observer
24+
25+
26+
def observe(
27+
phase: Literal["start", "finish"],
28+
facts: Mapping[str, Any],
29+
error: Optional[BaseException],
30+
) -> None:
31+
if phase == "finish":
32+
print(f"{facts['kind']}/{facts['action']}: error={error!r}")
33+
34+
35+
class ObservedConsole(TerminalConsole):
36+
def get_execution_observer(self) -> Optional[Observer]:
37+
return observe
38+
39+
40+
set_console(ObservedConsole())
41+
context = Context(paths=["examples/sushi"])
42+
```
43+
44+
A `Context` uses the `Console` that was current when the context was created.
45+
Unless an explicit `observer_scope()` is active, SQLMesh resolves
46+
`get_execution_observer()` once for each outer plan evaluation or scheduler run.
47+
Nested calls reuse that observer. If the getter raises an ordinary `Exception`,
48+
SQLMesh disables observation for that plan evaluation or scheduler run and
49+
continues native work.
50+
51+
## Observer scopes
52+
53+
`observer_scope(observer)` from `sqlmesh.core.execution_observation` sets the
54+
observer for the duration of the scope. A nested scope restores the previously
55+
active observer when it exits. `observer_scope(None)` disables observation inside
56+
that scope, including automatic Console registration.
57+
58+
## Callback lifecycle
59+
60+
SQLMesh calls `start` before observed work with `error=None`. When `start`
61+
returns or raises an ordinary `Exception`, SQLMesh continues the work and calls
62+
`finish` from a `finally` block afterward. The `finish` callback receives the
63+
original workload exception object or `None`. Both callbacks run synchronously
64+
on the thread that performs the observed work. Callbacks for work dispatched to
65+
a worker run on that worker's thread.
66+
67+
Every invocation that reaches `finish` passes the same read-only mapping object
68+
to `start` and `finish`. Distinct invocations use distinct mapping objects.
69+
Consumers can pair the phases by mapping identity. SQLMesh may add facts while
70+
the work runs, so values in the mapping at `finish` can differ from its values
71+
at `start`. The mapping's supported lifetime ends when the matching `finish`
72+
callback returns.
73+
74+
Ordinary observer `Exception` failures are suppressed and do not replace the
75+
workload result or error. SQLMesh does not suppress observer-raised
76+
`BaseException` subclasses that are not `Exception` subclasses, such as
77+
`KeyboardInterrupt` and `SystemExit`. If `start` raises a `BaseException` that
78+
is not an `Exception`, the work and `finish` callback do not run. If `finish`
79+
raises a `BaseException` that is not an `Exception`, that failure can replace
80+
the workload error.
81+
82+
If a worker raises a `BaseException`, the error can reach the caller after its
83+
worker pool exits. If a DAG run records a terminal error, SQLMesh stops
84+
scheduling nodes and waits for running workers to exit before it raises that
85+
error. Parallel value operations also wait for their workers to finish before
86+
raising a worker's `BaseException`. Blocking callbacks and process termination
87+
are outside the observer failure guarantee. SQLMesh does not log observer
88+
failures.
89+
90+
Nested workload calls produce nested observations. Callbacks for concurrent
91+
workers can interleave, and SQLMesh provides no global callback order. Observers
92+
must support concurrent calls and return promptly. SQLMesh allocates no
93+
execution IDs, timestamps, durations, or parent IDs. Consumers supply those
94+
values when needed.
95+
96+
While SQLMesh delivers a callback, it suppresses observations triggered by that
97+
callback and ignores calls to `update_execution()`. The guard covers callback
98+
delivery only. Normal model work can still contain observations for physical
99+
operations, audits, and queries.
100+
101+
## Native facts and limits
102+
103+
Every facts mapping contains `kind` and `action`. Other fields depend on the
104+
observed operation and can be absent when work exits early or fails.
105+
106+
| Kind | Action | Native facts |
107+
| --- | --- | --- |
108+
| `stage` | Plan-stage class name | `native_plan_id` |
109+
| `model` | `evaluate`, `audit_only` | `snapshot`, `interval`, `batch_index`, `execution_time`, `audit_only` |
110+
| `physical` | `create`, `materialize`, `schema_migration` | `snapshot`; `target` when known; `creating` for materialization; `existed` for schema migration when known |
111+
| `virtual` | `promote`, `demote` | `snapshot`; `target` when known; `source_table` for promotion when known |
112+
| `audit` | `audit` | `audit_name`; `audit_result` at finish if produced |
113+
| `query` | `execute` | `engine` dialect string |
114+
115+
[`Snapshot`](../concepts/architecture/snapshots.md) and `AuditResult` values are
116+
borrowed native objects. Consumers must
117+
treat these objects and other nested values as read-only and must not retain them
118+
beyond the matching `finish` callback. The mapping's read-only wrapper does not
119+
freeze nested objects. Facts are not a JSON event schema. SQLMesh does not
120+
interpret audit results as consumer statuses or inherit model facts into child
121+
mappings. Consumers that need facts after `finish` copy and normalize those
122+
values during the callback.
123+
124+
SQLMesh calls `finish` for an audit before it runs later audits or completes
125+
write-audit-publish (WAP). A later audit or WAP publication can still fail. An audit
126+
query failure can produce a `finish` callback without an `AuditResult`. The
127+
[audits guide](../concepts/audits.md) describes audit behavior in plans and
128+
runs.
129+
130+
For `physical/materialize`, `target` is the logical destination table from the
131+
snapshot. During WAP, SQLMesh writes to a staging destination, but the `target`
132+
fact remains the logical destination. The `finish` callback runs after the
133+
materialization's transaction and session exit. It does not report the result
134+
of later audits or WAP publication.
135+
136+
An observed operation can do no work, issue multiple statements, or trigger
137+
internal driver retries. The observation does not predict how many statements
138+
the operation will issue or report each retry.
139+
140+
The query observation surrounds the base adapter's existing SQL logging and
141+
`_execute` call. It ends before a surrounding transaction commits and before
142+
later fetch or result consumption. Some adapter operations do not call this
143+
query hook. BigQuery session queries, BigQuery dataframe loads, and ClickHouse
144+
dataframe inserts may not produce query observations. These hooks do not provide
145+
a complete warehouse activity history or guarantee transaction success.
146+
147+
SQL logging retains its existing behavior, including VALUES redaction for
148+
non-query expressions. The callback receives no SQL text, adapter objects, or
149+
warehouse query IDs. The `start` callback runs before SQL logging. Consumers can
150+
use that ordering to associate existing log entries with the invocation.
151+
152+
## Worker context
153+
154+
When an observer is active outside callback delivery, SQLMesh copies the current
155+
Python context for each task in scheduler and snapshot DAG work, snapshot schema creation, and
156+
data-object listing. That context carries Python's [context variables](https://docs.python.org/3/library/contextvars.html).
157+
Each task gets its own context copy, including during serial execution. DAG
158+
successors use the context captured for the run. They do not inherit changes
159+
made by earlier workers. Reusing a DAG executor captures a fresh context for
160+
each run.
161+
162+
Context copies are shallow. Mutable objects stored in `ContextVar` values remain
163+
shared across copies. A parent identity stored in a consumer-owned `ContextVar`
164+
is available to each worker. SQLMesh uses these copies in the scheduler and
165+
snapshot DAG, schema creation, and data-object listing. Arbitrary consumer
166+
threads and other concurrency helpers do not receive these copies.
167+
168+
With no observer registered, these operations do not copy contexts. The concurrency
169+
helpers retain their existing `ContextVar` behavior for serial and worker
170+
execution.

‎mkdocs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ nav:
106106
- reference/cli.md
107107
- reference/notebook.md
108108
- reference/python.md
109+
- reference/execution_observations.md
109110
- Configuration:
110111
- reference/configuration.md
111112
- reference/model_configuration.md

0 commit comments

Comments
 (0)