From d00ae1d82613b0534a0d5f993c75f4b4270fa9f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 12:32:22 +0100 Subject: [PATCH 1/6] Fix tenantboard against current snowflake-next images The nightly run has failed in test setup since early November. - clone_database: a cloned table now arrives with its row access policy still referencing the source database's policy, so the plain ADD failed with 003549. Swap the stale reference for the clone's own policy in one ALTER TABLE (DROP ..., ADD ...). - TENANTBOARD_SVC: disable default secondary roles. The user holds every tenant's roles, and Snowflake activates all granted roles as secondary roles by default, which made IS_ROLE_IN_SESSION true for every tenant. Co-Authored-By: Claude Fable 5.2 --- tenantboard/app/provisioning.py | 10 +++++++++- tenantboard/init/01_platform.sf.sql | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tenantboard/app/provisioning.py b/tenantboard/app/provisioning.py index c346b9d..aaf3e30 100644 --- a/tenantboard/app/provisioning.py +++ b/tenantboard/app/provisioning.py @@ -193,7 +193,15 @@ def clone_database(conn: SnowflakeConnection, source: str, target: str) -> None: fqtn = f"{target}.{SCHEMA}.{table}" if ref.kind == "ROW_ACCESS_POLICY": cols = ", ".join(_identifier(c) for c in ref.arg_columns) - statements.append(f"ALTER TABLE {fqtn} ADD ROW ACCESS POLICY {policy} ON ({cols})") + add = f"ADD ROW ACCESS POLICY {policy} ON ({cols})" + # A table carries at most one row access policy. If the clone still + # references the source's, swap it in one statement so the table is + # never unprotected. + stale = next((h for h in have if h.kind == ref.kind), None) + if stale: + old = ".".join(_identifier(part) for part in (stale.database, stale.schema, stale.name)) + add = f"DROP ROW ACCESS POLICY {old}, {add}" + statements.append(f"ALTER TABLE {fqtn} {add}") elif ref.kind == "MASKING_POLICY" and ref.column: column = _identifier(ref.column) if any(h.kind == ref.kind and h.column == ref.column for h in have): diff --git a/tenantboard/init/01_platform.sf.sql b/tenantboard/init/01_platform.sf.sql index 131944c..1f1c17d 100644 --- a/tenantboard/init/01_platform.sf.sql +++ b/tenantboard/init/01_platform.sf.sql @@ -29,6 +29,10 @@ GRANT ROLE PLATFORM_ADMIN TO ROLE SYSADMIN; CREATE USER IF NOT EXISTS TENANTBOARD_SVC DEFAULT_WAREHOUSE = TB_WH COMMENT = 'Tenantboard API service user (key-pair auth)'; +-- Snowflake activates all of a user's granted roles as secondary roles by +-- default. This user holds every tenant's roles, so each session must run +-- with its primary role only, or IS_ROLE_IN_SESSION is true for every tenant. +ALTER USER TENANTBOARD_SVC SET DEFAULT_SECONDARY_ROLES = (); GRANT ROLE PLATFORM_ADMIN TO USER TENANTBOARD_SVC; GRANT USAGE ON WAREHOUSE TB_WH TO ROLE TENANT_READER; GRANT USAGE ON WAREHOUSE TB_WH TO ROLE PLATFORM_ADMIN; From 00f9642d5183563e28ef78c5af94fd972a9f7625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:03:28 +0100 Subject: [PATCH 2/6] glue-snowflake-integration: download the connector jars with retries and a visible error deploy.sh fetched the two jars with 'wget -q', so a failed download ended the run with no message. Use curl with retries, and print the failing URL. Co-Authored-By: Claude Fable 5.2 --- glue-snowflake-integration/README.md | 2 +- glue-snowflake-integration/deploy.sh | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/glue-snowflake-integration/README.md b/glue-snowflake-integration/README.md index e3aff7e..8357ed9 100644 --- a/glue-snowflake-integration/README.md +++ b/glue-snowflake-integration/README.md @@ -27,7 +27,7 @@ glue-snowflake-integration/ - Docker with Docker Compose - Terraform, [`tflocal`](https://github.com/localstack/terraform-local) and [`awslocal`](https://github.com/localstack/awscli-local) - [Snowflake CLI](https://docs.snowflake.com/en/developer-guide/snowflake-cli/installation/installation) (`snow`) and `jq`, for `make test` -- Make and `wget` +- Make and `curl` Run `make install` to install `tflocal`, `awslocal` and the Snowflake CLI with pip. diff --git a/glue-snowflake-integration/deploy.sh b/glue-snowflake-integration/deploy.sh index d0ac77a..55e32f5 100755 --- a/glue-snowflake-integration/deploy.sh +++ b/glue-snowflake-integration/deploy.sh @@ -24,8 +24,17 @@ echo "📥 Downloading dependencies..." rm -rf jars && mkdir jars # Glue 4.0 runs Spark 3.3, so use the connector build for Spark 3.3 -wget -q "https://repo1.maven.org/maven2/net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar" -P jars -wget -q "https://repo1.maven.org/maven2/net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar" -P jars +MAVEN_REPO=${MAVEN_REPO:-https://repo1.maven.org/maven2} +for jar in \ + net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar \ + net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar; do + # -f fails on an HTTP error, -sS hides the progress bar but prints the error + if ! curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 \ + -o "jars/$(basename "$jar")" "$MAVEN_REPO/$jar"; then + echo "❌ Could not download $MAVEN_REPO/$jar" + exit 1 + fi +done # Upload jars to S3 echo "☁️ Uploading JARs to S3..." From 110bfc5c5226bf4b01a202b485f3aaa254201b45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:05:33 +0100 Subject: [PATCH 3/6] order-to-cash-cdc: reach Kafka on 127.0.0.1 instead of localhost The broker's host port is published on 127.0.0.1 only, but the EXTERNAL listener was advertised as localhost and the clients bootstrapped from localhost. On the CI runner localhost also resolves to ::1, so librdkafka kept trying [::1]:19092 (connection refused) and intermittently failed topic creation with _DESTROY_BROKER, in make up or in the tests. Advertise and bootstrap from 127.0.0.1 so every connection uses the published address. Co-Authored-By: Claude Fable 5.2 --- order-to-cash-cdc/docker-compose.yml | 7 +++++-- order-to-cash-cdc/pipeline/settings.py | 3 ++- order-to-cash-cdc/producer/produce.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/order-to-cash-cdc/docker-compose.yml b/order-to-cash-cdc/docker-compose.yml index 6e56fec..cffbddf 100644 --- a/order-to-cash-cdc/docker-compose.yml +++ b/order-to-cash-cdc/docker-compose.yml @@ -30,8 +30,11 @@ services: KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093 KAFKA_LISTENERS: INTERNAL://:29092,EXTERNAL://:19092,CONTROLLER://:9093 # INTERNAL is for Kafka Connect on the compose network, EXTERNAL for the - # producer and tests on the host. - KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://localhost:${KAFKA_PORT:-19092} + # producer and tests on the host. EXTERNAL is advertised as 127.0.0.1, + # not localhost: the port is published on 127.0.0.1 only, and where + # localhost also resolves to ::1 librdkafka tries the IPv6 address, gets + # connection refused and can fail the request. + KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://127.0.0.1:${KAFKA_PORT:-19092} KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER diff --git a/order-to-cash-cdc/pipeline/settings.py b/order-to-cash-cdc/pipeline/settings.py index 1eb5312..0bcdfcb 100644 --- a/order-to-cash-cdc/pipeline/settings.py +++ b/order-to-cash-cdc/pipeline/settings.py @@ -66,7 +66,8 @@ def load() -> Settings: "warehouse": _env("SNOWFLAKE_WAREHOUSE", "O2C_WH"), "database": _env("O2C_DATABASE", "O2C"), "connector_role": _env("O2C_CONNECTOR_ROLE", "O2C_INGEST"), - "kafka_bootstrap": f"localhost:{_env('KAFKA_PORT', '19092')}", + # 127.0.0.1, as published and advertised by docker-compose.yml (not localhost). + "kafka_bootstrap": f"127.0.0.1:{_env('KAFKA_PORT', '19092')}", "connect_url": f"http://127.0.0.1:{_env('CONNECT_PORT', '18083')}", } diff --git a/order-to-cash-cdc/producer/produce.py b/order-to-cash-cdc/producer/produce.py index d0117ee..cea6c26 100644 --- a/order-to-cash-cdc/producer/produce.py +++ b/order-to-cash-cdc/producer/produce.py @@ -344,7 +344,7 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--topic", default="orders.cdc") parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--bootstrap", default=f"localhost:{os.getenv('KAFKA_PORT', '19092')}") + parser.add_argument("--bootstrap", default=f"127.0.0.1:{os.getenv('KAFKA_PORT', '19092')}") args = parser.parse_args() scenario = initial_scenario(args.seed) count = publish(scenario.events, args.topic, args.bootstrap) From 89f1b7090e1a806fe4f9ae69f5837c099b301097 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:20:31 +0100 Subject: [PATCH 4/6] Pin the airflow-dbt-transformation requirements to the environment's Airflow version The unpinned requirements let pip upgrade Airflow inside the MWAA container from 3.0.6 to the newest release while installing dbt. After the restart the Airflow services refused to start, because the metadata database was created by 3.0.6 ("Database migration required"). Pin apache-airflow, the Snowflake provider and the Snowflake connector to the versions the Airflow 3.0.6 image ships, pin Cosmos and dbt to releases that work with them, and create the environment with an explicit Airflow version. Co-Authored-By: Claude Fable 5.2 --- airflow-dbt-transformation/Makefile | 3 +++ airflow-dbt-transformation/README.md | 2 ++ airflow-dbt-transformation/requirements.txt | 19 +++++++++++++++---- airflow-dbt-transformation/test.sh | 2 +- 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/airflow-dbt-transformation/Makefile b/airflow-dbt-transformation/Makefile index 6a1cbe5..b3bfaef 100644 --- a/airflow-dbt-transformation/Makefile +++ b/airflow-dbt-transformation/Makefile @@ -1,4 +1,6 @@ AIRFLOW_CONTAINER = localstack-mwaa-000000000000-us-east-1-my-mwaa-env +# the versions in requirements.txt are pinned to match this Airflow version +AIRFLOW_VERSION = 3.0.6 usage: ## Shows usage for this Makefile @cat Makefile | grep -E '^[a-zA-Z_-]+:.*?## .*$$' | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}' @@ -22,6 +24,7 @@ init: ## Initialize the Airflow environment in LocalStack MWAA awslocal s3 cp requirements.txt s3://snowflake-airflow/ -docker rm -f $(AIRFLOW_CONTAINER) awslocal mwaa create-environment --dag-s3-path /dags \ + --airflow-version $(AIRFLOW_VERSION) \ --requirements-s3-path /requirements.txt \ --execution-role-arn arn:aws:iam::000000000000:role/airflow-role \ --network-configuration {} \ diff --git a/airflow-dbt-transformation/README.md b/airflow-dbt-transformation/README.md index 97bc201..85c178e 100644 --- a/airflow-dbt-transformation/README.md +++ b/airflow-dbt-transformation/README.md @@ -43,6 +43,8 @@ Run the following command to initialize the Airflow environment in LocalStack (t make init ``` +The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`), and `requirements.txt` pins `apache-airflow` and the other packages to versions that match it. Keep the two in sync: without the pins, `pip` upgrades Airflow itself while installing dbt, and the Airflow services then fail to start with `Database migration required`. To use another Airflow version, change `AIRFLOW_VERSION` and take the pins from the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of that version. + After deploying the Airflow environment, you should be able to request its details, and extract the webserver URL: ``` awslocal mwaa get-environment --name my-mwaa-env diff --git a/airflow-dbt-transformation/requirements.txt b/airflow-dbt-transformation/requirements.txt index b8c42f7..76af33b 100644 --- a/airflow-dbt-transformation/requirements.txt +++ b/airflow-dbt-transformation/requirements.txt @@ -1,4 +1,15 @@ -apache-airflow-providers-snowflake -astronomer-cosmos -dbt-snowflake -snowflake-connector-python +# The environment runs Airflow 3.0.6 on Python 3.12 (`--airflow-version` in the +# Makefile). Pin Airflow and the packages its image already ships, so that +# installing dbt cannot upgrade Airflow itself: an upgraded Airflow no longer +# matches the environment's metadata database and fails to start. +# The first three versions are the ones in the Airflow constraints file: +# https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt +# That file cannot be used as `--constraint` here, because dbt needs newer +# protobuf and isodate versions than it allows. +apache-airflow==3.0.6 +apache-airflow-providers-snowflake==6.4.0 +snowflake-connector-python==3.17.2 +astronomer-cosmos==1.16.0 +# the newest dbt releases that work with snowflake-connector-python 3.x +dbt-core==1.10.23 +dbt-snowflake==1.10.5 diff --git a/airflow-dbt-transformation/test.sh b/airflow-dbt-transformation/test.sh index ade83d1..73a2943 100755 --- a/airflow-dbt-transformation/test.sh +++ b/airflow-dbt-transformation/test.sh @@ -25,7 +25,7 @@ poll() { airflow() { docker exec "$CONTAINER" airflow "$@" 2>/dev/null; } diagnostics() { docker inspect "$CONTAINER" --format '{{json .NetworkSettings.Networks}}' | jq -c 'keys' || true - docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true + docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true docker exec "$CONTAINER" airflow dags list-import-errors || true docker exec "$CONTAINER" bash -c 'tail -n 40 $(find /opt/airflow/logs -path "*query_result_data*" -name "*.log" | head -1)' || true docker logs --tail 80 "$CONTAINER" 2>&1 | grep -v SyntaxWarning || true From b983dd498271766c247d122a9787456997ba499b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:42:15 +0100 Subject: [PATCH 5/6] glue-snowflake-integration: drop the MAVEN_REPO override from deploy.sh Nothing sets it and no mirror is in use, so download the two jars from their Maven Central URLs directly. The curl retries and the error message stay as they were. Co-Authored-By: Claude Fable 5.2 --- glue-snowflake-integration/deploy.sh | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/glue-snowflake-integration/deploy.sh b/glue-snowflake-integration/deploy.sh index 55e32f5..6776f2b 100755 --- a/glue-snowflake-integration/deploy.sh +++ b/glue-snowflake-integration/deploy.sh @@ -24,14 +24,13 @@ echo "📥 Downloading dependencies..." rm -rf jars && mkdir jars # Glue 4.0 runs Spark 3.3, so use the connector build for Spark 3.3 -MAVEN_REPO=${MAVEN_REPO:-https://repo1.maven.org/maven2} -for jar in \ - net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar \ - net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar; do +for url in \ + https://repo1.maven.org/maven2/net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar \ + https://repo1.maven.org/maven2/net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar; do # -f fails on an HTTP error, -sS hides the progress bar but prints the error if ! curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 \ - -o "jars/$(basename "$jar")" "$MAVEN_REPO/$jar"; then - echo "❌ Could not download $MAVEN_REPO/$jar" + -o "jars/$(basename "$url")" "$url"; then + echo "❌ Could not download $url" exit 1 fi done From 3191271b1536590e88975b4eea5189c5dc0a4a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:47:15 +0100 Subject: [PATCH 6/6] airflow-dbt-transformation: run dbt in its own virtual environment and drop the version pins dbt and Airflow shared one Python environment, so requirements.txt had to pin Airflow, the Snowflake provider, the connector, Cosmos and dbt by hand, and dbt was held at 1.10. The DAG now uses the Cosmos virtualenv execution mode: the first dbt task creates /opt/airflow/dbt_venv with the newest dbt-snowflake and the following tasks reuse it. Airflow's environment has no dbt, so the DAG is rendered with LoadMode.CUSTOM instead of dbt ls. requirements.txt lists only what Airflow imports, without pins, under the official constraints file for Airflow 3.0.6 / Python 3.12. test.sh no longer waits for dbt-snowflake in Airflow's environment, and checks after the run that Airflow kept its version and that dbt is only in the virtual environment. dbt_project.yml uses the '+' config prefix that dbt 1.12 asks for. Co-Authored-By: Claude Fable 5.2 --- airflow-dbt-transformation/Makefile | 2 +- airflow-dbt-transformation/README.md | 10 +++++++-- airflow-dbt-transformation/airflow_dag.py | 24 ++++++++++++++------- airflow-dbt-transformation/dbt_project.yml | 14 ++++++------ airflow-dbt-transformation/requirements.txt | 24 ++++++++------------- airflow-dbt-transformation/test.sh | 17 +++++++++++++-- 6 files changed, 56 insertions(+), 35 deletions(-) diff --git a/airflow-dbt-transformation/Makefile b/airflow-dbt-transformation/Makefile index b3bfaef..6d738a0 100644 --- a/airflow-dbt-transformation/Makefile +++ b/airflow-dbt-transformation/Makefile @@ -1,5 +1,5 @@ AIRFLOW_CONTAINER = localstack-mwaa-000000000000-us-east-1-my-mwaa-env -# the versions in requirements.txt are pinned to match this Airflow version +# the constraints file in requirements.txt is the one of this Airflow version AIRFLOW_VERSION = 3.0.6 usage: ## Shows usage for this Makefile diff --git a/airflow-dbt-transformation/README.md b/airflow-dbt-transformation/README.md index 85c178e..c6fff55 100644 --- a/airflow-dbt-transformation/README.md +++ b/airflow-dbt-transformation/README.md @@ -38,12 +38,18 @@ From your machine, connect to `snowflake.localhost.localstack.cloud` on port 456 The sample application provides Makefile targets to simplify the setup process. -Run the following command to initialize the Airflow environment in LocalStack (this may take a couple of seconds). It uploads `requirements.txt` first, so the environment installs `astronomer-cosmos`, `dbt-snowflake` and the Snowflake provider: +Run the following command to initialize the Airflow environment in LocalStack (this may take a couple of seconds). It uploads `requirements.txt` first, so the environment installs `astronomer-cosmos` and the Snowflake provider: ``` make init ``` -The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`), and `requirements.txt` pins `apache-airflow` and the other packages to versions that match it. Keep the two in sync: without the pins, `pip` upgrades Airflow itself while installing dbt, and the Airflow services then fail to start with `Database migration required`. To use another Airflow version, change `AIRFLOW_VERSION` and take the pins from the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of that version. +Airflow and dbt do not share a Python environment, because their dependencies conflict (dbt needs newer `protobuf` and Snowflake connector versions than Airflow 3.0.6 allows): + +- `requirements.txt` lists only what Airflow imports to load the DAG. It has no version pins. Its first line applies the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of the environment's Airflow version, so `pip` cannot upgrade Airflow or the packages its image ships. +- dbt runs in its own virtual environment. The DAG uses the Cosmos [virtualenv execution mode](https://astronomer.github.io/astronomer-cosmos/getting_started/execution-modes.html#virtualenv): the first dbt task creates `/opt/airflow/dbt_venv` and installs the newest `dbt-snowflake` into it, and the following tasks reuse it. To use a specific dbt version, set it in `dbt_requirements` in `airflow_dag.py`. +- Airflow's own environment has no dbt, so Cosmos cannot run `dbt ls` to render the DAG. The DAG sets `LoadMode.CUSTOM`, which reads the models and their `ref()` calls with the Cosmos parser. + +The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`) on Python 3.12. To use another Airflow version, change `AIRFLOW_VERSION` and the two versions in the constraints URL in `requirements.txt`. After deploying the Airflow environment, you should be able to request its details, and extract the webserver URL: ``` diff --git a/airflow-dbt-transformation/airflow_dag.py b/airflow-dbt-transformation/airflow_dag.py index 57395ae..d00cd6f 100644 --- a/airflow-dbt-transformation/airflow_dag.py +++ b/airflow-dbt-transformation/airflow_dag.py @@ -1,6 +1,5 @@ import json import os -import shutil from datetime import datetime from pathlib import Path @@ -9,7 +8,8 @@ from airflow.providers.standard.operators.empty import EmptyOperator except ImportError: # Airflow 2 from airflow.operators.empty import EmptyOperator -from cosmos import DbtTaskGroup, ProjectConfig, ProfileConfig, ExecutionConfig +from cosmos import DbtTaskGroup, ProjectConfig, ProfileConfig, ExecutionConfig, RenderConfig +from cosmos.constants import ExecutionMode, LoadMode from cosmos.profiles.snowflake.user_pass import SnowflakeUserPasswordProfileMapping from snowflake import connector @@ -55,10 +55,12 @@ target_name="dev", profile_mapping=credentials) -# use a dedicated dbt virtualenv if the environment has one, otherwise the dbt -# installed from requirements.txt -dbt_venv_executable = f"{os.environ['AIRFLOW_HOME']}/dbt_venv/bin/dbt" -dbt_executable = dbt_venv_executable if os.path.exists(dbt_venv_executable) else shutil.which("dbt") +# dbt runs in its own virtual environment, so its dependencies cannot conflict +# with the packages of Airflow. Cosmos creates the environment in the first dbt +# task, installs the newest dbt-snowflake (which brings dbt-core) and reuses it +# in the following tasks. +dbt_venv_dir = Path(os.environ["AIRFLOW_HOME"]) / "dbt_venv" +dbt_requirements = ["dbt-snowflake"] @dag(schedule="@hourly", @@ -73,8 +75,14 @@ def dbt_snowpark_dag(): group_id="transform_data", project_config=ProjectConfig(dbt_project_path), profile_config=profile_config, - execution_config=ExecutionConfig(dbt_executable_path=dbt_executable), - operator_args={"install_deps": True}, + execution_config=ExecutionConfig( + execution_mode=ExecutionMode.VIRTUALENV, + virtualenv_dir=dbt_venv_dir, + ), + # Airflow's own environment has no dbt, so read the models and their + # ref() dependencies with the Cosmos parser instead of `dbt ls` + render_config=RenderConfig(load_method=LoadMode.CUSTOM), + operator_args={"install_deps": True, "py_requirements": dbt_requirements}, ) intermediate = EmptyOperator(task_id='intermediate') diff --git a/airflow-dbt-transformation/dbt_project.yml b/airflow-dbt-transformation/dbt_project.yml index 2ab42e1..020ce5a 100644 --- a/airflow-dbt-transformation/dbt_project.yml +++ b/airflow-dbt-transformation/dbt_project.yml @@ -3,16 +3,16 @@ models: test_dbt: # Applies to all files under models/example/ transform: - schema: transform - materialized: view + +schema: transform + +materialized: view analysis: - schema: analysis - materialized: view + +schema: analysis + +materialized: view seeds: bookings_1: - enabled: true + +enabled: true bookings_2: - enabled: true + +enabled: true customers: - enabled: true + +enabled: true diff --git a/airflow-dbt-transformation/requirements.txt b/airflow-dbt-transformation/requirements.txt index 76af33b..20c383d 100644 --- a/airflow-dbt-transformation/requirements.txt +++ b/airflow-dbt-transformation/requirements.txt @@ -1,15 +1,9 @@ -# The environment runs Airflow 3.0.6 on Python 3.12 (`--airflow-version` in the -# Makefile). Pin Airflow and the packages its image already ships, so that -# installing dbt cannot upgrade Airflow itself: an upgraded Airflow no longer -# matches the environment's metadata database and fails to start. -# The first three versions are the ones in the Airflow constraints file: -# https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt -# That file cannot be used as `--constraint` here, because dbt needs newer -# protobuf and isodate versions than it allows. -apache-airflow==3.0.6 -apache-airflow-providers-snowflake==6.4.0 -snowflake-connector-python==3.17.2 -astronomer-cosmos==1.16.0 -# the newest dbt releases that work with snowflake-connector-python 3.x -dbt-core==1.10.23 -dbt-snowflake==1.10.5 +# What Airflow itself imports to load and run the DAG. dbt is not in this list: +# Cosmos installs it into a separate virtual environment (see airflow_dag.py). +# The constraints file of the environment's Airflow and Python version +# (`AIRFLOW_VERSION` in the Makefile, Python 3.12) keeps `pip` from upgrading +# Airflow or the packages its image ships. +--constraint https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt +apache-airflow-providers-snowflake +snowflake-connector-python +astronomer-cosmos diff --git a/airflow-dbt-transformation/test.sh b/airflow-dbt-transformation/test.sh index 73a2943..059d2ee 100755 --- a/airflow-dbt-transformation/test.sh +++ b/airflow-dbt-transformation/test.sh @@ -25,7 +25,7 @@ poll() { airflow() { docker exec "$CONTAINER" airflow "$@" 2>/dev/null; } diagnostics() { docker inspect "$CONTAINER" --format '{{json .NetworkSettings.Networks}}' | jq -c 'keys' || true - docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true + docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos 2>&1 | grep -E "^(Name|Version)"; $AIRFLOW_HOME/dbt_venv/bin/dbt --version' || true docker exec "$CONTAINER" airflow dags list-import-errors || true docker exec "$CONTAINER" bash -c 'tail -n 40 $(find /opt/airflow/logs -path "*query_result_data*" -name "*.log" | head -1)' || true docker logs --tail 80 "$CONTAINER" 2>&1 | grep -v SyntaxWarning || true @@ -43,7 +43,8 @@ echo "PASS: MWAA environment is available" make deploy dag_synced() { docker exec "$CONTAINER" test -f /opt/airflow/dags/airflow_dag.py -a -d /opt/airflow/dags/macros; } poll "the DAG files to be synced from S3" 30 10 dag_synced -requirements_installed() { docker exec "$CONTAINER" bash -c "pip show astronomer-cosmos dbt-snowflake" > /dev/null 2>&1; } +# dbt is not among them: Cosmos installs it into its own virtual environment in the first dbt task +requirements_installed() { docker exec "$CONTAINER" bash -c "pip show astronomer-cosmos" > /dev/null 2>&1; } poll "the requirements to be installed" 60 10 requirements_installed echo "PASS: DAG files synced and requirements installed" @@ -75,6 +76,18 @@ if [ "$state" != "success" ]; then fi echo "PASS: the dbt seeds, models and the PREPPED_DATA query succeeded" +# dbt ran from its own virtual environment, and installing the requirements left Airflow's environment alone +docker exec "$CONTAINER" bash -c '$AIRFLOW_HOME/dbt_venv/bin/dbt --version' +installed=$(docker exec "$CONTAINER" bash -c "pip list --format json" 2>/dev/null) +airflow_version=$(jq -r '.[] | select(.name == "apache-airflow") | .version' <<< "$installed") +expected_version=$(sed -n 's/^AIRFLOW_VERSION = //p' Makefile) +if [ "$airflow_version" != "$expected_version" ] || jq -e 'any(.[]; .name | startswith("dbt-"))' <<< "$installed" > /dev/null; then + echo "Test failed: expected Airflow $expected_version without dbt in Airflow's environment, found Airflow $airflow_version and:" + jq -r '.[] | select(.name | startswith("dbt-")) | "\(.name) \(.version)"' <<< "$installed" + exit 1 +fi +echo "PASS: Airflow is still $airflow_version and dbt is installed only in the virtual environment" + snow connection add --connection-name airflow-dbt --user test --password test --account test \ --host snowflake.localhost.localstack.cloud --port 4567 --no-interactive > /dev/null 2>&1 || true rows=$(snow sql -c airflow-dbt --format json -q "SELECT COUNT(*) AS N FROM test.transform.PREPPED_DATA" | jq -r '.. | objects | .N? // empty' | head -1)