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(data-warehouse): implement dbt import source (#71227)

Tom Owersa7d2357e312d
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 aa88abb8480d..89ff7c7fb917 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -141,6 +141,7 @@ the row lists both.
| cursor | HTTP | requests | ✅ |
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
| datadog | HTTP | requests | ✅ |
+| dbt | HTTP | requests | ✅ |
| decagon | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
| deepgram | HTTP | requests | ✅ |
@@ -595,7 +596,6 @@ doesn't conflict with concurrent PRs.
- datascope
- datorama
- db2
-- dbt
- deepsource
- deno_deploy
- deputy
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
new file mode 100644
index 000000000000..165522fa8628
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/canonical_descriptions.py
@@ -0,0 +1,109 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "A dbt platform account the API token has access to, including plan and seat information.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v3",
+ "columns": {
+ "id": "Unique identifier for the account.",
+ "name": "Display name of the account.",
+ "plan": "The account's dbt plan (e.g. developer, team, enterprise).",
+ "state": "Account state; 1 means active.",
+ "run_slots": "Number of concurrent run slots available to the account.",
+ "developer_seats": "Number of developer seats on the account.",
+ "read_only_seats": "Number of read-only seats on the account.",
+ "created_at": "When the account was created.",
+ "updated_at": "When the account was last updated.",
+ },
+ },
+ "projects": {
+ "description": "A dbt project in the account, linking a repository and a data warehouse connection.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v3",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "account_id": "The account the project belongs to.",
+ "name": "Display name of the project.",
+ "connection_id": "The data warehouse connection used by the project.",
+ "repository_id": "The git repository connected to the project.",
+ "dbt_project_subdirectory": "Subdirectory of the repository containing the dbt project, if not the root.",
+ "state": "Project state; 1 means active.",
+ "created_at": "When the project was created.",
+ "updated_at": "When the project was last updated.",
+ },
+ },
+ "environments": {
+ "description": "A development or deployment environment within a dbt project, pinning a dbt version and git branch.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v3",
+ "columns": {
+ "id": "Unique identifier for the environment.",
+ "account_id": "The account the environment belongs to.",
+ "project_id": "The project the environment belongs to.",
+ "name": "Display name of the environment.",
+ "type": "Environment type: development or deployment.",
+ "dbt_version": "The dbt version the environment runs.",
+ "use_custom_branch": "Whether the environment builds from a custom git branch.",
+ "custom_branch": "The custom git branch used, when enabled.",
+ "created_at": "When the environment was created.",
+ "updated_at": "When the environment was last updated.",
+ },
+ },
+ "jobs": {
+ "description": "A job definition — a scheduled or triggered set of dbt commands run in an environment.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v2",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "account_id": "The account the job belongs to.",
+ "project_id": "The project the job belongs to.",
+ "environment_id": "The environment the job runs in.",
+ "name": "Display name of the job.",
+ "execute_steps": "The ordered dbt commands the job executes.",
+ "dbt_version": "dbt version override for the job, if any.",
+ "triggers": "How the job is triggered (schedule, git PRs, API).",
+ "state": "Job state; 1 means active.",
+ "generate_docs": "Whether the job generates dbt docs on run.",
+ "created_at": "When the job was created.",
+ "updated_at": "When the job was last updated.",
+ },
+ },
+ "users": {
+ "description": "A user with access to the dbt account.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v3",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "first_name": "The user's first name.",
+ "last_name": "The user's last name.",
+ "email": "The user's email address.",
+ "is_active": "Whether the user account is active.",
+ "last_login": "When the user last logged in.",
+ "created_at": "When the user was created.",
+ },
+ },
+ "runs": {
+ "description": "A single execution of a job, including status, timing, and git metadata.",
+ "docs_url": "https://docs.getdbt.com/dbt-cloud/api-v2",
+ "columns": {
+ "id": "Unique identifier for the run.",
+ "account_id": "The account the run belongs to.",
+ "project_id": "The project the run belongs to.",
+ "environment_id": "The environment the run executed in.",
+ "job_definition_id": "The job definition that produced the run.",
+ "trigger_id": "The trigger that started the run.",
+ "status": "Numeric run status (1 queued, 3 running, 10 success, 20 error, 30 cancelled).",
+ "status_humanized": "Human-readable run status.",
+ "git_branch": "Git branch the run built from.",
+ "git_sha": "Git commit SHA the run built from.",
+ "dbt_version": "dbt version used for the run.",
+ "duration": "Total run duration.",
+ "queued_duration": "Time the run spent queued.",
+ "run_duration": "Time the run spent executing.",
+ "artifacts_saved": "Whether run artifacts were saved.",
+ "has_docs_generated": "Whether the run generated dbt docs.",
+ "created_at": "When the run was created (queued).",
+ "started_at": "When the run started executing.",
+ "finished_at": "When the run finished.",
+ "should_start_at": "When a scheduled run was due to start.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..95c2d3778017
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/dbt.py
@@ -0,0 +1,353 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.dbt.settings import (
+ DBT_ENDPOINTS,
+ DBT_PAGE_LIMIT,
+ DBT_REGION_BASE_URLS,
+ DbtEndpointConfig,
+)
+
+HOST_NOT_ALLOWED_ERROR = "The dbt base URL is not allowed"
+
+
+class DbtRetryableError(Exception):
+ pass
+
+
+class DbtHostNotAllowedError(Exception):
+ pass
+
+
+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
+
+
+def get_base_url(region: str, custom_base_url: str | None) -> str:
+ """Resolve the API base URL from the region select, or a custom cell-based/single-tenant URL."""
+ if custom_base_url and custom_base_url.strip():
+ url = custom_base_url.strip().rstrip("/")
+ if not url.startswith("https://"):
+ raise DbtHostNotAllowedError("Custom dbt base URL must start with https://")
+ return url
+ return DBT_REGION_BASE_URLS.get(region, DBT_REGION_BASE_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).
+
+ The regional hosts are fixed dbt Labs domains, so only a user-supplied custom URL needs the
+ check. Only enforced on cloud — see _is_host_safe.
+ """
+ if not (custom_base_url and custom_base_url.strip()):
+ return True, None
+ host = urlparse(base_url).hostname or ""
+ if not host:
+ return False, HOST_NOT_ALLOWED_ERROR
+ return _is_host_safe(host, team_id)
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ # dbt Cloud accepts both `Token` and `Bearer` schemes for service account tokens and PATs.
+ return {
+ "Authorization": f"Token {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _status_message(response: requests.Response) -> str | None:
+ """Pull the human-readable message out of the dbt envelope ({"status": {"user_message": ...}})."""
+ try:
+ body = response.json()
+ return body.get("status", {}).get("user_message") or response.text
+ except Exception:
+ return response.text or None
+
+
+def validate_credentials(
+ api_token: str,
+ account_id: str,
+ region: str,
+ custom_base_url: str | None,
+ team_id: Optional[int] = None,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Probe the account endpoint to confirm the token is genuine and can reach the account.
+
+ At source-create (``schema_name is None``) a 403 is accepted: the token authenticated but may
+ lack the permission set for this particular probe. A scoped probe treats 403 as a failure.
+ """
+ try:
+ base_url = get_base_url(region, custom_base_url)
+ except DbtHostNotAllowedError as e:
+ return False, str(e)
+
+ if team_id is not None:
+ 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
+
+ url = f"{base_url}/api/v2/accounts/{account_id}/"
+ try:
+ # Don't follow redirects: a custom host could 3xx to an internal address, defeating the
+ # host check above (SSRF).
+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10, allow_redirects=False)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid dbt API token"
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid token, missing permission for this probe — let source creation through.
+ return True, None
+ return False, "Your dbt API token lacks the required permissions for this endpoint"
+
+ if response.status_code == 404:
+ return False, f"dbt account {account_id} not found — check the account ID and region"
+
+ return False, _status_message(response)
+
+
+def get_endpoint_permissions(
+ api_token: str,
+ account_id: str,
+ region: str,
+ custom_base_url: str | None,
+ team_id: int,
+ endpoints: list[str],
+) -> dict[str, str | None]:
+ """Probe each endpoint with limit=1 so the schema picker can flag tables the token can't read.
+
+ Only a real denial (401/403/404) counts as unreachable — throttles, 5xx, and network blips go
+ through the retryable sync path instead, so they report the endpoint as reachable here.
+ """
+ try:
+ base_url = get_base_url(region, custom_base_url)
+ except DbtHostNotAllowedError as e:
+ return dict.fromkeys(endpoints, str(e))
+
+ # These probes are separate outbound requests from credential validation, so re-check the host
+ # here too — otherwise a custom host could be re-pointed at an internal address after validation.
+ host_ok, host_err = _check_host_safety(base_url, custom_base_url, team_id)
+ if not host_ok:
+ return dict.fromkeys(endpoints, host_err or HOST_NOT_ALLOWED_ERROR)
+
+ session = make_tracked_session()
+ headers = _get_headers(api_token)
+ results: dict[str, str | None] = {}
+ 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"
+ try:
+ response = session.get(url, headers=headers, timeout=10, allow_redirects=False)
+ except requests.exceptions.RequestException:
+ results[endpoint] = None
+ continue
+ if response.status_code in (401, 403, 404):
+ results[endpoint] = (
+ _status_message(response) or "Your dbt API token lacks the permissions to read this table"
+ )
+ else:
+ results[endpoint] = None
+ return results
+
+
+def _coerce_datetime(value: Any) -> datetime | None:
+ """Normalize a watermark or row value to an aware UTC datetime for comparison."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+ return None
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ DbtRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=60, allow_redirects=False)
+
+ 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 API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"dbt API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _build_params(config: DbtEndpointConfig, incremental_field: str | None, walking_desc: bool) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": DBT_PAGE_LIMIT}
+ # runs is the only endpoint with a documented order_by; the other lists come back in stable
+ # id order by default, which offset pagination is safe against.
+ if walking_desc:
+ params["order_by"] = f"-{incremental_field or config.default_incremental_field}"
+ return params
+
+
+def get_rows(
+ api_token: str,
+ account_id: str,
+ region: str,
+ custom_base_url: str | None,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DbtResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = DBT_ENDPOINTS[endpoint]
+ base_url = get_base_url(region, custom_base_url)
+
+ # 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)
+
+ 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
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ watermark = _coerce_datetime(db_incremental_field_last_value)
+ 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)
+
+ rows = data.get("data") or []
+ if not rows:
+ break
+
+ 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
+ ]
+ if kept:
+ yield kept
+ if len(kept) < len(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
+
+ # 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))
+
+
+def dbt_source(
+ api_token: str,
+ account_id: str,
+ region: str,
+ custom_base_url: str | None,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DbtResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = DBT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ account_id=account_id,
+ region=region,
+ custom_base_url=custom_base_url,
+ endpoint=endpoint,
+ team_id=team_id,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Runs are walked newest-first (order_by=-created_at), so the incremental watermark only
+ # persists at successful job end.
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
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
new file mode 100644
index 000000000000..0e09c29e7d9d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/settings.py
@@ -0,0 +1,96 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Per-region base hostnames for the dbt Cloud Administrative API. Cell-based (e.g.
+# https://ab123.us1.dbt.com) and single-tenant deployments use a custom base URL instead.
+DBT_REGION_BASE_URLS: dict[str, str] = {
+ "us": "https://cloud.getdbt.com",
+ "emea": "https://emea.dbt.com",
+ "au": "https://au.dbt.com",
+}
+
+# dbt Cloud caps limit/offset pagination at 100 rows per request.
+DBT_PAGE_LIMIT = 100
+
+
+@dataclass
+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
+ 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.
+ partition_key: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+ # Safety overlap subtracted from the incremental watermark on every run. Runs are cursored on
+ # the immutable created_at, but their status/timing fields keep mutating for a while after
+ # 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
+ description: Optional[str] = None
+
+
+DBT_ENDPOINTS: dict[str, DbtEndpointConfig] = {
+ "accounts": DbtEndpointConfig(
+ name="accounts",
+ # Not account-scoped: lists every account the token can access.
+ path="/v3/accounts/",
+ description="dbt platform accounts the API token has access to",
+ ),
+ "projects": DbtEndpointConfig(
+ name="projects",
+ path="/v3/accounts/{account_id}/projects/",
+ description="dbt projects in the account",
+ ),
+ "environments": DbtEndpointConfig(
+ name="environments",
+ path="/v3/accounts/{account_id}/environments/",
+ description="Development and deployment environments across the account's projects",
+ ),
+ "jobs": DbtEndpointConfig(
+ name="jobs",
+ path="/v2/accounts/{account_id}/jobs/",
+ description="Job definitions (scheduled and triggered dbt executions) across the account",
+ ),
+ "users": DbtEndpointConfig(
+ name="users",
+ path="/v3/accounts/{account_id}/users/",
+ # Listing users needs account-level user permissions many read-only service tokens lack,
+ # so leave it deselected by default; the schema picker's permission probe explains why.
+ should_sync_default=False,
+ description="Users with access to the account. Requires a token with user read permissions",
+ ),
+ "runs": DbtEndpointConfig(
+ name="runs",
+ path="/v2/accounts/{account_id}/runs/",
+ # The runs list has no server-side time filter, but it supports order_by=-created_at, so
+ # incremental syncs walk newest-first and stop once a whole page predates the watermark —
+ # only new rows are fetched, unlike a client-side skip cursor.
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ default_incremental_field="created_at",
+ partition_key="created_at",
+ sort_mode="desc",
+ incremental_lookback=timedelta(hours=24),
+ description="Job run history, including status, timing, and git metadata",
+ ),
+}
+
+ENDPOINTS = tuple(DBT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DBT_ENDPOINTS.items()
+}
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 e7a43876e668..ec38b248b49b 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
@@ -1,19 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt import (
+ DbtResumeConfig,
+ dbt_source,
+ get_endpoint_permissions as get_dbt_endpoint_permissions,
+ validate_credentials as validate_dbt_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.settings import (
+ DBT_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DbtSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DbtSource(SimpleSource[DbtSourceConfig]):
+class DbtSource(ResumableSource[DbtSourceConfig, DbtResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DBT
@@ -24,7 +51,152 @@ class DbtSource(SimpleSource[DbtSourceConfig]):
name=SchemaExternalDataSourceType.DBT,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="dbt",
+ keywords=["dbt cloud", "dbt labs", "dbt platform"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your dbt platform (dbt Cloud) account ID and API token to pull your dbt projects, jobs, environments, and run history into the PostHog Data warehouse.
+
+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.""",
iconPath="/static/services/dbt.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/dbt",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="account_id",
+ label="Account ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="12345",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (cloud.getdbt.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EMEA (emea.dbt.com)", value="emea"),
+ SourceFieldSelectConfigOption(label="APAC (au.dbt.com)", value="au"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="custom_base_url",
+ label="Custom base URL (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://ab123.us1.dbt.com",
+ 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"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # The base URL varies by region/custom deployment, so match on the stable status text only.
+ # These errors always originate from this source's own requests to the dbt API.
+ 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.",
+ }
+
+ def get_schemas(
+ self,
+ config: DbtSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = DBT_ENDPOINTS[endpoint]
+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ # The incremental lookback re-pulls a window of rows each run; only merge dedupes
+ # those on the primary key, append would materialize them as duplicates.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: DbtSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_dbt_credentials(
+ api_token=config.api_token,
+ account_id=config.account_id,
+ region=config.region,
+ custom_base_url=config.custom_base_url,
+ team_id=team_id,
+ schema_name=schema_name,
+ )
+
+ def get_endpoint_permissions(
+ self, config: DbtSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ return get_dbt_endpoint_permissions(
+ api_token=config.api_token,
+ account_id=config.account_id,
+ region=config.region,
+ custom_base_url=config.custom_base_url,
+ team_id=team_id,
+ endpoints=endpoints,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DbtResumeConfig]:
+ return ResumableSourceManager[DbtResumeConfig](inputs, DbtResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DbtSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DbtResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return dbt_source(
+ api_token=config.api_token,
+ account_id=config.account_id,
+ region=config.region,
+ custom_base_url=config.custom_base_url,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
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
new file mode 100644
index 000000000000..ad22040aae00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt.py
@@ -0,0 +1,422 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt import (
+ DbtHostNotAllowedError,
+ DbtResumeConfig,
+ _coerce_datetime,
+ dbt_source,
+ get_base_url,
+ get_endpoint_permissions,
+ get_rows,
+ validate_credentials,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt"
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ return response
+
+
+def _page(rows: list[dict], *, count: Optional[int] = None, total_count: Optional[int] = None) -> mock.MagicMock:
+ """A dbt API list response envelope."""
+ return _response(
+ json_data={
+ "status": {"code": 200, "is_success": True},
+ "data": rows,
+ "extra": {
+ "pagination": {
+ "count": count if count is not None else len(rows),
+ "total_count": total_count if total_count is not None else len(rows),
+ },
+ },
+ }
+ )
+
+
+def _manager(resume: Optional[DbtResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _requested_query(session: mock.MagicMock, call_index: int) -> dict[str, list[str]]:
+ url = session.get.call_args_list[call_index].args[0]
+ return parse_qs(urlparse(url).query)
+
+
+class TestGetBaseUrl:
+ @pytest.mark.parametrize(
+ "region, expected",
+ [
+ ("us", "https://cloud.getdbt.com"),
+ ("emea", "https://emea.dbt.com"),
+ ("au", "https://au.dbt.com"),
+ ("unknown", "https://cloud.getdbt.com"),
+ ],
+ )
+ def test_region_mapping(self, region, expected):
+ assert get_base_url(region, None) == expected
+
+ @pytest.mark.parametrize(
+ "custom, expected",
+ [
+ ("https://ab123.us1.dbt.com", "https://ab123.us1.dbt.com"),
+ ("https://ab123.us1.dbt.com/", "https://ab123.us1.dbt.com"),
+ (" https://single-tenant.example.com ", "https://single-tenant.example.com"),
+ ("", "https://cloud.getdbt.com"),
+ (" ", "https://cloud.getdbt.com"),
+ (None, "https://cloud.getdbt.com"),
+ ],
+ )
+ def test_custom_base_url_overrides_region(self, custom, expected):
+ assert get_base_url("us", custom) == expected
+
+ def test_non_https_custom_url_rejected(self):
+ with pytest.raises(DbtHostNotAllowedError):
+ get_base_url("us", "http://internal-host")
+
+
+class TestCoerceDatetime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC), datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)),
+ (datetime(2026, 6, 1, 12, 0, 0), datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)),
+ (date(2026, 6, 1), datetime(2026, 6, 1, tzinfo=UTC)),
+ ("2026-06-01T12:00:00Z", datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)),
+ ("2026-06-01 12:00:00+00:00", datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)),
+ ("2026-06-01T12:00:00", datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)),
+ ("not-a-date", None),
+ (12345, None),
+ (None, None),
+ ],
+ )
+ def test_coerce(self, value, expected):
+ assert _coerce_datetime(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, schema_name, expected_valid, expected_error_fragment",
+ [
+ (200, None, True, None),
+ (401, None, False, "Invalid dbt API token"),
+ # A 403 at source-create means the token authenticated but lacks the permission for
+ # this probe — creation must go through so per-endpoint checks can guide the user.
+ (403, None, True, None),
+ (403, "runs", False, "permissions"),
+ (404, None, False, "not found"),
+ ],
+ )
+ def test_status_mapping(self, status_code, schema_name, expected_valid, expected_error_fragment):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status_code=status_code, json_data={"status": {}})
+
+ valid, error = validate_credentials(
+ api_token="token", account_id="12345", region="us", custom_base_url=None, schema_name=schema_name
+ )
+
+ assert valid is expected_valid
+ if expected_error_fragment is None:
+ assert error is None
+ else:
+ assert expected_error_fragment in (error or "")
+
+ def test_probes_account_endpoint_without_following_redirects(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status_code=200, json_data={"status": {}})
+
+ validate_credentials(api_token="token", account_id="12345", region="emea", custom_base_url=None)
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://emea.dbt.com/api/v2/accounts/12345/"
+ assert call.kwargs["headers"]["Authorization"] == "Token token"
+ assert call.kwargs["allow_redirects"] is False
+
+ def test_redirect_is_rejected(self):
+ # A custom host could 3xx to an internal address, defeating the host check (SSRF).
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status_code=302)
+
+ valid, error = validate_credentials(
+ api_token="token", account_id="12345", region="us", custom_base_url=None
+ )
+
+ assert valid is False
+ assert error is not None
+
+ def test_non_https_custom_url_fails_without_request(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ valid, _error = validate_credentials(
+ api_token="token", account_id="12345", region="us", custom_base_url="http://internal"
+ )
+
+ assert valid is False
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestGetEndpointPermissions:
+ def test_denied_endpoints_get_a_reason(self):
+ responses = {
+ "https://cloud.getdbt.com/api/v3/accounts/12345/users/?limit=1": _response(
+ status_code=403, json_data={"status": {"user_message": "Insufficient permissions"}}
+ ),
+ "https://cloud.getdbt.com/api/v3/accounts/12345/projects/?limit=1": _page([{"id": 1}]),
+ }
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = lambda url, **kwargs: responses[url]
+
+ result = get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=1,
+ endpoints=["users", "projects"],
+ )
+
+ assert result["projects"] is None
+ assert "Insufficient permissions" in (result["users"] or "")
+
+ def test_network_errors_do_not_report_missing_permission(self):
+ # A blip is not a denial — only a real 401/403/404 should flag the table.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ result = get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=1,
+ endpoints=["projects"],
+ )
+
+ assert result["projects"] is None
+
+ 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).
+ with (
+ mock.patch(f"{MODULE}._is_host_safe", return_value=(False, "Host not allowed")),
+ mock.patch(f"{MODULE}.make_tracked_session") as mock_session,
+ ):
+ result = get_endpoint_permissions(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url="https://internal.local",
+ team_id=1,
+ endpoints=["projects", "users"],
+ )
+
+ mock_session.return_value.get.assert_not_called()
+ assert result["projects"] is not None
+ assert result["users"] is not None
+
+
+class TestGetRows:
+ 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=kwargs.pop("region", "us"),
+ custom_base_url=kwargs.pop("custom_base_url", None),
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ def test_full_refresh_paginates_until_total_count(self):
+ session = mock.MagicMock()
+ page1_rows = [{"id": index} for index in range(3)]
+ page2_rows = [{"id": 100 + index} for index in range(2)]
+ session.get.side_effect = [
+ _page(page1_rows, count=100, total_count=137),
+ _page(page2_rows, count=37, total_count=137),
+ ]
+ manager = _manager()
+
+ batches = self._get_rows(session, manager, "projects")
+
+ assert batches == [page1_rows, page2_rows]
+ assert session.get.call_count == 2
+ assert (
+ session.get.call_args_list[0].args[0].startswith("https://cloud.getdbt.com/api/v3/accounts/12345/projects/")
+ )
+ assert _requested_query(session, 0)["offset"] == ["0"]
+ assert _requested_query(session, 1)["offset"] == ["100"]
+ assert "order_by" not in _requested_query(session, 0)
+ assert session.get.call_args_list[0].kwargs["headers"]["Authorization"] == "Token token"
+
+ def test_state_saved_after_yield_only_when_more_pages_remain(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ _page([{"id": 1}], count=100, total_count=137),
+ _page([{"id": 2}], count=37, total_count=137),
+ ]
+ manager = _manager()
+
+ self._get_rows(session, manager, "projects")
+
+ manager.save_state.assert_called_once_with(DbtResumeConfig(offset=100))
+
+ def test_stops_when_offset_reaches_total_count(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 1}], count=100, total_count=100)]
+ manager = _manager()
+
+ batches = self._get_rows(session, manager, "projects")
+
+ assert batches == [[{"id": 1}]]
+ assert session.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ def test_empty_page_yields_nothing(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([])]
+ manager = _manager()
+
+ assert self._get_rows(session, manager, "projects") == []
+
+ def test_resume_starts_from_saved_offset(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 1}], count=5, total_count=105)]
+ manager = _manager(resume=DbtResumeConfig(offset=100))
+
+ self._get_rows(session, manager, "projects")
+
+ assert _requested_query(session, 0)["offset"] == ["100"]
+
+ def test_runs_walk_newest_first(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([{"id": 1, "created_at": "2026-06-10T00:00:00Z"}])]
+ manager = _manager()
+
+ self._get_rows(session, manager, "runs")
+
+ assert _requested_query(session, 0)["order_by"] == ["-created_at"]
+
+ def test_runs_incremental_stops_once_page_dips_below_watermark(self):
+ watermark = datetime(2026, 6, 10, tzinfo=UTC)
+ session = mock.MagicMock()
+ page1_rows = [{"id": 3, "created_at": "2026-06-20T00:00:00Z"}]
+ page2_rows: list[dict[str, Any]] = [
+ {"id": 2, "created_at": "2026-06-11T00:00:00Z"},
+ # Within the 24h lookback window below the watermark: re-pulled so late status
+ # changes land; merge dedupes it on the primary key.
+ {"id": 1, "created_at": "2026-06-09T12:00:00Z"},
+ # Missing cursor value: kept to stay on the safe side.
+ {"id": 0},
+ # Below the effective watermark: already synced, walking stops here.
+ {"id": -1, "created_at": "2026-06-01T00:00:00Z"},
+ ]
+ session.get.side_effect = [
+ _page(page1_rows, count=100, total_count=500),
+ _page(page2_rows, count=100, total_count=500),
+ ]
+ manager = _manager()
+
+ batches = self._get_rows(
+ session,
+ manager,
+ "runs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ incremental_field="created_at",
+ )
+
+ assert batches == [page1_rows, page2_rows[:3]]
+ # The third page (offset=200) must never be requested — that's the whole point of the
+ # newest-first walk: incremental syncs don't re-crawl history.
+ assert session.get.call_count == 2
+
+ def test_runs_without_watermark_walk_all_pages(self):
+ session = mock.MagicMock()
+ page1_rows = [{"id": 2, "created_at": "2026-06-10T00:00:00Z"}]
+ page2_rows = [{"id": 1, "created_at": "2026-01-01T00:00:00Z"}]
+ session.get.side_effect = [
+ _page(page1_rows, count=100, total_count=101),
+ _page(page2_rows, count=1, total_count=101),
+ ]
+ manager = _manager()
+
+ batches = self._get_rows(
+ session,
+ manager,
+ "runs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="created_at",
+ )
+
+ assert batches == [page1_rows, page2_rows]
+
+ def test_custom_base_url_is_used(self):
+ session = mock.MagicMock()
+ session.get.side_effect = [_page([])]
+ manager = _manager()
+
+ self._get_rows(session, manager, "projects", custom_base_url="https://ab123.us1.dbt.com/")
+
+ assert session.get.call_args_list[0].args[0].startswith("https://ab123.us1.dbt.com/api/v3/accounts/12345/")
+
+
+class TestDbtSourceResponse:
+ def test_runs_response_shape(self):
+ response = dbt_source(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ endpoint="runs",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.name == "runs"
+ assert response.primary_keys == ["id"]
+ # Runs are walked newest-first; declaring asc here would checkpoint the watermark to
+ # ~now after the first batch and corrupt resume semantics.
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
+
+ def test_full_refresh_response_shape(self):
+ response = dbt_source(
+ api_token="token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ endpoint="projects",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.name == "projects"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
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
new file mode 100644
index 000000000000..14f52ea41566
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dbt/tests/test_dbt_source.py
@@ -0,0 +1,160 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.dbt import DbtResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dbt.source import DbtSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DbtSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestDbtSource:
+ def setup_method(self):
+ self.source = DbtSource()
+ self.team_id = 123
+ self.config = DbtSourceConfig(account_id="12345", api_token="dbtc_token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.DBT
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Dbt"
+ assert config.label == "dbt"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/dbt"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["account_id", "api_token", "region", "custom_base_url"]
+
+ account_field, token_field, region_field, custom_url_field = config.fields
+ assert isinstance(account_field, SourceFieldInputConfig)
+ assert account_field.required is True
+ assert account_field.secret is False
+
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert [option.value for option in region_field.options] == ["us", "emea", "au"]
+ assert region_field.defaultValue == "us"
+
+ assert isinstance(custom_url_field, SourceFieldInputConfig)
+ assert custom_url_field.required is False
+
+ 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"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, incremental",
+ [
+ ("accounts", False),
+ ("projects", False),
+ ("environments", False),
+ ("jobs", False),
+ ("users", False),
+ ("runs", True),
+ ],
+ )
+ def test_schema_incremental_support(self, endpoint, incremental):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[endpoint].supports_incremental is incremental
+ # The lookback re-pulls a window of rows each run, so merge is the only safe mode.
+ assert schemas[endpoint].supports_append is False
+
+ def test_users_not_synced_by_default(self):
+ # Listing users needs permissions many read-only tokens lack; a default connection
+ # must not enable a table whose first sync would 403.
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["users"].should_sync_default is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["runs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "runs"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "Invalid dbt API token"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dbt.source.validate_dbt_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="runs")
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with(
+ api_token="dbtc_token",
+ account_id="12345",
+ region="us",
+ custom_base_url=None,
+ team_id=self.team_id,
+ schema_name="runs",
+ )
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DbtResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dbt.source.dbt_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_dbt_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "runs"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "created_at"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_dbt_source.assert_called_once()
+ kwargs = mock_dbt_source.call_args.kwargs
+ assert kwargs["api_token"] == "dbtc_token"
+ assert kwargs["account_id"] == "12345"
+ assert kwargs["region"] == "us"
+ assert kwargs["custom_base_url"] is None
+ assert kwargs["endpoint"] == "runs"
+ assert kwargs["team_id"] == 42
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "created_at"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dbt.source.dbt_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_dbt_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "projects"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_dbt_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index b1f17d7385d1..dfa35f7a54b0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1140,7 +1140,10 @@ class Db2SourceConfig(config.Config):
@config.config
class DbtSourceConfig(config.Config):
- pass
+ account_id: str
+ api_token: str
+ region: Literal["us", "emea", "au"] = config.value(default="us")
+ custom_base_url: str | None = None
@config.config