# Cal-ITP's dbt project This dbt project is intended to be the source of truth for the cal-itp-data-infra BigQuery warehouse. ## Setting up the project in your JupyterHub personal server If you are developing dbt models in JupyterHub, the following pieces are already configured/installed. - Libraries such as gdal - The `gcloud` CLI > You may have already authenticated gcloud and the GitHub CLI (gh) if you followed the > [JupyterHub setup docs](https://docs.calitp.org/data-infra/analytics_tools/jupyterhub.html). If not, follow those instructions before proceeding. ### Clone and install the warehouse project 1. [Clone](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) the `data-infra` repo via `git clone git@github.com:cal-itp/data-infra.git` if you haven't already. Use [SSH](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account), not HTTPS. If you haven't made a folder/directory for your git repos yet, you can create one with `mkdir git` (within your home directory, usually). 1. You may be prompted to accept GitHub key's fingerprint if you are cloning a repository for the first time. 2. The rest of these instructions assume you are in the `warehouse/` directory of the repository. 1. You will need to `cd` to it via `cd /data-infra/warehouse/` or similar; for example, if you had created your directory with `mkdir git`, you will navigate to the warehouse directory with `cd git/data-infra/warehouse/`. 3. Execute `uv sync` to create a virtual environment and install requirements. > [!NOTE] > If you run into the error `No such file or directory` you need to [install uv](#Install-uv). 4. Execute `uv run dbt deps` to install the dbt dependencies defined in `packages.yml` (such as `dbt_utils`). 5. Set up your DBT profiles directory: 1. If you are using JupyterHub, it should already be set to `/home/jovyan/.dbt/`. 2. On your local machine, you will need to modify your respective shell's RC (e.g. `.zshrc`, `.bashrc`) file to export `DBT_PROFILES_DIR` to something like `~/.dbt/`. You can check with `echo $DBT_PROFILES_DIR` to make sure it's set correctly. 6. Execute `uv run dbt init` to create the `$DBT_PROFILES_DIR` directory and a pre-built `profiles.yml` file; you will be prompted to enter a personal `schema` which is used as a prefix for your personal development environment schemas. The output should look similar to the following: ```text ➜ uv run dbt init 19:14:32 Running with dbt=1.4.5 19:14:32 Setting up your profile. schema (usually your name; will be added as a prefix to schemas e.g. _mart_gtfs): andrew maximum_bytes_billed (the maximum number of bytes allowed per BigQuery query; default is 2 TB) [2000000000000]: 19:14:35 Profile calitp_warehouse written to /Users/andrewvaccaro/.dbt/profiles.yml using project's profile_template.yml and your supplied values. Run 'dbt debug' to validate the connection. ``` See [the dbt docs on profiles.yml](https://docs.getdbt.com/dbt-cli/configure-your-profile) for more background on this file. > [!NOTE] > This default profile template will set a maximum bytes billed of 2 TB; no models should fail with the default lookbacks in our development environment, even with a full refresh. You can override this limit during the init, or change it later by calling init again and choosing to overwrite (or editing the profiles.yml directly). > > [!WARNING] > If you receive a warning similar to the following, do **NOT** overwrite the file. This is a sign that you do not have a `DBT_PROFILES_DIR` variable available in your environment and need to address that first (see step 5). > > ```text > The profile calitp_warehouse already exists in /data-infra/warehouse/profiles.yml. Continue and overwrite it? [y/N]: > ``` 7. Check whether `~/.dbt/profiles.yml` was successfully created, e.g. `cat ~/.dbt/profiles.yml`. If you encountered an error, you may create it by hand and fill it with the same content - this will point your models at BigQuery datasets (schemas) in the `cal-itp-data-infra-staging` project that are prefixed with your name, where operations on them will not impact production data: ```yaml calitp_warehouse: outputs: dev: fixed_retries: 1 location: us-west2 method: oauth priority: interactive project: cal-itp-data-infra-staging schema: threads: 8 timeout_seconds: 3000 maximum_bytes_billed: 100000000000 type: bigquery gcs_bucket: test-calitp-dbt-python-models dataproc_region: us-west2 submission_method: serverless dataproc_batch: runtime_config: container_image: gcr.io/cal-itp-data-infra/dbt-spark:2023.3.28 properties: spark.executor.cores: "4" spark.executor.instances: "4" spark.executor.memory: 4g spark.dynamicAllocation.maxExecutors: "16" target: dev ``` 8. Finally, test your connection to our staging BigQuery project with `uv run dbt debug`. You should see output similar to the following. ```bash ➜ warehouse git:(jupyterhub-dbt) ✗ uv run dbt debug Running with dbt=1.10.1 dbt version: 1.10.1 python version: 3.11.13 python path: /Users/Username/Documents/workspace/data-infra/warehouse/.venv/bin/python3 os info: macOS-26.2-arm64-arm-64bit Using profiles.yml file at /Users/Username/.dbt/profiles.yml Using dbt_project.yml file at /Users/Username/go/src/github.com/cal-itp/data-infra/warehouse/dbt_project.yml adapter type: bigquery adapter version: 1.10.0 Configuration: profiles.yml file [OK found and valid] dbt_project.yml file [OK found and valid] Required dependencies: - git [OK found] Connection: method: oauth database: cal-itp-data-infra-staging execution_project: cal-itp-data-infra-staging schema: location: us-west2 priority: interactive maximum_bytes_billed: 2000000000000 impersonate_service_account: None job_retry_deadline_seconds: None job_retries: 1 job_creation_timeout_seconds: None job_execution_timeout_seconds: 3000 timeout_seconds: 3000 client_id: None token_uri: None compute_region: us-west2 dataproc_cluster_name: None gcs_bucket: test-calitp-dbt-python-models dataproc_batch: {'runtime_config': {'container_image': 'gcr.io/cal-itp-data-infra/dbt-spark:2023.3.28', 'properties': {'spark.dynamicAllocation.maxExecutors': '16', 'spark.executor.cores': '4', 'spark.executor.instances': '4', 'spark.executor.memory': '4g'}}} Registered adapter: bigquery=1.10.0 Connection test: [OK connection ok] All checks passed! ``` ## dbt Commands Once you have performed the setup above, you are good to go run [dbt commands](https://docs.getdbt.com/reference/dbt-commands) locally! Run the following commands in order. 1. `uv run dbt seed` This command creates tables in your personally-named schema from the CSV files present in [./seeds](./seeds), which can then be referenced by dbt models. You will need to re-run seeds if new seeds are added, or existing ones are changed. 2. `uv run dbt compile` This command generates executable SQL from the source model, but will not execute anything in the warehouse. It is useful for visualizing what dbt will actually execute. You can find these compiled SQL files in the `target/` directory. 3. `uv run dbt run` This command executes compiled SQL model files in the warehouse. The default target is `dev` that points to `cal-itp-data-infra-staging` project. During development, you can specify [selections](https://docs.getdbt.com/reference/node-selection/syntax) (via the `-s` or `--select` flags) to run only a subset of models, otherwise this will run _all_ the tables. By default, your very first `run` is a [full refresh](https://docs.getdbt.com/reference/commands/run#refresh-incremental-models) but you'll need to pass the `--full-refresh` flag (or an appropriate `--event-time-start` / `--event-time-end` range) in the future if you want to change the schema of incremental tables, or "backfill" existing rows with new logic. > [!NOTE] > In general, it is a good idea to run `seed` and `run --full-refresh` if you think your local environment is substantially outdated (for example, if you haven't worked on dbt models in a few weeks but want to create or modify a model). We have macros in the project that prevent a non-production "full refresh" from actually processing all possible data. > [!NOTE] > If your workflow requires querying historical source data in our production environment, you will need to: > 1. Ensure that you have the appropriate permissions to query our production Google Cloud environment `cal-itp-data-infra`. If you don't have the adequate permissions, or are unsure, contact an administrator of our Google Cloud project. > 2. Add the appropriate flag and variable to your command: `--vars 'GOOGLE_CLOUD_PROJECT: cal-itp-data-infra'` > > ex. `uv run dbt run -s schema.table --vars 'GOOGLE_CLOUD_PROJECT: cal-itp-data-infra'` Some additional helpful commands: - `uv run dbt test` This command runs data tests defined on models, sources, seeds, and unit tests defined on SQL models. Many tests in the warehouse are disabled pending investigation & prioritization -- to turn on a specific test during development, you can set the [`config.enabled` flag](https://docs.getdbt.com/reference/resource-configs/enabled) on that test to true -- this is done in the YAML or SQL file where the test is defined, or you can turn on tests for an entire directory of models by changing the flag in `dbt_project.yaml` under the `data-tests` key. You can specify [selections](https://docs.getdbt.com/reference/node-selection/syntax) (via the `-s` or `--select` flags) to test only a specific model. ```bash $ uv run dbt test -s <> ``` - `uv run dbt docs generate` This command generates the dbt documentation website by: * Copying the website `index.html` file into the `target/` directory. * Compiling the resources in the project to included in `manifest.json`. * Running queries against database metadata to produce the `catalog.json` file, which contains metadata about the tables and views produced by the models in the project. - `uv run dbt docs serve` This command starts a webserver on `http://localhost:8080` to "serve" your dbt documentation locally so you can access it in your default browser. Be sure to run `uv run dbt docs generate` first. ### Incremental model considerations We make heavy use of [incremental models](https://docs.getdbt.com/docs/build/incremental-models) in the Cal-ITP warehouse since we have large data volumes, but that data arrives in a relatively consistent pattern (i.e. temporal). #### Incremental date settings The amount of history that will be run in a given dbt execution is controlled by a combination of three settings: * **Global start dates**: These are the dates that will be used the first time an incremental model is run or if `--full-refresh` is specified and enabled for the given model. In `dbt_project.yaml`, we set global start dates for data sources using the variables `GTFS_SCHEDULE_START`, `GTFS_RT_START`, `KUBA_DEVICE_START`. For GTFS data, these dates are set to only 7 days in the past in non-production environments to limit how much history will be run. See below for more information on options for running different amounts of history in development vs. production environments. * `--full-refresh` note: It is best practice that microbatch incremental models have `full-refresh` set to `false` in their individual model configuration. Therefore they may not full refresh even if the flag is passed. Instead, use `--event-time-start` and `--event-time-end` for historical backfills on microbatch models. * Microbatch note: `--event-time-start` and `--event-time-end` will override this for microbatch models, meaning that if an event time start/end before the dataset start are explicitly passed to a microbatch model, that model will try to run those earlier historical dates. * **Lookback range**: Most of our incremental models use a fixed lookback period, meaning that on a standard incremental run they will run a set number of days of history. This lookback window is configured using the `DBT_ALL_INCREMENTAL_LOOKBACK_DAYS` and `DBT_DAILY_INCREMENTAL_LOOKBACK_DAYS` dbt variables, defined by default in `dbt_project.yaml`. Which variable a given model uses depends on whether the model runs in the `dbt all` or `dbt daily` Airflow DAG. * **Specified date range**: The standard lookback period can be overridden by using configurations to define a date range to refresh. These configurations take two forms: * For **microbatch** incremental models, define a date range using the `--event-time-start` and `--event-time-end` dbt arguments. * For **non-microbatch** incremental models, use the `DBT_INCREMENTAL_START_DATE` and `DBT_INCREMENTAL_END_DATE` dbt variables. * These two configurations (`event time start/end` and `DBT incremental start/end date`) can be passed together if you want to handle microbatch and non-microbatch models in the same run. #### In development environment In a development environment, if you want to access additional history for an incremental model, there are multiple options and considerations: - You can copy the production table with `CREATE TABLE . COPY .`; copies are free in BigQuery so this is substantially cheaper than fully building the model yourself. This will give you a full copy of the production table in your development schema to work with. - If you need to rebuild specific date ranges, first check whether the model you care about is microbatch or not. - For microbatch models, you can pass the `--event-time-start` and `--event-time-end` arguments to reprocess a historical date range. Both arguments are required. For example: ``` uv run dbt run -s [your model] --event-time-start '2025-01-01' --event-time-end '2025-01-02' ``` These settings will ignore/override the global start date for microbatch models and run regardless of what is set in the global start date. - For non-microbatch models, you can pass the `DBT_INCREMENTAL_START_DATE` and `DBT_INCREMENTAL_END_DATE` variables, like this: ``` uv run dbt run -s [your model] --vars '{DBT_INCREMENTAL_START_DATE: "2025-01-01", DBT_INCREMENTAL_END_DATE: "2025-01-02", [START DATE VARIABLE]: "2025-01-01"}' ``` **For these models, you must ensure that an early enough global start date is provided, because the macro won't run data before the global start date.** Putting these together, you can run a combination of microbatch and non-microbatch models by providing the same configs in both variables and providing an appropriate start date: ``` uv run dbt run -s [your models and/or selector logic] --event-time-start '2025-01-01' --event-time-end '2025-01-02' --vars '{DBT_INCREMENTAL_START_DATE: "2025-01-01", DBT_INCREMENTAL_END_DATE: "2025-01-02", [START DATE VARIABLE]: "2025-01-01"}' ``` - If you need to compile or run models in Staging instead of in your personally-named schema, you need to include the configuration in your `~/.dbt/profiles.yml` and add the `--target staging` flag in your command. ```bash $ uv run dbt [run/compile] -s [incremental_model_name] --target staging --event-time-start '2025-01-01' --event-time-end '2025-01-02' --vars '{DBT_INCREMENTAL_START_DATE: "2025-01-01", DBT_INCREMENTAL_END_DATE: "2025-01-02", [START DATE VARIABLE]: "2025-01-01"}' ``` **Note that at time of writing, `dbt compile` does not actually show compiled event time batches for microbatch models. See [dbt-core#12592](https://github.com/dbt-labs/dbt-core/issues/12592).** #### In production **In production**, avoid using `--full-refresh` for larger incremental models. BigQuery does not have enough resources to run a full-refresh in some of GTFS RT tables, but you can rebuild data (if needed) in batches for specific ranges. To re-run data in production, use the `dbt_manual_run_with_args` Airflow DAG. This DAG lets you pass relevant configuration while storing run information in Airflow and guaranteeing that you will run against the correct production target. To run, open the DAG and click the "play" button icon in the upper right and select `Trigger DAG w/ config`. This will open a configuration screen where you can enter your information. You can enter dbt model selection logic, variables, etc. Use the `select` box for the [dbt node selection syntax](https://docs.getdbt.com/reference/node-selection/syntax?version=1.12), exclude for exclusions, `event-time-start` / `event-time-end` for those arguments, and the `vars` entry box for any dbt variables you want to pass. ## Setting up the project on your local machine If you prefer to install dbt locally and use your own development environment, you may follow these instructions to install the same tools already installed in the JupyterHub environment. If this is your first time using the terminal, we recommend reading "[Learning the Mac OS X Command Line](https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line)" or another tutorial first. You will generally need to understand `cd` and the concept of the "home directory" aka `~`. When you first open the terminal, your "working directory" will be the home directory. Running the `cd` command without any arguments will set your working directory back to `~`. You can enable [displaying hidden folders/files in macOS Finder](https://www.macworld.com/article/671158/how-to-show-hidden-files-on-a-mac.html) but generally, we recommend using the terminal when possible for editing these files. Generally, `nano ~/.dbt/profiles.yml` will be the easiest method for editing your personal profiles file. `nano` is a simple terminal-based text editor; you use the arrows keys to navigate and the hotkeys displayed at the bottom to save and exit. Reading an [online tutorial for using `nano`](https://www.howtogeek.com/42980/the-beginners-guide-to-nano-the-linux-command-line-text-editor/) may be useful if you haven't used a terminal-based editor before. > [!NOTE] > These instructions assume you are on macOS, but are largely similar for other operating systems. Most \*nix OSes will have a package manager that you should use instead of Homebrew. > > If you get `Operation not permitted` when attempting to use the terminal, you may need to [fix your terminal permissions](https://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/) ### Install Homebrew (if you haven't) 1. Follow the installation instructions at [https://brew.sh/](https://brew.sh/) 2. Then, `brew install gdal` to install libraries used by some Python libraries. ### Install the Google SDK (if you haven't) 0. Implied: make sure that you have GCP permissions (i.e. that someone has added you to the GCP project) 1. Install and configure Google Cloud CLI 1. Install it via Homebrew for an automatic process or skip to step 2 for a manual installation ```bash brew install google-cloud-sdk ``` 2. Follow download the latest release from [Google `gcloud` documentation](https://cloud.google.com/sdk/docs/install) and follow their instructions or read along here. 1. Unzip the `.tar.gz` file that you downloaded ```bash # This will unzip the file to your home directory (aka ~/) tar -xvf ~ ``` 2. Then run the installer in your terminal ```bash ~/google-cloud-sdk/install.sh ``` 3. When prompted to modify your `$PATH` and enable command completion, choose yes. 4. After the installation process has completed, check your shell configuration (e.g. `~/.zshrc`, `~/.bashrc`) to ensure that the `google-cloud-sdk` folder has been added to your `$PATH`. The line you're looking for may look similar to, ```bash export PATH="$HOME/google-cloud-sdk/bin:$PATH" ``` 2. Restart your terminal and run `gcloud auth login --login-config=iac/login.json` 3. Set the default project with `gcloud config set project cal-itp-data-infra-staging` 4. You should also [set the application default](https://cloud.google.com/sdk/gcloud/reference/auth/application-default) so that `dbt` can access your Google Cloud credentials. ```bash gcloud auth application-default login --login-config=iac/login.json ``` 5. If `bq ls` shows output, you are good to go. ### Install uv > [!IMPORTANT] > Use uv instead of Poetry > `pip install uv` 1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/) (used for package/dependency management). 2. Restart your terminal and confirm `uv --version` works. 3. Follow the [warehouse setup instructions](#clone-and-install-the-warehouse-project) #### Poetry vs uv commands To install packages and dependences use `uv sync` instead of `poetry install`. For other common commands you can just replace `poetry` by `uv`, for example: * `poetry run dbt deps` -> `uv run dbt deps` * `poetry run dbt compile` -> `uv run dbt compile` ### Install Python If you need to install any specific Python version [follow this instructions](https://docs.astral.sh/uv/concepts/python-versions/#managed-and-system-python-installations). ### Dataproc configuration > If you are not using Python models or are just using the existing Dataproc configuration, you can ignore this section. [dbt docs](https://docs.getdbt.com/docs/build/python-models) exist for setting up Python models in general, as well as the specific steps required to configure BigQuery/Dataproc. The default profile template specifies `gcr.io/cal-itp-data-infra/dbt-spark:` as the custom image for Dataproc batch jobs. This image is built and pushed via the following; note that the image is hosted on Google Container Registry (`gcr.io`) not GitHub Container Registry (`ghcr.io`). This will need to be migrated to Google Artifact Repository at some point in the future, as it is replacing GCR. ```bash docker build -f Dockerfile.spark -t gcr.io/cal-itp/data-infra/dbt-spark:2023.3.28 docker push gcr.io/cal-itp-data-infra/dbt-spark:2023.3.28 ``` Dockerfile.spark is based on the [example provided by Google in their Dataproc Serverless documentation](https://cloud.google.com/dataproc-serverless/docs/guides/custom-containers#example_custom_container_image_build). It references two files that are copied from local into the image; links are provided as comments for downloading these if the image needs to be re-built. In addition to the steps specified in the dbt docs, [Google Private Access was enabled on our default VPC](https://cloud.google.com/vpc/docs/configure-private-google-access#enabling-pga) and the cal-itp-data-infra-staging project's default service account (`473674835135-compute@developer.gserviceaccount.com`) was granted access to the production project since the buckets for compiled Python models (`gs://calitp-dbt-python-models` and `gs://test-calitp-dbt-python-models`) as well as external tables exist in the production project. ## Run with VS Code Dev Containers This repository comes with a [Dev Containers](https://containers.dev/) configuration that makes it possible to run everything within VS Code with minimal dependencies, from any operating system. 1. Ensure you have Docker and Docker Compose installed locally 1. Ensure you have the Dev Containers VS Code extension installed: `ms-vscode-remote.remote-containers` 1. If you have never run the DBT project before, create the following directories locally: ```console mkdir ~/.dbt mkdir -p ~/.config/gcloud ``` 1. Open this repository in VS Code 1. When prompted, choose `Reopen in Container` or use the Command Palette: `Ctrl/Cmd` + `Shift` + `P` and type `Dev Containers` 1. If you have never run the DBT project before, once the devcontainer has built and opens, you will be guided through the initialization process for DBT and Google Cloud CLI. You can also run any DBT command from your local machine via Docker Compose. Change into the `.devcontainer/` directory: ```console cd .devcontainer/ ``` Then use `docker compose run` with a `dbt `: ```console docker compose run dbt ``` E.g. ```console docker compose run dbt debug ``` ## Deploying Changes to Production Changes to the dbt project are automatically deployed when relevant changes are merged into `main` through the [Deploy dbt](../.github/workflows/deploy-dbt.yml) GitHub Actions workflow.