Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): add dbt discovery api and run detail tables (#104407)

Tom Owersfb9137056c74
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index e0757131758d..cd94dedf0177 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2324,14 +2324,14 @@ Note: The metamodel index lists 71 entity types; the source syncs 22. The run-ev
## Dbt — gaps
-Today (6): `accounts`, `environments`, `jobs`, `projects`, `runs`, `users`
+Today (16): `accounts`, `audit_logs`, `environments`, `exposures`, `jobs`, `model_historical_runs`, `models`, `projects`, `run_artifacts`, `run_steps`, `runs`, `seeds`, `snapshots`, `sources`, `tests`, `users`
Diffed against: <https://raw.githubusercontent.com/dbt-labs/dbt-cloud-openapi-spec/master/openapi-v2.yaml>
-- [ ] `Discovery API (metadata GraphQL): environment.applied models, tests, sources, snapshots, seeds, exposures, model historical runs, lineage` — model- and test-level state and run history — the resource-grain data every dbt warehouse use case needs, none of which the Admin API exposes (high)
-- [ ] `GET /api/v2/accounts/{account_id}/runs/?include_related=["run_steps"] (and /api/v2/accounts/{account_id}/steps/{id}/)` — per-step timings, commands and status inside the runs we already sync — where run duration actually goes (high)
-- [ ] `GET /api/v2/accounts/{account_id}/runs/{run_id}/artifacts/ and /artifacts/{remainder}` — run_results.json and manifest.json per run, giving model-level execution results and node metadata (high)
-- [ ] `GET /api/v3/accounts/{account_id}/audit-logs/` — who changed jobs, environments and permissions, with timestamps (medium)
+- [x] `Discovery API (metadata GraphQL): environment.applied models, tests, sources, snapshots, seeds, exposures, model historical runs, lineage` — model- and test-level state and run history — the resource-grain data every dbt warehouse use case needs, none of which the Admin API exposes (high)
+- [x] `GET /api/v2/accounts/{account_id}/runs/?include_related=["run_steps"] (and /api/v2/accounts/{account_id}/steps/{id}/)` — per-step timings, commands and status inside the runs we already sync — where run duration actually goes (high)
+- [x] `GET /api/v2/accounts/{account_id}/runs/{run_id}/artifacts/ and /artifacts/{remainder}` — run_results.json and manifest.json per run, giving model-level execution results and node metadata (high)
+- [x] `GET /api/v3/accounts/{account_id}/audit-logs/` — who changed jobs, environments and permissions, with timestamps (medium)
- [ ] `GET /api/v2/accounts/{account_id}/repositories/ and /api/v3/accounts/{account_id}/projects/{project_id}/repositories/` — lookup resolving the repository and branch behind each project we already sync (medium)
- [ ] `GET /api/v3/accounts/{account_id}/connections/ and /api/v3/accounts/{account_id}/projects/{project_id}/connections/` — lookup resolving the warehouse connection each environment points at (medium)
- [ ] `GET /api/v3/accounts/{account_id}/groups/ and /api/v3/accounts/{account_id}/group-permissions/{group_id}/` — group membership and permission assignment for the users we already sync (medium)
@@ -2339,6 +2339,11 @@ Diffed against: <https://raw.githubusercontent.com/dbt-labs/dbt-cloud-openapi-sp
Note: Diffed against the vendor's own OpenAPI specs (openapi-v2.yaml, openapi-v3.yaml in dbt-labs/dbt-cloud-openapi-spec — the files the docs site renders through Stoplight). The Admin API is well covered; the real gap is the separate Discovery API, whose object list (Models, Tests, Sources, Snapshots, Seeds, Exposures, Tags, Packages, Owners, Model historical runs, Lineage, Job) I read from the schema navigation on https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-models. Excluded as config: environment variables, notifications, service tokens, IP restrictions, SCIM, OAuth configurations, webhooks, credentials, extended attributes.
+Note on the ticked entries: three sub-endpoints named above are deliberately not tables.
+`environment.applied.lineage` is an unpaginated list whose node types expose no parent or child references, so it carries no edges and only repeats the identity columns of the six applied-state tables.
+`/steps/{id}/` fetches one step by id and has no list route to enumerate ids from, so the step rows come from the run's `run_steps` instead; that value is documented on the run-detail route, not the runs list, so `run_steps` fans out over run detail.
+`/artifacts/{remainder}` downloads a raw artifact file (JSON or parquet) whose shape follows the project's dbt version, so `run_artifacts` syncs the artifact inventory from the documented list route and the model-level execution results come from the Discovery API tables.
+
## Debugbear — gaps
Today (6): `Annotations`, `PageMetrics`, `Pages`, `Projects`, `RumMetrics`, `RumPageViews`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 66c67e798bb3..d5e98137b270 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -226,7 +226,7 @@ the row lists both.
| datadog | HTTP | requests | ✅ |
| dataforseo | HTTP | requests | ✅ |
| datahub | HTTP | requests | ✅ |
-| dbt | HTTP | requests | ✅ |
+| dbt | HTTP (REST + GraphQL) | requests | ✅ |
| debugbear | HTTP | requests | ✅ |
| decagon | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/canonical_descriptions.py
index 165522fa8628..531d2661d1a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/canonical_descriptions.py
@@ -106,4 +106,239 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"should_start_at": "When a scheduled run was due to start.",
},
},
+ "run_steps": {
+ "description": "A single step within a job run, running one dbt command with its own status and logs.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v2",
+ "columns": {
+ "run_id": "The run the step belongs to.",
+ "run_created_at": "When the parent run was created (queued).",
+ "index": "Position of the step in the run; the first step is 1.",
+ "name": "Display name of the step.",
+ "status": "Numeric step status (1 queued, 3 running, 10 success, 20 error, 30 cancelled).",
+ "account_id": "The account the step belongs to.",
+ "logs": "High-level log output for the step.",
+ "log_path": "Path to the step's log file, when available.",
+ "debug_log_path": "Path to the step's debug log file, when available.",
+ },
+ },
+ "run_artifacts": {
+ "description": "An artifact file a job run produced, such as manifest.json or run_results.json.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v2",
+ "columns": {
+ "run_id": "The run that produced the artifact.",
+ "run_created_at": "When the parent run was created (queued).",
+ "path": "Path of the artifact, relative to the run's artifact root.",
+ },
+ },
+ "audit_logs": {
+ "description": "An audited account event, recording who changed jobs, environments or permissions and when. Enterprise plans only.",
+ "docs_url": "https://docs.getdbt.com/docs/cloud/manage-access/audit-log",
+ "columns": {
+ "id": "Unique identifier for the audit event.",
+ "account_id": "The account the event belongs to.",
+ "created_at": "When the event was recorded.",
+ "event_type": "Machine-readable event type, such as v1.events.job.Update.",
+ "event_label": "Human-readable summary of the event.",
+ "event_context": "Details of what changed, including the affected resource.",
+ "actor": "The user or system that performed the action.",
+ "source": "Where the action came from, such as the web UI or the API.",
+ "service": "The dbt service that emitted the event.",
+ },
+ },
+ "models": {
+ "description": "Current state of a model in a deployment environment, as reported by the Discovery API.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-models",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the model, in the form model.PACKAGE.NAME.",
+ "name": "Name of the model.",
+ "description": "Model description from the project's YAML.",
+ "resourceType": "dbt resource type; always model here.",
+ "packageName": "The dbt package the model is defined in.",
+ "filePath": "Path to the model file in the repository.",
+ "fqn": "Fully qualified dbt name, as a path of package and directory parts.",
+ "database": "Warehouse database the model is built in.",
+ "schema": "Warehouse schema the model is built in.",
+ "alias": "Warehouse relation name, when it differs from the model name.",
+ "relationName": "Fully qualified warehouse relation the model builds.",
+ "materializedType": "How the model is materialized (table, view, incremental, ephemeral).",
+ "modelingLayer": "Modeling layer the model is tagged with, such as staging or marts.",
+ "language": "Language the model is written in (sql or python).",
+ "access": "Model access level (private, protected, public).",
+ "group": "The dbt group that owns the model.",
+ "tags": "Tags applied to the model.",
+ "meta": "Arbitrary metadata declared on the model.",
+ "config": "Resolved dbt config for the model.",
+ "contractEnforced": "Whether the model enforces a data contract.",
+ "columnCount": "Number of columns in the built relation.",
+ "latestVersion": "Latest declared version of a versioned model.",
+ "version": "Version of this model instance.",
+ "releaseVersion": "Release channel of a versioned model (latest, prerelease, old).",
+ "deprecationDate": "Date the model is marked for deprecation.",
+ "isDescriptionInherited": "Whether the description came from an upstream resource.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the model belongs to.",
+ "projectId": "The project the model belongs to.",
+ "environmentId": "The environment this state was read from.",
+ "executionInfo": "Timing and result of the resource's most recent run: last run id, status, error, and the compile/execute timestamps.",
+ },
+ },
+ "tests": {
+ "description": "Current state of a data test in a deployment environment, including its last known result.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-tests",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the test.",
+ "name": "Name of the test.",
+ "description": "Test description from the project's YAML.",
+ "resourceType": "dbt resource type; always test here.",
+ "testType": "Kind of test (generic data test, singular data test, unit test).",
+ "lastKnownResult": "Most recent result: pass, fail, error, warn or skipped.",
+ "columnName": "Column the test asserts on, for column-level tests.",
+ "model": "Name of the resource the test is attached to.",
+ "testedNodeUniqueId": "Unique ID of the resource the test asserts on.",
+ "filePath": "Path to the file the test is defined in.",
+ "fqn": "Fully qualified dbt name of the test.",
+ "tags": "Tags applied to the test.",
+ "meta": "Arbitrary metadata declared on the test.",
+ "config": "Resolved dbt config for the test, including severity and thresholds.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the test belongs to.",
+ "projectId": "The project the test belongs to.",
+ "environmentId": "The environment this state was read from.",
+ "executionInfo": "Timing and result of the test's most recent run, including how many rows failed.",
+ },
+ },
+ "sources": {
+ "description": "Current state of a source table in a deployment environment, including its freshness check.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-sources",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the source table.",
+ "name": "Name of the source table.",
+ "description": "Table description from the project's YAML.",
+ "resourceType": "dbt resource type; always source here.",
+ "sourceName": "Name of the source the table belongs to.",
+ "sourceDescription": "Description of the parent source.",
+ "identifier": "Warehouse table name, when it differs from the source table name.",
+ "loader": "Tool declared as loading the table.",
+ "database": "Warehouse database the table lives in.",
+ "schema": "Warehouse schema the table lives in.",
+ "filePath": "Path to the file the source is defined in.",
+ "fqn": "Fully qualified dbt name of the source table.",
+ "tags": "Tags applied to the source table.",
+ "meta": "Arbitrary metadata declared on the source table.",
+ "columnCount": "Number of columns in the source table.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the source belongs to.",
+ "projectId": "The project the source belongs to.",
+ "environmentId": "The environment this state was read from.",
+ "freshness": "Result of the last source freshness check, including status and the newest loaded timestamp.",
+ },
+ },
+ "snapshots": {
+ "description": "Current state of a snapshot in a deployment environment, including its last run result.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-snapshots",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the snapshot.",
+ "name": "Name of the snapshot.",
+ "description": "Snapshot description from the project's YAML.",
+ "resourceType": "dbt resource type; always snapshot here.",
+ "packageName": "The dbt package the snapshot is defined in.",
+ "filePath": "Path to the snapshot file in the repository.",
+ "fqn": "Fully qualified dbt name of the snapshot.",
+ "database": "Warehouse database the snapshot is built in.",
+ "schema": "Warehouse schema the snapshot is built in.",
+ "alias": "Warehouse relation name, when it differs from the snapshot name.",
+ "tags": "Tags applied to the snapshot.",
+ "meta": "Arbitrary metadata declared on the snapshot.",
+ "config": "Resolved dbt config for the snapshot, including its strategy and keys.",
+ "columnCount": "Number of columns in the built relation.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the snapshot belongs to.",
+ "projectId": "The project the snapshot belongs to.",
+ "environmentId": "The environment this state was read from.",
+ "executionInfo": "Timing and result of the resource's most recent run: last run id, status, error, and the compile/execute timestamps.",
+ },
+ },
+ "seeds": {
+ "description": "Current state of a seed in a deployment environment, including its last run result.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-seeds",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the seed.",
+ "name": "Name of the seed.",
+ "description": "Seed description from the project's YAML.",
+ "resourceType": "dbt resource type; always seed here.",
+ "packageName": "The dbt package the seed is defined in.",
+ "filePath": "Path to the seed file in the repository.",
+ "fqn": "Fully qualified dbt name of the seed.",
+ "database": "Warehouse database the seed is loaded into.",
+ "schema": "Warehouse schema the seed is loaded into.",
+ "alias": "Warehouse relation name, when it differs from the seed name.",
+ "tags": "Tags applied to the seed.",
+ "meta": "Arbitrary metadata declared on the seed.",
+ "columnCount": "Number of columns in the loaded relation.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the seed belongs to.",
+ "projectId": "The project the seed belongs to.",
+ "environmentId": "The environment this state was read from.",
+ "executionInfo": "Timing and result of the seed's most recent run, including whether it was skipped.",
+ },
+ },
+ "exposures": {
+ "description": "A downstream use of the project's data, such as a dashboard, report or application declared as an exposure.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-exposures",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the exposure.",
+ "name": "Name of the exposure.",
+ "label": "Display label for the exposure.",
+ "description": "Exposure description from the project's YAML.",
+ "resourceType": "dbt resource type; always exposure here.",
+ "exposureType": "Kind of exposure (dashboard, notebook, analysis, ml, application).",
+ "maturity": "Declared maturity of the exposure (low, medium, high).",
+ "url": "Link to the exposure.",
+ "ownerName": "Name of the exposure's owner.",
+ "ownerEmail": "Email address of the exposure's owner.",
+ "packageName": "The dbt package the exposure is defined in.",
+ "filePath": "Path to the file the exposure is defined in.",
+ "fqn": "Fully qualified dbt name of the exposure.",
+ "tags": "Tags applied to the exposure.",
+ "meta": "Arbitrary metadata declared on the exposure.",
+ "manifestGeneratedAt": "When the manifest this state came from was generated.",
+ "dbtVersion": "dbt version that produced this state.",
+ "accountId": "The account the exposure belongs to.",
+ "projectId": "The project the exposure belongs to.",
+ "environmentId": "The environment this state was read from.",
+ },
+ },
+ "model_historical_runs": {
+ "description": "One execution of one model. This is the per-model build history behind a run's total duration.",
+ "docs_url": "https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-modelHistoricalRuns",
+ "columns": {
+ "uniqueId": "Stable dbt identifier for the model.",
+ "name": "Name of the model.",
+ "alias": "Warehouse relation name, when it differs from the model name.",
+ "database": "Warehouse database the model was built in.",
+ "schema": "Warehouse schema the model was built in.",
+ "resourceType": "dbt resource type; always model here.",
+ "materializedType": "How the model was materialized for this run.",
+ "language": "Language the model is written in (sql or python).",
+ "packageName": "The dbt package the model is defined in.",
+ "runId": "The run this execution belongs to.",
+ "jobId": "The job that produced the run.",
+ "invocationId": "Identifier of the dbt invocation within the run.",
+ "threadId": "Thread that executed the model.",
+ "status": "Outcome of this execution (success, error, skipped).",
+ "error": "Error message, when the execution failed.",
+ "skip": "Whether the model was skipped in this run.",
+ "compileStartedAt": "When compilation of the model started.",
+ "compileCompletedAt": "When compilation of the model finished.",
+ "executeStartedAt": "When execution of the model started.",
+ "executeCompletedAt": "When execution of the model finished.",
+ "executionTime": "Seconds the model took to execute.",
+ "runElapsedTime": "Seconds elapsed in the run when the model finished.",
+ "runGeneratedAt": "When the run's artifacts were generated.",
+ "dbtVersion": "dbt version used for the run.",
+ "accountId": "The account the model belongs to.",
+ "projectId": "The project the model belongs to.",
+ "environmentId": "The environment this run executed in.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/dbt.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/dbt.py
index 04fa134c8b46..7d941c82b3dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/dbt.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/dbt.py
@@ -1,4 +1,4 @@
-import dataclasses
+import json
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -8,19 +8,33 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.queries import (
+ DISCOVERY_VALIDATION_QUERY,
+ MODEL_UNIQUE_IDS_QUERY,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.settings import (
+ DBT_DISCOVERY_PAGE_SIZE,
+ DBT_DISCOVERY_REGION_URLS,
DBT_ENDPOINTS,
+ DBT_MODEL_HISTORICAL_RUN_COUNT,
DBT_PAGE_LIMIT,
DBT_REGION_BASE_URLS,
DbtEndpointConfig,
+ DbtRunFanoutConfig,
)
HOST_NOT_ALLOWED_ERROR = "The dbt base URL is not allowed"
+# Prefix of the error raised when the Discovery API refuses the token. The GraphQL service answers
+# an auth failure with HTTP 200 and an `errors` body, so there is no status text to match on.
+DISCOVERY_TOKEN_ERROR = "dbt Discovery API rejected the token"
+
class DbtRetryableError(Exception):
pass
@@ -30,12 +44,17 @@ class DbtHostNotAllowedError(Exception):
pass
+@frozen
class DbtResumeConfig:
# Row offset of the next page to fetch. Resuming mid-list is safe against rows landing between
# attempts: runs are walked newest-first, so inserts shift already-read rows deeper and a resume
# at the saved offset re-reads them (merge dedupes on the primary key) rather than skipping.
offset: int = 0
+ # Fan-out progress: the offset into the runs list, or the index into the environment list,
+ # whose children were being expanded.
+ parent_offset: int = 0
+ # Discovery API page cursor within the parent being expanded.
+ cursor: Optional[str] = None
def get_base_url(region: str, custom_base_url: str | None) -> str:
@@ -48,6 +67,21 @@ def get_base_url(region: str, custom_base_url: str | None) -> str:
return DBT_REGION_BASE_URLS.get(region, DBT_REGION_BASE_URLS["us"])
+def get_discovery_url(region: str, discovery_api_url: str | None) -> str:
+ """Resolve the Discovery API (GraphQL) URL from the region select, or a user-supplied URL.
+
+ Cell-based and single-tenant deployments prefix the account onto the metadata hostname
+ (``https://ab123.metadata.us1.dbt.com/graphql``), which can't be derived from the Admin API
+ base URL, so those users enter it themselves.
+ """
+ if discovery_api_url and discovery_api_url.strip():
+ url = discovery_api_url.strip().rstrip("/")
+ if not url.startswith("https://"):
+ raise DbtHostNotAllowedError("Custom dbt Discovery API URL must start with https://")
+ return url
+ return DBT_DISCOVERY_REGION_URLS.get(region, DBT_DISCOVERY_REGION_URLS["us"])
+
+
def _check_host_safety(base_url: str, custom_base_url: str | None, team_id: int) -> tuple[bool, str | None]:
"""Block custom base URLs that resolve to private/internal addresses (SSRF).
@@ -86,6 +120,7 @@ def validate_credentials(
custom_base_url: str | None,
team_id: Optional[int] = None,
schema_name: Optional[str] = None,
+ discovery_api_url: str | None = None,
) -> tuple[bool, str | None]:
"""Probe the account endpoint to confirm the token is genuine and can reach the account.
@@ -94,6 +129,7 @@ def validate_credentials(
"""
try:
base_url = get_base_url(region, custom_base_url)
+ discovery_url = get_discovery_url(region, discovery_api_url)
except DbtHostNotAllowedError as e:
return False, str(e)
@@ -101,6 +137,9 @@ def validate_credentials(
host_ok, host_err = _check_host_safety(base_url, custom_base_url, team_id)
if not host_ok:
return False, host_err or HOST_NOT_ALLOWED_ERROR
+ discovery_ok, discovery_err = _check_host_safety(discovery_url, discovery_api_url, team_id)
+ if not discovery_ok:
+ return False, discovery_err or HOST_NOT_ALLOWED_ERROR
url = f"{base_url}/api/v2/accounts/{account_id}/"
try:
@@ -131,6 +170,119 @@ def validate_credentials(
return False, _status_message(response)
+def _raise_for_graphql_errors(payload: dict[str, Any]) -> None:
+ """Classify a Discovery API response body, which reports failures with HTTP 200 + `errors`."""
+ errors = payload.get("errors")
+ if not errors:
+ if "data" not in payload:
+ raise Exception(f"Unexpected dbt Discovery API response. Keys: {sorted(payload.keys())}")
+ return
+
+ messages = "; ".join(str(error.get("message", "")) for error in errors)
+ lowered = messages.lower()
+ if "rate limit" in lowered or "too many requests" in lowered:
+ raise DbtRetryableError(f"dbt Discovery API rate limited: {messages}")
+ if any(word in lowered for word in ("token", "unauthorized", "forbidden", "permission")):
+ raise Exception(f"{DISCOVERY_TOKEN_ERROR}: {messages}")
+ raise Exception(f"dbt Discovery API error: {messages}")
+
+
+@retry(
+ retry=retry_if_exception_type(DbtRetryableError),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _post_graphql(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ try:
+ response = session.post(
+ url,
+ headers=headers,
+ json={"query": query, "variables": variables},
+ timeout=60,
+ allow_redirects=False,
+ )
+ except (requests.ConnectionError, requests.Timeout) as e:
+ # The session's transport-level retries only cover idempotent methods, so these POSTs get
+ # none. Fold transient network failures into this backoff instead.
+ raise DbtRetryableError(f"dbt Discovery API: transient network error - {e}")
+
+ if response.is_redirect or response.is_permanent_redirect:
+ raise DbtHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DbtRetryableError(f"dbt Discovery API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"dbt Discovery API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ payload = response.json()
+ _raise_for_graphql_errors(payload)
+ return payload.get("data") or {}
+
+
+def _probe_discovery_access(
+ session: requests.Session,
+ headers: dict[str, str],
+ region: str,
+ discovery_api_url: str | None,
+ team_id: int,
+ endpoints: list[str],
+) -> str | None:
+ """Check once whether the token reaches the Discovery API, for the schema picker.
+
+ Admin API tokens are not automatically accepted by the metadata service, so this catches the
+ common case of a token that can list jobs and runs but cannot read project state.
+ """
+ configs = [DBT_ENDPOINTS[endpoint] for endpoint in endpoints if endpoint in DBT_ENDPOINTS]
+ if not any(config.discovery is not None for config in configs):
+ return None
+
+ try:
+ discovery_url = get_discovery_url(region, discovery_api_url)
+ except DbtHostNotAllowedError as e:
+ return str(e)
+
+ host_ok, host_err = _check_host_safety(discovery_url, discovery_api_url, team_id)
+ if not host_ok:
+ return host_err or HOST_NOT_ALLOWED_ERROR
+
+ try:
+ response = session.post(
+ discovery_url,
+ headers=headers,
+ json={"query": DISCOVERY_VALIDATION_QUERY},
+ timeout=10,
+ allow_redirects=False,
+ )
+ except requests.exceptions.RequestException:
+ # A blip is not a denial.
+ return None
+
+ if response.status_code in (401, 403):
+ return "Your dbt API token cannot read the Discovery API"
+ if not response.ok:
+ return None
+
+ try:
+ payload = response.json()
+ except Exception:
+ return None
+
+ errors = payload.get("errors") or []
+ if errors:
+ return errors[0].get("message") or "Your dbt API token cannot read the Discovery API"
+ return None
+
+
def get_endpoint_permissions(
api_token: str,
account_id: str,
@@ -138,6 +290,7 @@ def get_endpoint_permissions(
custom_base_url: str | None,
team_id: int,
endpoints: list[str],
+ discovery_api_url: str | None = None,
) -> dict[str, str | None]:
"""Probe each endpoint with limit=1 so the schema picker can flag tables the token can't read.
@@ -158,12 +311,20 @@ def get_endpoint_permissions(
session = make_tracked_session()
headers = _get_headers(api_token)
results: dict[str, str | None] = {}
+ discovery_error = _probe_discovery_access(session, headers, region, discovery_api_url, team_id, endpoints)
for endpoint in endpoints:
config = DBT_ENDPOINTS.get(endpoint)
if config is None:
results[endpoint] = None
continue
- url = f"{base_url}/api{config.path.format(account_id=account_id)}?limit=1"
+ if config.discovery is not None:
+ results[endpoint] = discovery_error
+ continue
+ # A run fan-out reads the runs list plus a per-run route; the list is the permission that
+ # decides whether the table can sync at all.
+ probe_path = config.path if config.path is not None else DBT_ENDPOINTS["runs"].path
+ assert probe_path is not None
+ url = f"{base_url}/api{probe_path.format(account_id=account_id)}?limit=1"
try:
response = session.get(url, headers=headers, timeout=10, allow_redirects=False)
except requests.exceptions.RequestException:
@@ -233,6 +394,312 @@ def _build_params(config: DbtEndpointConfig, incremental_field: str | None, walk
return params
+@frozen
+class _ListPage:
+ rows: list[dict[str, Any]]
+ next_offset: int
+ has_more: bool
+
+
+def _iter_offset_pages(
+ session: requests.Session,
+ base_url: str,
+ path: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ start_offset: int = 0,
+) -> Iterator[_ListPage]:
+ """Walk a dbt limit/offset list endpoint."""
+ offset = start_offset
+ while True:
+ url = f"{base_url}/api{path}?{urlencode({**params, 'offset': offset})}"
+ data = _fetch_page(session, url, headers, logger)
+
+ rows = data.get("data") or []
+ if not rows:
+ return
+
+ pagination = (data.get("extra") or {}).get("pagination") or {}
+ count = pagination.get("count", len(rows))
+ total_count = pagination.get("total_count")
+ next_offset = offset + count
+ has_more = count >= DBT_PAGE_LIMIT and not (total_count is not None and next_offset >= total_count)
+
+ yield _ListPage(rows=rows, next_offset=next_offset, has_more=has_more)
+
+ if not has_more:
+ return
+ offset = next_offset
+
+
+def _rows_above_watermark(rows: list[dict[str, Any]], cursor_field: str, watermark: datetime) -> list[dict[str, Any]]:
+ """Keep the rows newer than the watermark. Rows with no parseable cursor value are kept."""
+ return [
+ row for row in rows if (row_value := _coerce_datetime(row.get(cursor_field))) is None or row_value > watermark
+ ]
+
+
+def _fetch_run_children(
+ session: requests.Session,
+ base_url: str,
+ account_id: str,
+ fanout: DbtRunFanoutConfig,
+ run: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ run_id = run.get("id")
+ if run_id is None:
+ return []
+
+ url = f"{base_url}/api{fanout.path.format(account_id=account_id, run_id=run_id)}"
+ if fanout.include_related:
+ # dbt expects a JSON array literal here, not repeated query params.
+ url = f"{url}?{urlencode({'include_related': json.dumps(list(fanout.include_related))})}"
+
+ try:
+ data = _fetch_page(session, url, headers, logger)
+ except requests.HTTPError as e:
+ if e.response is not None and e.response.status_code == 404:
+ # Runs age out and cancelled runs never produce artifacts; skip rather than fail the sync.
+ return []
+ raise
+
+ payload = data.get("data")
+ if fanout.data_selector is not None:
+ children = (payload or {}).get(fanout.data_selector) or []
+ else:
+ children = payload or []
+
+ # run_created_at carries the parent's immutable creation time so the child table has a cursor
+ # and a partition key of its own.
+ parent_fields = {"run_id": run_id, "run_created_at": run.get("created_at")}
+ if fanout.string_row_field is not None:
+ return [{**parent_fields, fanout.string_row_field: child} for child in children]
+ return [{**child, **parent_fields} for child in children]
+
+
+def _iter_run_fanout_rows(
+ session: requests.Session,
+ base_url: str,
+ account_id: str,
+ config: DbtEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DbtResumeConfig],
+ resume: DbtResumeConfig | None,
+ watermark: datetime | None,
+) -> Iterator[Any]:
+ """Expand a child resource of every run in the incremental window.
+
+ The runs list is walked newest-first and stopped at the watermark, so an incremental sync only
+ fans out over runs it has not expanded before.
+ """
+ fanout = config.run_fanout
+ assert fanout is not None
+ runs_path = DBT_ENDPOINTS["runs"].path
+ assert runs_path is not None
+
+ params = {"limit": DBT_PAGE_LIMIT, "order_by": "-created_at"}
+ for page in _iter_offset_pages(
+ session,
+ base_url,
+ runs_path.format(account_id=account_id),
+ params,
+ headers,
+ logger,
+ start_offset=resume.parent_offset if resume is not None else 0,
+ ):
+ runs = page.rows
+ kept_runs = runs if watermark is None else _rows_above_watermark(runs, "created_at", watermark)
+
+ batch: list[dict[str, Any]] = []
+ for run in kept_runs:
+ batch.extend(_fetch_run_children(session, base_url, account_id, fanout, run, headers, logger))
+ if batch:
+ yield batch
+
+ if len(kept_runs) < len(runs):
+ break
+ if page.has_more:
+ resumable_source_manager.save_state(DbtResumeConfig(parent_offset=page.next_offset))
+
+
+def _deployment_environment_ids(
+ session: requests.Session,
+ base_url: str,
+ account_id: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[int]:
+ """List the environments the Discovery API can report applied state for.
+
+ Development environments have no applied state, so querying them would spend a request per
+ environment to get nothing back.
+ """
+ path = DBT_ENDPOINTS["environments"].path
+ assert path is not None
+
+ environment_ids: list[int] = []
+ for page in _iter_offset_pages(
+ session, base_url, path.format(account_id=account_id), {"limit": DBT_PAGE_LIMIT}, headers, logger
+ ):
+ environment_ids.extend(
+ row["id"] for row in page.rows if row.get("id") is not None and row.get("type") == "deployment"
+ )
+ return environment_ids
+
+
+def _next_page_cursor(page_info: dict[str, Any], cursor: str | None, context: str) -> str | None:
+ """Resolve the cursor of the next page, or None at the end of the connection.
+
+ A connection that claims another page but hands back no cursor, or the same one again, would
+ make the caller re-request the page it just read until the activity times out. Fail instead:
+ silently ending the walk would write a partial table that reads as complete.
+ """
+ if not page_info.get("hasNextPage"):
+ return None
+ next_cursor = page_info.get("endCursor")
+ if not next_cursor or next_cursor == cursor:
+ raise Exception(f"dbt Discovery API reported another page without advancing the cursor. {context}")
+ return next_cursor
+
+
+def _iter_discovery_pages(
+ session: requests.Session,
+ discovery_url: str,
+ headers: dict[str, str],
+ config: DbtEndpointConfig,
+ environment_id: int,
+ start_cursor: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Walk one environment's applied-state connection, yielding (rows, cursor of the next page)."""
+ discovery = config.discovery
+ assert discovery is not None
+
+ cursor = start_cursor
+ while True:
+ data = _post_graphql(
+ session,
+ discovery_url,
+ headers,
+ discovery.query,
+ {"environmentId": environment_id, "first": DBT_DISCOVERY_PAGE_SIZE, "after": cursor},
+ logger,
+ )
+ applied = ((data.get("environment") or {}).get("applied")) or {}
+ connection = applied.get(discovery.applied_field) or {}
+ rows = [edge["node"] for edge in (connection.get("edges") or []) if edge.get("node")]
+
+ page_info = connection.get("pageInfo") or {}
+ next_cursor = _next_page_cursor(
+ page_info, cursor, f"field={discovery.applied_field}, environment={environment_id}"
+ )
+
+ yield rows, next_cursor
+
+ if next_cursor is None:
+ return
+ cursor = next_cursor
+
+
+def _iter_model_historical_run_pages(
+ session: requests.Session,
+ discovery_url: str,
+ headers: dict[str, str],
+ config: DbtEndpointConfig,
+ environment_id: int,
+ start_cursor: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Walk the environment's models, asking each one for its run history.
+
+ modelHistoricalRuns takes a single model at a time, so the page cursor tracks the model list
+ and each page costs one request per model in it.
+ """
+ discovery = config.discovery
+ assert discovery is not None
+
+ cursor = start_cursor
+ while True:
+ data = _post_graphql(
+ session,
+ discovery_url,
+ headers,
+ MODEL_UNIQUE_IDS_QUERY,
+ {"environmentId": environment_id, "first": DBT_DISCOVERY_PAGE_SIZE, "after": cursor},
+ logger,
+ )
+ applied = ((data.get("environment") or {}).get("applied")) or {}
+ connection = applied.get("models") or {}
+ unique_ids = [
+ unique_id
+ for edge in (connection.get("edges") or [])
+ if (unique_id := (edge.get("node") or {}).get("uniqueId"))
+ ]
+
+ rows: list[dict[str, Any]] = []
+ for unique_id in unique_ids:
+ run_data = _post_graphql(
+ session,
+ discovery_url,
+ headers,
+ discovery.query,
+ {
+ "environmentId": environment_id,
+ "uniqueId": unique_id,
+ "lastRunCount": DBT_MODEL_HISTORICAL_RUN_COUNT,
+ },
+ logger,
+ )
+ run_applied = ((run_data.get("environment") or {}).get("applied")) or {}
+ rows.extend(run_applied.get(discovery.applied_field) or [])
+
+ page_info = connection.get("pageInfo") or {}
+ next_cursor = _next_page_cursor(page_info, cursor, f"field=models, environment={environment_id}")
+
+ yield rows, next_cursor
+
+ if next_cursor is None:
+ return
+ cursor = next_cursor
+
+
+def _iter_discovery_rows(
+ session: requests.Session,
+ base_url: str,
+ discovery_url: str,
+ account_id: str,
+ config: DbtEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DbtResumeConfig],
+ resume: DbtResumeConfig | None,
+) -> Iterator[Any]:
+ discovery = config.discovery
+ assert discovery is not None
+
+ environment_ids = _deployment_environment_ids(session, base_url, account_id, headers, logger)
+ start_index = resume.parent_offset if resume is not None else 0
+ walk = _iter_model_historical_run_pages if discovery.per_model else _iter_discovery_pages
+
+ for index in range(start_index, len(environment_ids)):
+ environment_id = environment_ids[index]
+ start_cursor = resume.cursor if resume is not None and index == start_index else None
+
+ for rows, next_cursor in walk(session, discovery_url, headers, config, environment_id, start_cursor, logger):
+ if rows:
+ # environmentId is part of the primary key, so it is stamped from the environment
+ # being queried rather than trusted to be resolved on every node type.
+ yield [{**row, "environmentId": environment_id} for row in rows]
+ if next_cursor is not None:
+ resumable_source_manager.save_state(DbtResumeConfig(parent_offset=index, cursor=next_cursor))
+ if index + 1 < len(environment_ids):
+ resumable_source_manager.save_state(DbtResumeConfig(parent_offset=index + 1))
+
+
def get_rows(
api_token: str,
account_id: str,
@@ -245,19 +712,24 @@ def get_rows(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
incremental_field: str | None = None,
+ discovery_api_url: str | None = None,
) -> Iterator[Any]:
config = DBT_ENDPOINTS[endpoint]
base_url = get_base_url(region, custom_base_url)
+ discovery_url = get_discovery_url(region, discovery_api_url) if config.discovery else None
# Re-check at run time (not just at source-create) in case the URL was edited or now resolves
# to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
host_ok, host_err = _check_host_safety(base_url, custom_base_url, team_id)
if not host_ok:
raise DbtHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+ if discovery_url is not None:
+ discovery_ok, discovery_err = _check_host_safety(discovery_url, discovery_api_url, team_id)
+ if not discovery_ok:
+ raise DbtHostNotAllowedError(discovery_err or HOST_NOT_ALLOWED_ERROR)
session = make_tracked_session()
headers = _get_headers(api_token)
- path = config.path.format(account_id=account_id)
cursor_field = incremental_field or config.default_incremental_field
watermark: datetime | None = None
@@ -266,49 +738,67 @@ def get_rows(
if watermark is not None and config.incremental_lookback is not None:
watermark -= config.incremental_lookback
- walking_desc = config.sort_mode == "desc" and cursor_field is not None
- params = _build_params(config, incremental_field, walking_desc)
-
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- offset = resume.offset if resume is not None else 0
if resume is not None:
- logger.debug(f"dbt: resuming {endpoint} from offset={offset}")
-
- while True:
- url = f"{base_url}/api{path}?{urlencode({**params, 'offset': offset})}"
- data = _fetch_page(session, url, headers, logger)
+ logger.debug(f"dbt: resuming {endpoint} from {resume}")
+
+ if discovery_url is not None:
+ yield from _iter_discovery_rows(
+ session,
+ base_url,
+ discovery_url,
+ account_id,
+ config,
+ headers,
+ logger,
+ resumable_source_manager,
+ resume,
+ )
+ return
+
+ if config.run_fanout is not None:
+ yield from _iter_run_fanout_rows(
+ session,
+ base_url,
+ account_id,
+ config,
+ headers,
+ logger,
+ resumable_source_manager,
+ resume,
+ watermark,
+ )
+ return
- rows = data.get("data") or []
- if not rows:
- break
+ path = config.path
+ assert path is not None
+ walking_desc = config.sort_mode == "desc" and cursor_field is not None
+ params = _build_params(config, incremental_field, walking_desc)
+ for page in _iter_offset_pages(
+ session,
+ base_url,
+ path.format(account_id=account_id),
+ params,
+ headers,
+ logger,
+ start_offset=resume.offset if resume is not None else 0,
+ ):
if watermark is not None and cursor_field is not None:
# Newest-first walk: keep rows above the watermark and stop as soon as the page dips
- # below it — everything past that point was synced by a previous run. Rows with a
- # missing/unparseable cursor value are kept to stay on the safe side.
- kept = [
- row
- for row in rows
- if (row_value := _coerce_datetime(row.get(cursor_field))) is None or row_value > watermark
- ]
+ # below it — everything past that point was synced by a previous run.
+ kept = _rows_above_watermark(page.rows, cursor_field, watermark)
if kept:
yield kept
- if len(kept) < len(rows):
+ if len(kept) < len(page.rows):
break
else:
- yield rows
-
- pagination = (data.get("extra") or {}).get("pagination") or {}
- count = pagination.get("count", len(rows))
- total_count = pagination.get("total_count")
- offset += count
-
- if count < DBT_PAGE_LIMIT or (total_count is not None and offset >= total_count):
- break
+ yield page.rows
# Save AFTER yielding (and only when more pages remain) so a crash re-yields the last page
# rather than skipping it — merge dedupes on the primary key.
- resumable_source_manager.save_state(DbtResumeConfig(offset=offset))
+ if page.has_more:
+ resumable_source_manager.save_state(DbtResumeConfig(offset=page.next_offset))
def dbt_source(
@@ -323,6 +813,7 @@ def dbt_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
+ discovery_api_url: str | None = None,
) -> SourceResponse:
endpoint_config = DBT_ENDPOINTS[endpoint]
@@ -340,6 +831,7 @@ def dbt_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
incremental_field=incremental_field,
+ discovery_api_url=discovery_api_url,
),
primary_keys=endpoint_config.primary_keys,
# Runs are walked newest-first (order_by=-created_at), so the incremental watermark only
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/queries.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/queries.py
new file mode 100644
index 000000000000..152f5bfcb342
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/queries.py
@@ -0,0 +1,342 @@
+# Hand-written GraphQL documents against the dbt Discovery API (the metadata service), which is a
+# separate API from the Admin API the rest of this source reads. Field sets are kept to scalars and
+# the well-known nested execution/freshness objects: the docs warn that nested nodes, raw code and
+# catalog columns count against a per-query complexity limit, so those are left out deliberately.
+#
+# https://docs.getdbt.com/docs/dbt-cloud-apis/discovery-schema-environment-applied-models
+
+# Cheap probe for the Discovery URL: a bad token is rejected at the gateway before any resolver
+# runs, so this never depends on which permission set the token carries.
+DISCOVERY_VALIDATION_QUERY = "query { __typename }"
+
+_EXECUTION_INFO = """
+ executionInfo {
+ lastRunId
+ lastRunStatus
+ lastRunError
+ lastRunGeneratedAt
+ lastSuccessRunId
+ lastJobDefinitionId
+ compileStartedAt
+ compileCompletedAt
+ executeStartedAt
+ executeCompletedAt
+ executionTime
+ runElapsedTime
+ runGeneratedAt
+ }"""
+
+MODELS_QUERY = (
+ """
+query AppliedModels($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ models(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ description
+ resourceType
+ packageName
+ filePath
+ fqn
+ database
+ schema
+ alias
+ relationName
+ materializedType
+ modelingLayer
+ language
+ access
+ group
+ tags
+ meta
+ config
+ contractEnforced
+ columnCount
+ latestVersion
+ version
+ releaseVersion
+ deprecationDate
+ isDescriptionInherited
+ dbtVersion
+ accountId
+ projectId
+ environmentId"""
+ + _EXECUTION_INFO
+ + """
+ }
+ }
+ }
+ }
+ }
+}"""
+)
+
+TESTS_QUERY = """
+query AppliedTests($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ tests(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ description
+ resourceType
+ testType
+ lastKnownResult
+ columnName
+ model
+ testedNodeUniqueId
+ filePath
+ fqn
+ tags
+ meta
+ config
+ dbtVersion
+ accountId
+ projectId
+ environmentId
+ executionInfo {
+ lastRunId
+ lastRunStatus
+ lastRunError
+ lastRunFailures
+ lastRunGeneratedAt
+ lastSuccessRunId
+ lastJobDefinitionId
+ compileStartedAt
+ compileCompletedAt
+ executeStartedAt
+ executeCompletedAt
+ executionTime
+ runElapsedTime
+ runGeneratedAt
+ }
+ }
+ }
+ }
+ }
+ }
+}"""
+
+SOURCES_QUERY = """
+query AppliedSources($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ sources(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ description
+ resourceType
+ sourceName
+ sourceDescription
+ identifier
+ loader
+ database
+ schema
+ filePath
+ fqn
+ tags
+ meta
+ columnCount
+ dbtVersion
+ accountId
+ projectId
+ environmentId
+ freshness {
+ freshnessChecked
+ freshnessStatus
+ freshnessJobDefinitionId
+ freshnessRunId
+ freshnessRunGeneratedAt
+ maxLoadedAt
+ maxLoadedAtTimeAgoInS
+ snapshottedAt
+ }
+ }
+ }
+ }
+ }
+ }
+}"""
+
+SNAPSHOTS_QUERY = (
+ """
+query AppliedSnapshots($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ snapshots(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ description
+ resourceType
+ packageName
+ filePath
+ fqn
+ database
+ schema
+ alias
+ tags
+ meta
+ config
+ columnCount
+ dbtVersion
+ accountId
+ projectId
+ environmentId"""
+ + _EXECUTION_INFO
+ + """
+ }
+ }
+ }
+ }
+ }
+}"""
+)
+
+# SeedAppliedStateNode carries no `config`, and its executionInfo adds `lastRunSkip`, so the seed
+# field set is spelled out rather than sharing the model/snapshot one.
+SEEDS_QUERY = """
+query AppliedSeeds($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ seeds(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ description
+ resourceType
+ packageName
+ filePath
+ fqn
+ database
+ schema
+ alias
+ tags
+ meta
+ columnCount
+ dbtVersion
+ accountId
+ projectId
+ environmentId
+ executionInfo {
+ lastRunId
+ lastRunStatus
+ lastRunError
+ lastRunSkip
+ lastRunGeneratedAt
+ lastSuccessRunId
+ lastJobDefinitionId
+ compileStartedAt
+ compileCompletedAt
+ executeStartedAt
+ executeCompletedAt
+ executionTime
+ runElapsedTime
+ runGeneratedAt
+ }
+ }
+ }
+ }
+ }
+ }
+}"""
+
+EXPOSURES_QUERY = """
+query AppliedExposures($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ exposures(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges {
+ node {
+ uniqueId
+ name
+ label
+ description
+ resourceType
+ exposureType
+ maturity
+ url
+ ownerName
+ ownerEmail
+ packageName
+ filePath
+ fqn
+ tags
+ meta
+ manifestGeneratedAt
+ dbtVersion
+ accountId
+ projectId
+ environmentId
+ }
+ }
+ }
+ }
+ }
+}"""
+
+# modelHistoricalRuns takes one model at a time, so the model list is walked first to collect the
+# unique IDs to ask about.
+MODEL_UNIQUE_IDS_QUERY = """
+query AppliedModelUniqueIds($environmentId: BigInt!, $first: Int!, $after: String) {
+ environment(id: $environmentId) {
+ applied {
+ models(first: $first, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ edges { node { uniqueId } }
+ }
+ }
+ }
+}"""
+
+MODEL_HISTORICAL_RUNS_QUERY = """
+query ModelHistoricalRuns($environmentId: BigInt!, $uniqueId: String!, $lastRunCount: Int!) {
+ environment(id: $environmentId) {
+ applied {
+ modelHistoricalRuns(uniqueId: $uniqueId, lastRunCount: $lastRunCount) {
+ uniqueId
+ name
+ alias
+ database
+ schema
+ resourceType
+ materializedType
+ language
+ packageName
+ runId
+ jobId
+ invocationId
+ threadId
+ status
+ error
+ skip
+ compileStartedAt
+ compileCompletedAt
+ executeStartedAt
+ executeCompletedAt
+ executionTime
+ runElapsedTime
+ runGeneratedAt
+ dbtVersion
+ accountId
+ projectId
+ environmentId
+ }
+ }
+ }
+}"""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/settings.py
index c1d199978dcd..5d7093bdab26 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/settings.py
@@ -1,8 +1,19 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from datetime import timedelta
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.queries import (
+ EXPOSURES_QUERY,
+ MODEL_HISTORICAL_RUNS_QUERY,
+ MODELS_QUERY,
+ SEEDS_QUERY,
+ SNAPSHOTS_QUERY,
+ SOURCES_QUERY,
+ TESTS_QUERY,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# dbt Cloud's Administrative API runs two live versions: v3 (the vendor's recommended version) and
@@ -27,13 +38,66 @@ DBT_REGION_BASE_URLS: dict[str, str] = {
# dbt Cloud caps limit/offset pagination at 100 rows per request.
DBT_PAGE_LIMIT = 100
+# The Discovery API (model/test/source state and run history) is a separate GraphQL service on its
+# own per-region hostname. Cell-based and single-tenant deployments prefix the account, so those
+# users supply the URL directly instead (see the discovery_api_url source field).
+DBT_DISCOVERY_REGION_URLS: dict[str, str] = {
+ "us": "https://metadata.cloud.getdbt.com/graphql",
+ "emea": "https://metadata.emea.dbt.com/graphql",
+ "au": "https://metadata.au.dbt.com/graphql",
+}
+
+# Discovery API connections accept up to 500 nodes per page; 100 keeps each response small enough
+# to stay well inside the documented response-size and query-complexity limits.
+DBT_DISCOVERY_PAGE_SIZE = 100
+
+# Runs per model requested from modelHistoricalRuns, matching the count in dbt's own example query.
+DBT_MODEL_HISTORICAL_RUN_COUNT = 20
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@frozen
+class DbtRunFanoutConfig:
+ """A child resource of a run, fetched once per run in the runs list."""
+
+ # Path template under {base_url}/api, with {account_id} and {run_id} placeholders.
+ path: str
+ # include_related values to ask for on the child call.
+ include_related: tuple[str, ...] = ()
+ # Key inside the response envelope's `data` object holding the child rows. None means `data`
+ # is itself the row list.
+ data_selector: Optional[str] = None
+ # Set when the child rows are bare strings rather than objects; names the column they land in.
+ string_row_field: Optional[str] = None
+
+
+@frozen
+class DbtDiscoveryConfig:
+ """An endpoint served by the Discovery API (GraphQL) instead of the Admin API."""
+
+ query: str
+ # AppliedState field the rows come from; also the connection key in the response.
+ applied_field: str
+ # modelHistoricalRuns takes one model at a time, so its rows come from a second walk over the
+ # environment's models rather than from a paginated connection.
+ per_model: bool = False
-@dataclass
+
+@frozen
class DbtEndpointConfig:
name: str
# Path template under {base_url}/api, with an {account_id} placeholder. The API version is part
- # of the path because coverage is split: jobs/runs live on v2, the rest on v3.
- path: str
+ # of the path because coverage is split: jobs/runs live on v2, the rest on v3. None for
+ # endpoints that are not a top-level Admin API list (run fan-outs and Discovery API tables).
+ path: Optional[str] = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
default_incremental_field: Optional[str] = None
# Field to partition by — a stable created-at style field, never one that mutates.
@@ -46,6 +110,10 @@ class DbtEndpointConfig:
# creation — the lookback re-pulls that recent window so those rows get their final state;
# merge dedupes them on the primary key.
incremental_lookback: Optional[timedelta] = None
+ # Set when rows come from a child resource fetched once per run instead of a list endpoint.
+ run_fanout: Optional[DbtRunFanoutConfig] = None
+ # Set when rows come from the Discovery API instead of the Admin API.
+ discovery: Optional[DbtDiscoveryConfig] = None
description: Optional[str] = None
@@ -99,6 +167,102 @@ DBT_ENDPOINTS: dict[str, DbtEndpointConfig] = {
incremental_lookback=timedelta(hours=24),
description="Job run history, including status, timing, and git metadata",
),
+ "run_steps": DbtEndpointConfig(
+ name="run_steps",
+ # run_steps is only an include_related value on the run-detail route, not on the runs list,
+ # so each run in the window costs one extra request.
+ run_fanout=DbtRunFanoutConfig(
+ path="/v2/accounts/{account_id}/runs/{run_id}/",
+ include_related=("run_steps",),
+ data_selector="run_steps",
+ ),
+ # A step is identified by its position in its run; the nested step objects carry no id.
+ primary_keys=["run_id", "index"],
+ incremental_fields=[_datetime_incremental_field("run_created_at")],
+ default_incremental_field="run_created_at",
+ partition_key="run_created_at",
+ sort_mode="desc",
+ incremental_lookback=timedelta(hours=24),
+ should_sync_default=False,
+ description="Individual steps within each job run, with per-step command, status and logs. Costs one extra request per run",
+ ),
+ "run_artifacts": DbtEndpointConfig(
+ name="run_artifacts",
+ run_fanout=DbtRunFanoutConfig(
+ path="/v2/accounts/{account_id}/runs/{run_id}/artifacts/",
+ string_row_field="path",
+ ),
+ primary_keys=["run_id", "path"],
+ incremental_fields=[_datetime_incremental_field("run_created_at")],
+ default_incremental_field="run_created_at",
+ partition_key="run_created_at",
+ sort_mode="desc",
+ incremental_lookback=timedelta(hours=24),
+ should_sync_default=False,
+ description="Which artifact files each job run produced. Costs one extra request per run",
+ ),
+ "audit_logs": DbtEndpointConfig(
+ name="audit_logs",
+ path="/v3/accounts/{account_id}/audit-logs/",
+ # The endpoint documents no timestamp filter and no order_by, so there is no way to stop
+ # a walk early, so this table is full refresh only.
+ should_sync_default=False,
+ description="Account audit events: who changed jobs, environments and permissions, and when. Requires an Enterprise plan",
+ ),
+ "models": DbtEndpointConfig(
+ name="models",
+ discovery=DbtDiscoveryConfig(query=MODELS_QUERY, applied_field="models"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Current state of every model in each deployment environment, including its last run result. Needs a token with Discovery API access",
+ ),
+ "tests": DbtEndpointConfig(
+ name="tests",
+ discovery=DbtDiscoveryConfig(query=TESTS_QUERY, applied_field="tests"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Current state of every data test, including its last known result. Needs a token with Discovery API access",
+ ),
+ "sources": DbtEndpointConfig(
+ name="sources",
+ discovery=DbtDiscoveryConfig(query=SOURCES_QUERY, applied_field="sources"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Current state of every source, including freshness checks. Needs a token with Discovery API access",
+ ),
+ "snapshots": DbtEndpointConfig(
+ name="snapshots",
+ discovery=DbtDiscoveryConfig(query=SNAPSHOTS_QUERY, applied_field="snapshots"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Current state of every snapshot, including its last run result. Needs a token with Discovery API access",
+ ),
+ "seeds": DbtEndpointConfig(
+ name="seeds",
+ discovery=DbtDiscoveryConfig(query=SEEDS_QUERY, applied_field="seeds"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Current state of every seed, including its last run result. Needs a token with Discovery API access",
+ ),
+ "exposures": DbtEndpointConfig(
+ name="exposures",
+ discovery=DbtDiscoveryConfig(query=EXPOSURES_QUERY, applied_field="exposures"),
+ primary_keys=["environmentId", "uniqueId"],
+ should_sync_default=False,
+ description="Downstream exposures declared in each project, with their owner and maturity. Needs a token with Discovery API access",
+ ),
+ "model_historical_runs": DbtEndpointConfig(
+ name="model_historical_runs",
+ discovery=DbtDiscoveryConfig(
+ query=MODEL_HISTORICAL_RUNS_QUERY, applied_field="modelHistoricalRuns", per_model=True
+ ),
+ primary_keys=["environmentId", "uniqueId", "runId"],
+ should_sync_default=False,
+ description=(
+ "Per-model execution history: build time and status for each of a model's recent runs. "
+ "Costs one request per model, and the Discovery API only retains two months"
+ ),
+ ),
}
ENDPOINTS = tuple(DBT_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/source.py
index ef0331278d13..9da66200ab4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/source.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt import (
+ DISCOVERY_TOKEN_ERROR,
DbtResumeConfig,
dbt_source,
get_endpoint_permissions as get_dbt_endpoint_permissions,
@@ -57,7 +58,9 @@ class DbtSource(ResumableSource[DbtSourceConfig, DbtResumeConfig]):
You can create a service account token under **Account settings** → **API tokens** → **Service tokens** in dbt (Team and Enterprise plans), or use a personal access token. Read-only access to the resources you want to sync is enough.
-Your account ID is the number after `/deploy/` in your dbt URL. If your account runs on a cell-based or single-tenant deployment (for example `https://ab123.us1.dbt.com`), enter that base URL in the custom base URL field.""",
+The model, test, source, snapshot, seed and exposure tables come from the dbt Discovery API, so those need a token with metadata access on a Starter plan or above. The audit log table needs an Enterprise plan.
+
+Your account ID is the number after `/deploy/` in your dbt URL. If your account runs on a cell-based or single-tenant deployment (for example `https://ab123.us1.dbt.com`), enter that base URL in the custom base URL field, and enter your Discovery API URL from **Account settings** → **Access URLs**.""",
iconPath="/static/services/dbt.png",
docsUrl="https://posthog.com/docs/cdp/sources/dbt",
fields=cast(
@@ -98,16 +101,24 @@ Your account ID is the number after `/deploy/` in your dbt URL. If your account
placeholder="https://ab123.us1.dbt.com",
secret=False,
),
+ SourceFieldInputConfig(
+ name="discovery_api_url",
+ label="Discovery API URL (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://ab123.metadata.us1.dbt.com/graphql",
+ secret=False,
+ ),
],
),
)
@property
def connection_host_fields(self) -> list[str]:
- # region and custom_base_url pick the host; account_id is the path the token is sent to.
- # Retargeting any of them must re-require the token so a preserved credential can't be
- # pointed at another host or another account authorized by that same token.
- return ["region", "custom_base_url", "account_id"]
+ # region, custom_base_url and discovery_api_url pick the hosts; account_id is the path the
+ # token is sent to. Retargeting any of them must re-require the token so a preserved
+ # credential can't be pointed at another host or another account authorized by that token.
+ return ["region", "custom_base_url", "discovery_api_url", "account_id"]
def get_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.canonical_descriptions import (
@@ -122,6 +133,9 @@ Your account ID is the number after `/deploy/` in your dbt URL. If your account
return {
"401 Client Error: Unauthorized for url:": "Your dbt API token is invalid or has been revoked. Create a new service token in your dbt account settings, then reconnect.",
"403 Client Error: Forbidden for url:": "Your dbt API token is missing the permissions needed to sync this data. Grant the required read permissions in your dbt account settings, then reconnect.",
+ # The Discovery API answers an auth failure with HTTP 200 and an errors body, so there
+ # is no status text to match on.
+ DISCOVERY_TOKEN_ERROR: "Your dbt API token cannot read the Discovery API, which serves the model, test, source, snapshot, seed and exposure tables. Create a service token with metadata access, then reconnect.",
}
def get_schemas(
@@ -163,6 +177,7 @@ Your account ID is the number after `/deploy/` in your dbt URL. If your account
custom_base_url=config.custom_base_url,
team_id=team_id,
schema_name=schema_name,
+ discovery_api_url=config.discovery_api_url,
)
def get_endpoint_permissions(
@@ -175,6 +190,7 @@ Your account ID is the number after `/deploy/` in your dbt URL. If your account
custom_base_url=config.custom_base_url,
team_id=team_id,
endpoints=endpoints,
+ discovery_api_url=config.discovery_api_url,
)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DbtResumeConfig]:
@@ -200,4 +216,5 @@ Your account ID is the number after `/deploy/` in your dbt URL. If your account
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ discovery_api_url=config.discovery_api_url,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt.py
index 0d6ef07b56e7..c76d7dac6597 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt.py
@@ -8,11 +8,15 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt import (
+ DISCOVERY_TOKEN_ERROR,
DbtHostNotAllowedError,
DbtResumeConfig,
+ DbtRetryableError,
_coerce_datetime,
+ _raise_for_graphql_errors,
dbt_source,
get_base_url,
+ get_discovery_url,
get_endpoint_permissions,
get_rows,
validate_credentials,
@@ -29,6 +33,8 @@ def _response(*, status_code: int = 200, json_data: Any = None, text: str = "")
response.is_permanent_redirect = status_code in (301, 308)
response.text = text
response.json.return_value = json_data
+ if not response.ok:
+ response.raise_for_status.side_effect = requests.HTTPError(response=response)
return response
@@ -210,6 +216,62 @@ class TestGetEndpointPermissions:
assert result["projects"] is None
+ def test_run_fanout_endpoints_probe_the_runs_list(self):
+ # A run fan-out has no list path of its own, so the permission that decides whether it can
+ # sync is the runs list. Reading the missing path instead would break the schema picker.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _page([{"id": 1}])
+
+ result = get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=1,
+ endpoints=["run_steps", "run_artifacts"],
+ )
+
+ assert result == {"run_steps": None, "run_artifacts": None}
+ probed = {call.args[0] for call in mock_session.return_value.get.call_args_list}
+ assert probed == {"https://cloud.getdbt.com/api/v2/accounts/12345/runs/?limit=1"}
+
+ def test_discovery_endpoints_report_one_shared_probe_result(self):
+ # An Admin API token is not automatically accepted by the metadata service, and the
+ # rejection arrives as HTTP 200 with an errors body.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _page([{"id": 1}])
+ mock_session.return_value.post.return_value = _response(
+ json_data={"errors": [{"message": "No token was provided."}]}
+ )
+
+ result = get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=1,
+ endpoints=["models", "projects"],
+ )
+
+ assert result["models"] == "No token was provided."
+ assert result["projects"] is None
+ assert mock_session.return_value.post.call_count == 1
+
+ def test_discovery_probe_is_skipped_when_no_discovery_table_is_selected(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _page([{"id": 1}])
+
+ get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=1,
+ endpoints=["projects"],
+ )
+
+ mock_session.return_value.post.assert_not_called()
+
def test_unsafe_custom_host_is_rejected_without_probing(self):
# The probes are separate outbound requests, so an internal custom host must be blocked
# here too — not just in validate_credentials — before any request goes out (SSRF).
@@ -425,6 +487,34 @@ class TestDbtSourceResponse:
assert response.partition_keys == ["created_at"]
assert response.partition_mode == "datetime"
+ @pytest.mark.parametrize(
+ "endpoint, primary_keys",
+ [
+ # A key that is not unique table-wide seeds duplicate rows that every later merge
+ # multi-matches: fan-out children need the parent id, and Discovery rows repeat their
+ # uniqueId once per environment.
+ ("run_steps", ["run_id", "index"]),
+ ("run_artifacts", ["run_id", "path"]),
+ ("audit_logs", ["id"]),
+ ("models", ["environmentId", "uniqueId"]),
+ ("model_historical_runs", ["environmentId", "uniqueId", "runId"]),
+ ],
+ )
+ def test_primary_keys_are_unique_table_wide(self, endpoint, primary_keys):
+ response = dbt_source(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+
def test_full_refresh_response_shape(self):
response = dbt_source(
api_token="token",
@@ -441,3 +531,312 @@ class TestDbtSourceResponse:
assert response.primary_keys == ["id"]
assert response.sort_mode == "asc"
assert response.partition_mode is None
+
+
+class TestGetDiscoveryUrl:
+ @pytest.mark.parametrize(
+ "region, expected",
+ [
+ ("us", "https://metadata.cloud.getdbt.com/graphql"),
+ ("emea", "https://metadata.emea.dbt.com/graphql"),
+ ("au", "https://metadata.au.dbt.com/graphql"),
+ ("unknown", "https://metadata.cloud.getdbt.com/graphql"),
+ ],
+ )
+ def test_region_mapping(self, region, expected):
+ # The Discovery API lives on its own hostname per region; pointing a region at the wrong
+ # one 404s every model/test/source table while the Admin API tables keep working.
+ assert get_discovery_url(region, None) == expected
+
+ def test_custom_url_overrides_region(self):
+ assert (
+ get_discovery_url("us", " https://ab123.metadata.us1.dbt.com/graphql/ ")
+ == "https://ab123.metadata.us1.dbt.com/graphql"
+ )
+
+ def test_non_https_custom_url_rejected(self):
+ with pytest.raises(DbtHostNotAllowedError):
+ get_discovery_url("us", "http://internal-host/graphql")
+
+
+class TestRaiseForGraphqlErrors:
+ @pytest.mark.parametrize(
+ "message, expected_exception, expected_fragment",
+ [
+ ("Query rate limit exceeded", DbtRetryableError, "rate limited"),
+ ("Too many requests", DbtRetryableError, "rate limited"),
+ ("No token was provided.", Exception, DISCOVERY_TOKEN_ERROR),
+ ("You do not have permission to perform this action", Exception, DISCOVERY_TOKEN_ERROR),
+ ("Environment 1 not found", Exception, "dbt Discovery API error"),
+ ],
+ )
+ def test_error_classification(self, message, expected_exception, expected_fragment):
+ # The Discovery API reports failures with HTTP 200 and an errors body, so there is no
+ # status code to classify on: a throttle read as terminal fails the sync, and a bad token
+ # read as retryable burns five attempts before failing anyway.
+ with pytest.raises(expected_exception) as error:
+ _raise_for_graphql_errors({"errors": [{"message": message}]})
+
+ assert expected_fragment in str(error.value)
+
+ def test_data_without_errors_passes(self):
+ _raise_for_graphql_errors({"data": {"environment": None}})
+
+ def test_body_with_neither_data_nor_errors_raises(self):
+ with pytest.raises(Exception, match="Unexpected dbt Discovery API response"):
+ _raise_for_graphql_errors({"extensions": {}})
+
+
+def _graphql_connection(
+ applied_field: str, nodes: list[dict], *, has_next: bool = False, end_cursor: Optional[str] = None
+) -> mock.MagicMock:
+ return _response(
+ json_data={
+ "data": {
+ "environment": {
+ "applied": {
+ applied_field: {
+ "edges": [{"node": node} for node in nodes],
+ "pageInfo": {"hasNextPage": has_next, "endCursor": end_cursor},
+ }
+ }
+ }
+ }
+ }
+ )
+
+
+def _graphql_list(applied_field: str, rows: list[dict]) -> mock.MagicMock:
+ return _response(json_data={"data": {"environment": {"applied": {applied_field: rows}}}})
+
+
+def _posted_variables(session: mock.MagicMock, call_index: int) -> dict[str, Any]:
+ return session.post.call_args_list[call_index].kwargs["json"]["variables"]
+
+
+class TestRunFanout:
+ def _get_rows(self, session: mock.MagicMock, manager: mock.MagicMock, endpoint: str, **kwargs: Any) -> list[Any]:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ return list(
+ get_rows(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ def test_run_steps_expand_each_run_from_the_run_detail_route(self):
+ # run_steps is only an include_related value on the run-detail route, and dbt wants a JSON
+ # array literal. If either is wrong, the table stays permanently empty.
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 7, "created_at": "2026-06-20T00:00:00Z"}]),
+ _response(
+ json_data={
+ "data": {
+ "id": 7,
+ "run_steps": [
+ {"index": 1, "name": "dbt deps", "status": 10},
+ {"index": 2, "name": "dbt build", "status": 20},
+ ],
+ }
+ }
+ ),
+ ]
+
+ batches = self._get_rows(session, _manager(), "run_steps")
+
+ assert batches == [
+ [
+ {"index": 1, "name": "dbt deps", "status": 10, "run_id": 7, "run_created_at": "2026-06-20T00:00:00Z"},
+ {"index": 2, "name": "dbt build", "status": 20, "run_id": 7, "run_created_at": "2026-06-20T00:00:00Z"},
+ ]
+ ]
+ assert _requested_query(session, 0)["order_by"] == ["-created_at"]
+ assert session.get.call_args_list[1].args[0] == (
+ "https://cloud.getdbt.com/api/v2/accounts/12345/runs/7/?include_related=%5B%22run_steps%22%5D"
+ )
+
+ def test_run_artifacts_turn_bare_paths_into_rows(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 7, "created_at": "2026-06-20T00:00:00Z"}]),
+ _response(json_data={"data": ["manifest.json", "run_results.json"]}),
+ ]
+
+ batches = self._get_rows(session, _manager(), "run_artifacts")
+
+ assert batches == [
+ [
+ {"run_id": 7, "run_created_at": "2026-06-20T00:00:00Z", "path": "manifest.json"},
+ {"run_id": 7, "run_created_at": "2026-06-20T00:00:00Z", "path": "run_results.json"},
+ ]
+ ]
+
+ def test_missing_child_is_skipped_rather_than_failing_the_sync(self):
+ # Runs age out and cancelled runs never save artifacts, so a 404 on one run must not take
+ # the whole table down with it.
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 7, "created_at": "2026-06-20T00:00:00Z"}, {"id": 8, "created_at": "2026-06-19T00:00:00Z"}]),
+ _response(status_code=404, json_data={"status": {"user_message": "Not found"}}),
+ _response(json_data={"data": ["manifest.json"]}),
+ ]
+
+ batches = self._get_rows(session, _manager(), "run_artifacts")
+
+ assert batches == [[{"run_id": 8, "run_created_at": "2026-06-19T00:00:00Z", "path": "manifest.json"}]]
+
+ def test_incremental_does_not_fan_out_below_the_watermark(self):
+ # Without the newest-first stop, every sync re-expands each historical run, which costs
+ # one extra request per run forever.
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page(
+ [
+ {"id": 9, "created_at": "2026-06-20T00:00:00Z"},
+ {"id": 1, "created_at": "2026-01-01T00:00:00Z"},
+ ],
+ count=100,
+ total_count=500,
+ ),
+ _response(json_data={"data": {"id": 9, "run_steps": [{"index": 1, "name": "dbt build", "status": 10}]}}),
+ ]
+
+ batches = self._get_rows(
+ session,
+ _manager(),
+ "run_steps",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 10, tzinfo=UTC),
+ incremental_field="run_created_at",
+ )
+
+ assert batches == [
+ [{"index": 1, "name": "dbt build", "status": 10, "run_id": 9, "run_created_at": "2026-06-20T00:00:00Z"}]
+ ]
+ # The aged run is never expanded, and the second runs page is never requested.
+ assert session.get.call_count == 2
+
+ def test_resume_restarts_from_the_saved_parent_page(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 7, "created_at": "2026-06-20T00:00:00Z"}]),
+ _response(json_data={"data": ["manifest.json"]}),
+ ]
+
+ self._get_rows(session, _manager(resume=DbtResumeConfig(parent_offset=200)), "run_artifacts")
+
+ assert _requested_query(session, 0)["offset"] == ["200"]
+
+
+class TestDiscoverySync:
+ def _get_rows(self, session: mock.MagicMock, manager: mock.MagicMock, endpoint: str, **kwargs: Any) -> list[Any]:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ return list(
+ get_rows(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ def test_only_deployment_environments_are_queried(self):
+ # Development environments have no applied state, so querying them spends a request per
+ # environment to get nothing back.
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 10, "type": "deployment"}, {"id": 11, "type": "development"}, {"type": "deployment"}])
+ ]
+ session.post.side_effect = [_graphql_connection("models", [{"uniqueId": "model.a.b"}])]
+
+ self._get_rows(session, _manager(), "models")
+
+ assert session.post.call_count == 1
+ assert _posted_variables(session, 0)["environmentId"] == 10
+
+ def test_pages_are_walked_and_stamped_with_the_environment(self):
+ # environmentId is half the primary key. If a node type ever stops resolving it, unstamped
+ # rows from different environments collide on uniqueId and every later merge multi-matches
+ # the duplicates.
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 10, "type": "deployment"}])]
+ session.post.side_effect = [
+ _graphql_connection("tests", [{"uniqueId": "test.a.b"}], has_next=True, end_cursor="cursor-1"),
+ _graphql_connection("tests", [{"uniqueId": "test.a.c", "environmentId": 99}]),
+ ]
+ manager = _manager()
+
+ batches = self._get_rows(session, manager, "tests")
+
+ assert batches == [
+ [{"uniqueId": "test.a.b", "environmentId": 10}],
+ [{"uniqueId": "test.a.c", "environmentId": 10}],
+ ]
+ assert _posted_variables(session, 0)["after"] is None
+ assert _posted_variables(session, 1)["after"] == "cursor-1"
+ manager.save_state.assert_called_once_with(DbtResumeConfig(parent_offset=0, cursor="cursor-1"))
+
+ def test_environment_without_applied_state_yields_nothing(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 10, "type": "deployment"}])]
+ session.post.side_effect = [_response(json_data={"data": {"environment": {"applied": None}}})]
+
+ assert self._get_rows(session, _manager(), "sources") == []
+
+ def test_resume_continues_the_saved_cursor(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 10, "type": "deployment"}])]
+ session.post.side_effect = [_graphql_connection("seeds", [{"uniqueId": "seed.a.b"}])]
+
+ self._get_rows(session, _manager(resume=DbtResumeConfig(parent_offset=0, cursor="cursor-9")), "seeds")
+
+ assert _posted_variables(session, 0)["after"] == "cursor-9"
+
+ @pytest.mark.parametrize("end_cursor", [None, "cursor-1"])
+ def test_a_page_that_does_not_advance_the_cursor_fails(self, end_cursor):
+ # hasNextPage with no new cursor would re-request the page just read until the activity
+ # times out. Ending the walk quietly instead would write a partial table that reads as
+ # complete.
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 10, "type": "deployment"}])]
+ session.post.side_effect = [
+ _graphql_connection("models", [{"uniqueId": "model.a.b"}], has_next=True, end_cursor="cursor-1"),
+ _graphql_connection("models", [{"uniqueId": "model.a.c"}], has_next=True, end_cursor=end_cursor),
+ ]
+
+ with pytest.raises(Exception, match="without advancing the cursor"):
+ self._get_rows(session, _manager(resume=DbtResumeConfig()), "models")
+
+ def test_model_historical_runs_asks_once_per_model(self):
+ # modelHistoricalRuns takes a single model at a time, so the model list has to be walked
+ # first; querying the connection directly returns nothing.
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 10, "type": "deployment"}])]
+ session.post.side_effect = [
+ _graphql_connection("models", [{"uniqueId": "model.a.b"}, {"uniqueId": "model.a.c"}]),
+ _graphql_list("modelHistoricalRuns", [{"uniqueId": "model.a.b", "runId": 1}]),
+ _graphql_list("modelHistoricalRuns", [{"uniqueId": "model.a.c", "runId": 2}]),
+ ]
+
+ batches = self._get_rows(session, _manager(), "model_historical_runs")
+
+ assert batches == [
+ [
+ {"uniqueId": "model.a.b", "runId": 1, "environmentId": 10},
+ {"uniqueId": "model.a.c", "runId": 2, "environmentId": 10},
+ ]
+ ]
+ assert [_posted_variables(session, index)["uniqueId"] for index in (1, 2)] == ["model.a.b", "model.a.c"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt_source.py
index ba089b47ce3d..ca298bb801df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt_source.py
@@ -15,7 +15,12 @@ class TestDbtSource:
def test_connection_host_fields_cover_host_determining_fields(self):
# These fields retarget where the stored token is sent (host and account path); missing one
# lets an editor point the preserved credential at their own server or another account.
- assert self.source.connection_host_fields == ["region", "custom_base_url", "account_id"]
+ assert self.source.connection_host_fields == [
+ "region",
+ "custom_base_url",
+ "discovery_api_url",
+ "account_id",
+ ]
def test_declares_v3_as_default_over_legacy_pin(self):
# New sources are stamped with default_version; a revert here silently pins them to the
@@ -37,6 +42,16 @@ class TestDbtSource:
("jobs", False),
("users", False),
("runs", True),
+ ("run_steps", True),
+ ("run_artifacts", True),
+ ("audit_logs", False),
+ ("models", False),
+ ("tests", False),
+ ("sources", False),
+ ("snapshots", False),
+ ("seeds", False),
+ ("exposures", False),
+ ("model_historical_runs", False),
],
)
def test_schema_incremental_support(self, endpoint, incremental):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dbt.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dbt.py
index 4bfdc9b30978..34fc3754cc2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dbt.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dbt.py
@@ -12,3 +12,4 @@ class DbtSourceConfig(config.Config):
api_token: str
region: Literal["us", "emea", "au"] = config.value(default="us")
custom_base_url: str | None = None
+ discovery_api_url: str | None = None