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 deepgram import source (#70042)

Tom Owers38018449d427
diff --git a/frontend/public/services/deepgram.png b/frontend/public/services/deepgram.png
new file mode 100644
index 000000000000..d53d692373f0
Binary files /dev/null and b/frontend/public/services/deepgram.png differ
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 f983dca89c53..03bd0327952e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -135,6 +135,7 @@ the row lists both.
| datadog | HTTP | requests | ✅ |
| decagon | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
+| deepgram | HTTP | requests | ✅ |
| delighted | HTTP | requests | ✅ |
| devin_ai | HTTP | requests | ✅ |
| ding_connect | HTTP | requests | ✅ |
@@ -513,7 +514,6 @@ doesn't conflict with concurrent PRs.
- datorama
- db2
- dbt
-- deepgram
- deno_deploy
- deputy
- digitalocean
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/canonical_descriptions.py
new file mode 100644
index 000000000000..5f237fee2c83
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/canonical_descriptions.py
@@ -0,0 +1,86 @@
+"""Canonical, documentation-sourced descriptions for Deepgram Management API endpoints and columns.
+
+Sourced from the official Deepgram Management API reference
+(https://developers.deepgram.com/reference/management-api). Keyed by the endpoint names in
+`settings.py` `DEEPGRAM_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table.
+Columns absent here fall back to LLM enrichment. Every fan-out row carries a `project_id` column
+identifying the Deepgram project it belongs to.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://developers.deepgram.com/reference/management-api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "A Deepgram project — the top-level container that owns members, API keys, "
+ "balances, and requests.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Unique identifier for the project.",
+ "name": "The project's display name.",
+ },
+ },
+ "members": {
+ "description": "A user who is a member of the project, with their assigned scopes.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Identifier of the project the member belongs to.",
+ "member_id": "Unique identifier for the member.",
+ "email": "The member's email address.",
+ "first_name": "The member's first name.",
+ "last_name": "The member's last name.",
+ "scopes": "The access scopes granted to the member within the project.",
+ },
+ },
+ "keys": {
+ "description": "An API key belonging to the project. The nested key object is flattened onto "
+ "the row root, alongside the member the key was created for.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Identifier of the project the API key belongs to.",
+ "api_key_id": "Unique identifier for the API key.",
+ "comment": "The human-readable label given to the key.",
+ "scopes": "The access scopes granted to the key.",
+ "tags": "Tags associated with the key.",
+ "created": "Time at which the key was created.",
+ "member": "The member the key was issued to.",
+ },
+ },
+ "balances": {
+ "description": "A funding balance for the project, in the account's billing units.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Identifier of the project the balance belongs to.",
+ "balance_id": "Unique identifier for the balance.",
+ "amount": "The remaining amount on the balance.",
+ "units": "The units the balance is measured in (e.g. usd, hour).",
+ "purchase_order_id": "Identifier of the purchase the balance came from.",
+ },
+ },
+ "invites": {
+ "description": "A pending invitation for a user to join the project.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Identifier of the project the invite is for.",
+ "email": "The email address the invitation was sent to.",
+ "scope": "The scope the invited user will be granted on joining.",
+ },
+ },
+ "requests": {
+ "description": "A single inference request made against the project, with model/feature "
+ "metadata, the response code, and the time it was created. Synced incrementally on `created`.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "project_id": "Identifier of the project the request was made under.",
+ "request_id": "Unique identifier for the request.",
+ "created": "Time at which the request was created.",
+ "path": "The API path the request was made to.",
+ "api_key_id": "Identifier of the API key that made the request.",
+ "response": "Metadata about the response, including its status code and details.",
+ "callback": "Callback delivery metadata, when the request used a callback URL.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/deepgram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/deepgram.py
new file mode 100644
index 000000000000..c241dff7f3d0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/deepgram.py
@@ -0,0 +1,282 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlsplit, urlunsplit
+
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.settings import (
+ DEEPGRAM_ENDPOINTS,
+ DeepgramEndpointConfig,
+)
+
+DEEPGRAM_BASE_URL = "https://api.deepgram.com/v1"
+
+# The requests log caps `limit` at 1000; use the max to minimise round trips.
+REQUESTS_PAGE_SIZE = 1000
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class DeepgramRetryableError(Exception):
+ pass
+
+
+class DeepgramResumeConfig:
+ # Stable project-id bookmark of the project currently being fetched. Not a positional index so a
+ # project added/removed between a crash and the retry can't resume us into the wrong project.
+ project_id: str | None = None
+ # Next page to fetch for the paginated requests endpoint (0-indexed). None for the unpaginated
+ # full-refresh endpoints.
+ page: int | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Token {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _get_session(api_key: str) -> requests.Session:
+ # The API key travels in the Authorization header on every request; register it for value-based
+ # redaction so a failed or sampled request never persists the customer's secret in HTTP logs.
+ return make_tracked_session(redact_values=(api_key,))
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ DeepgramRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_json(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger, params: dict[str, Any]
+) -> dict:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DeepgramRetryableError(f"Deepgram API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Deepgram API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # Listing projects is the cheapest probe that proves the token is genuine; it is also the seed for
+ # every other (project-scoped) endpoint, so a token that can't list projects can't sync anything.
+ try:
+ response = _get_session(api_key).get(
+ f"{DEEPGRAM_BASE_URL}/projects",
+ headers=_get_headers(api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _list_project_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ data = _fetch_json(session, f"{DEEPGRAM_BASE_URL}/projects", headers, logger, params={})
+ return [project["project_id"] for project in data.get("projects", []) if project.get("project_id")]
+
+
+def _format_start_value(value: Any) -> str:
+ """Format an incremental cursor value for Deepgram's `start` filter.
+
+ Deepgram accepts YYYY-MM-DD or ISO 8601; we send full ISO 8601 with a Z suffix. Future-dated
+ cursors are capped at now so we never build a start-in-the-future filter (harmless but pointless).
+ """
+ now = datetime.now(UTC)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ aware = now if aware > now else aware
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ capped = now.date() if value > now.date() else value
+ return capped.isoformat()
+ return str(value)
+
+
+def _redact_url_userinfo(url: str) -> str:
+ """Strip embedded userinfo (`user:pass@`) from a URL.
+
+ Deepgram callback URLs can carry Basic Auth credentials in the userinfo component; those must not
+ land in the warehouse where anyone with query access could read them. The host/path is preserved
+ so the row still records which callback was used.
+ """
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return url
+ if "@" not in parts.netloc:
+ return url
+ host = parts.netloc.rsplit("@", 1)[1]
+ return urlunsplit(parts._replace(netloc=host))
+
+
+def _transform_row(row: dict[str, Any], project_id: str, config: DeepgramEndpointConfig) -> dict[str, Any]:
+ if config.flatten_key and isinstance(row.get(config.flatten_key), dict):
+ nested = row.pop(config.flatten_key)
+ row = {**row, **nested}
+ # Fan-out rows carry the parent project's id so the composite primary key stays unique table-wide.
+ row["project_id"] = project_id
+ # Request-log rows can echo the callback URL, which may embed Basic Auth credentials.
+ if isinstance(row.get("callback"), str):
+ row["callback"] = _redact_url_userinfo(row["callback"])
+ # A row missing a required primary-key field would let the delta merge build a partial predicate
+ # and overwrite unrelated rows in the same project, so fail loudly instead of emitting it.
+ for primary_key in config.primary_keys:
+ if row.get(primary_key) is None:
+ raise ValueError(f"Deepgram {config.name} row missing required primary key '{primary_key}'")
+ return row
+
+
+def _build_request_params(
+ config: DeepgramEndpointConfig,
+ page: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": REQUESTS_PAGE_SIZE, "page": page}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params["start"] = _format_start_value(db_incremental_field_last_value)
+ return params
+
+
+def _iter_project_endpoint(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepgramResumeConfig],
+ config: DeepgramEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ project_ids = _list_project_ids(session, headers, logger)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = project_ids
+ resume_page: int | None = None
+ if resume is not None and resume.project_id is not None and resume.project_id in project_ids:
+ remaining = project_ids[project_ids.index(resume.project_id) :]
+ resume_page = resume.page
+ logger.debug(f"Deepgram: resuming {config.name} from project_id={resume.project_id}, page={resume_page}")
+
+ for index, project_id in enumerate(remaining):
+ base_url = f"{DEEPGRAM_BASE_URL}/projects/{project_id}{config.path}"
+
+ if config.paginated:
+ page = resume_page if index == 0 and resume_page is not None else 0
+ while True:
+ params = _build_request_params(
+ config, page, should_use_incremental_field, db_incremental_field_last_value
+ )
+ data = _fetch_json(session, base_url, headers, logger, params)
+ items = data.get(config.data_key, [])
+
+ if items:
+ yield [_transform_row(item, project_id, config) for item in items]
+
+ # A short page (fewer rows than the limit) or an empty page means we've reached the end.
+ if len(items) < REQUESTS_PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the last saved page rather than skipping
+ # it; merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(DeepgramResumeConfig(project_id=project_id, page=page))
+ else:
+ data = _fetch_json(session, base_url, headers, logger, params={})
+ items = data.get(config.data_key, [])
+ if items:
+ yield [_transform_row(item, project_id, config) for item in items]
+
+ resume_page = None
+ # Advance the bookmark to the next project so a crash between projects resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(DeepgramResumeConfig(project_id=remaining[index + 1], page=0))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepgramResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = DEEPGRAM_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every request so urllib3 keeps the connection alive instead of
+ # re-handshaking per project/page.
+ session = _get_session(api_key)
+
+ if config.is_project_list:
+ data = _fetch_json(session, f"{DEEPGRAM_BASE_URL}/projects", headers, logger, params={})
+ items = data.get(config.data_key, [])
+ if items:
+ yield items
+ return
+
+ yield from _iter_project_endpoint(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+
+def deepgram_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepgramResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = DEEPGRAM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ 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,
+ ),
+ primary_keys=config.primary_keys,
+ # The requests log's default order isn't documented and can't be curl-verified without a live
+ # token, so we use "desc": the pipeline finalises the incremental watermark (max `created`) only
+ # at job end rather than checkpointing per batch, which stays correct regardless of the actual
+ # arrival order. The `start` filter still bounds each incremental sync server-side, so this is
+ # not a re-fetch-all-history situation. Full-refresh endpoints keep the default "asc".
+ sort_mode="desc" if config.supports_incremental else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/settings.py
new file mode 100644
index 000000000000..388b3e222896
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/settings.py
@@ -0,0 +1,95 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class DeepgramEndpointConfig:
+ name: str
+ # Path suffix appended to /v1/projects/{project_id} for the per-project fan-out endpoints.
+ # Empty string is the top-level /v1/projects list itself (see `is_project_list`).
+ path: str
+ # Key in the JSON response body that holds the list of rows (Deepgram wraps every list in an
+ # envelope, e.g. {"projects": [...]}, {"requests": [...]}).
+ data_key: str
+ primary_keys: list[str]
+ # Stable creation-time field used for datetime partitioning. Never a mutable field.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ supports_incremental: bool = False
+ # page/limit pagination — only the requests log supports it; the other endpoints return a full
+ # unpaginated array.
+ paginated: bool = False
+ # The top-level /v1/projects list. It seeds the fan-out and is not itself fanned out per project.
+ is_project_list: bool = False
+ # Sub-object to lift into the row root before keying/partitioning (e.g. /keys nests the key under
+ # "api_key"). None means the row is used as-is.
+ flatten_key: Optional[str] = None
+ should_sync_default: bool = True
+
+
+DEEPGRAM_ENDPOINTS: dict[str, DeepgramEndpointConfig] = {
+ "projects": DeepgramEndpointConfig(
+ name="projects",
+ path="",
+ data_key="projects",
+ primary_keys=["project_id"],
+ is_project_list=True,
+ ),
+ "members": DeepgramEndpointConfig(
+ name="members",
+ path="/members",
+ data_key="members",
+ # member_id is only unique within a project, so key on the pair to stay unique table-wide.
+ primary_keys=["project_id", "member_id"],
+ ),
+ "keys": DeepgramEndpointConfig(
+ name="keys",
+ path="/keys",
+ data_key="api_keys",
+ primary_keys=["project_id", "api_key_id"],
+ partition_key="created",
+ flatten_key="api_key",
+ ),
+ "balances": DeepgramEndpointConfig(
+ name="balances",
+ path="/balances",
+ data_key="balances",
+ primary_keys=["project_id", "balance_id"],
+ ),
+ "invites": DeepgramEndpointConfig(
+ name="invites",
+ path="/invites",
+ data_key="invites",
+ # Invites have no id; the invited email is unique per project.
+ primary_keys=["project_id", "email"],
+ ),
+ # The request log is the highest-value stream: one row per inference request with model/feature
+ # metadata, response code, and a `created` timestamp. It is the only endpoint with a genuine
+ # server-side timestamp filter (`start`/`end` on `created`) and page/limit pagination, so it is
+ # the only one synced incrementally.
+ "requests": DeepgramEndpointConfig(
+ name="requests",
+ path="/requests",
+ data_key="requests",
+ primary_keys=["project_id", "request_id"],
+ partition_key="created",
+ supports_incremental=True,
+ paginated=True,
+ incremental_fields=[
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(DEEPGRAM_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DEEPGRAM_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/source.py
index 96bcbb9981df..3e51b4a2ccd5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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.deepgram.deepgram import (
+ DeepgramResumeConfig,
+ deepgram_source,
+ validate_credentials as validate_deepgram_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.settings import (
+ DEEPGRAM_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DeepgramSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DeepgramSource(SimpleSource[DeepgramSourceConfig]):
+class DeepgramSource(ResumableSource[DeepgramSourceConfig, DeepgramResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DEEPGRAM
@@ -24,8 +48,91 @@ class DeepgramSource(SimpleSource[DeepgramSourceConfig]):
name=SchemaExternalDataSourceType.DEEPGRAM,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Deepgram",
+ releaseStatus=ReleaseStatus.ALPHA,
+ unreleasedSource=True,
+ caption="""Enter your Deepgram API key to sync your Deepgram Management API data into the PostHog Data warehouse.
+
+You can create an API key in your [Deepgram Console](https://console.deepgram.com/) under **Settings → API Keys**. A key with a read-capable scope (e.g. `member`) is sufficient — the source only reads projects, members, keys, balances, invites, and the request log.""",
iconPath="/static/services/deepgram.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/deepgram",
keywords=["speech-to-text", "transcription", "voice ai", "usage"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.deepgram.com": "Your Deepgram API key is invalid or has been revoked. Create a new key in your Deepgram Console, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.deepgram.com": "Your Deepgram API key is missing the scope needed to sync this data. Grant a read-capable scope in your Deepgram Console, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: DeepgramSourceConfig,
+ 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 = DEEPGRAM_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ detected_primary_keys=endpoint_config.primary_keys,
+ )
+
+ 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: DeepgramSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_deepgram_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Deepgram API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DeepgramResumeConfig]:
+ return ResumableSourceManager[DeepgramResumeConfig](inputs, DeepgramResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DeepgramSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DeepgramResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return deepgram_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py
new file mode 100644
index 000000000000..36801f72590b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py
@@ -0,0 +1,231 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram import deepgram
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.deepgram import (
+ DeepgramResumeConfig,
+ _build_request_params,
+ _format_start_value,
+ _transform_row,
+ deepgram_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.settings import DEEPGRAM_ENDPOINTS
+
+
+class TestFormatStartValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_start_value(value) == expected
+
+ def test_no_plus_zero_offset(self) -> None:
+ # A +00:00 offset (isoformat default) is not the ISO shape we send; assert we emit the Z form.
+ assert "+00:00" not in _format_start_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_future_datetime_clamped_to_now(self) -> None:
+ # Asking for requests created after "now" is pointless; cap it so we don't skip the window.
+ assert _format_start_value(datetime(2027, 1, 1, tzinfo=UTC)) == "2026-06-15T12:00:00.000Z"
+
+
+class TestBuildRequestParams:
+ def test_incremental_sets_start_and_page_size(self) -> None:
+ params = _build_request_params(
+ DEEPGRAM_ENDPOINTS["requests"],
+ page=3,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert params["page"] == 3
+ assert params["limit"] == deepgram.REQUESTS_PAGE_SIZE
+ assert params["start"] == "2026-03-04T02:58:14.000Z"
+
+ def test_non_incremental_omits_start(self) -> None:
+ params = _build_request_params(
+ DEEPGRAM_ENDPOINTS["requests"],
+ page=0,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert "start" not in params
+
+
+class TestTransformRow:
+ def test_injects_project_id(self) -> None:
+ row = _transform_row({"member_id": "m1"}, "proj-1", DEEPGRAM_ENDPOINTS["members"])
+ assert row["project_id"] == "proj-1"
+ assert row["member_id"] == "m1"
+
+ def test_flattens_nested_key_to_root(self) -> None:
+ # /keys nests the key under "api_key"; api_key_id must land at the row root or the composite
+ # primary key can't be built and the delta merge multi-matches duplicate rows.
+ row = _transform_row(
+ {"api_key": {"api_key_id": "k1", "comment": "ci"}, "member": {"email": "[email protected]"}},
+ "proj-1",
+ DEEPGRAM_ENDPOINTS["keys"],
+ )
+ assert row["api_key_id"] == "k1"
+ assert row["comment"] == "ci"
+ assert row["project_id"] == "proj-1"
+ assert row["member"] == {"email": "[email protected]"}
+ assert "api_key" not in row
+
+ @parameterized.expand(
+ [
+ ("basic_auth", "https://user:[email protected]/cb", "https://hooks.example.com/cb"),
+ ("no_creds", "https://hooks.example.com/cb", "https://hooks.example.com/cb"),
+ ("not_a_url", "not-a-url", "not-a-url"),
+ ]
+ )
+ def test_redacts_callback_userinfo(self, _name: str, callback: str, expected: str) -> None:
+ # A callback URL can embed Basic Auth creds; they must not reach the warehouse.
+ row = _transform_row({"request_id": "r1", "callback": callback}, "proj-1", DEEPGRAM_ENDPOINTS["requests"])
+ assert row["callback"] == expected
+
+ def test_missing_primary_key_raises(self) -> None:
+ # A row missing request_id would let the merge overwrite unrelated rows; fail instead of emit.
+ with pytest.raises(ValueError, match="request_id"):
+ _transform_row({"created": "2026-01-01"}, "proj-1", DEEPGRAM_ENDPOINTS["requests"])
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ with patch.object(deepgram, "make_tracked_session", return_value=session):
+ assert validate_credentials("token") is expected
+
+ def test_network_error_is_false(self) -> None:
+ with patch.object(deepgram, "make_tracked_session", side_effect=Exception("boom")):
+ assert validate_credentials("token") is False
+
+
+def _fake_manager(resume: DeepgramResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestGetRows:
+ def _run(self, endpoint: str, fetch_side_effect: Any, manager: MagicMock, **kwargs: Any) -> list[list[dict]]:
+ with (
+ patch.object(deepgram, "make_tracked_session", return_value=MagicMock()),
+ patch.object(deepgram, "_fetch_json", side_effect=fetch_side_effect),
+ ):
+ return list(
+ get_rows(
+ api_key="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ def test_project_list_yields_projects_without_fan_out(self) -> None:
+ projects = [{"project_id": "p1"}, {"project_id": "p2"}]
+
+ def fetch(_session, url, _headers, _logger, params=None):
+ assert url.endswith("/projects")
+ return {"projects": projects}
+
+ batches = self._run("projects", fetch, _fake_manager())
+ assert batches == [projects]
+
+ def test_fan_out_injects_project_id_per_row(self) -> None:
+ def fetch(_session, url, _headers, _logger, params=None):
+ if url.endswith("/projects"):
+ return {"projects": [{"project_id": "p1"}, {"project_id": "p2"}]}
+ return {"members": [{"member_id": "m1"}]}
+
+ batches = self._run("members", fetch, _fake_manager())
+ project_ids = {row["project_id"] for batch in batches for row in batch}
+ assert project_ids == {"p1", "p2"}
+
+ def test_paginated_requests_terminate_on_short_page(self) -> None:
+ # limit is patched to 2, so a page returning fewer than 2 rows ends pagination for a project.
+ pages = {0: [{"request_id": "r1"}, {"request_id": "r2"}], 1: [{"request_id": "r3"}]}
+
+ def fetch(_session, url, _headers, _logger, params):
+ if url.endswith("/projects"):
+ return {"projects": [{"project_id": "p1"}]}
+ return {"requests": pages[params["page"]]}
+
+ with patch.object(deepgram, "REQUESTS_PAGE_SIZE", 2):
+ batches = self._run(
+ "requests",
+ fetch,
+ _fake_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ request_ids = [row["request_id"] for batch in batches for row in batch]
+ assert request_ids == ["r1", "r2", "r3"]
+
+ def test_resume_starts_from_saved_project(self) -> None:
+ def fetch(_session, url, _headers, _logger, params=None):
+ if url.endswith("/projects"):
+ return {"projects": [{"project_id": "p1"}, {"project_id": "p2"}]}
+ return {"members": [{"member_id": f"m-{url.split('/projects/')[1].split('/')[0]}"}]}
+
+ manager = _fake_manager(DeepgramResumeConfig(project_id="p2", page=None))
+ batches = self._run("members", fetch, manager)
+ project_ids = {row["project_id"] for batch in batches for row in batch}
+ assert project_ids == {"p2"} # p1 skipped — already synced before the crash
+
+ def test_state_saved_advances_page_after_yield(self) -> None:
+ pages = {0: [{"request_id": "r1"}, {"request_id": "r2"}], 1: [{"request_id": "r3"}]}
+
+ def fetch(_session, url, _headers, _logger, params):
+ if url.endswith("/projects"):
+ return {"projects": [{"project_id": "p1"}]}
+ return {"requests": pages[params["page"]]}
+
+ manager = _fake_manager()
+ with patch.object(deepgram, "REQUESTS_PAGE_SIZE", 2):
+ self._run(
+ "requests", fetch, manager, should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
+ # After yielding page 0 we persist page 1 so a crash re-fetches page 1 rather than restarting.
+ saved_pages = [call.args[0].page for call in manager.save_state.call_args_list]
+ assert 1 in saved_pages
+
+
+class TestDeepgramSource:
+ @parameterized.expand(
+ [
+ ("requests_is_incremental", "requests", "desc", ["project_id", "request_id"]),
+ ("members_full_refresh", "members", "asc", ["project_id", "member_id"]),
+ ("projects_top_level", "projects", "asc", ["project_id"]),
+ ]
+ )
+ def test_source_response_shape(self, _name: str, endpoint: str, sort_mode: str, primary_keys: list[str]) -> None:
+ response = deepgram_source(
+ api_key="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+
+ def test_partitioned_only_when_partition_key_set(self) -> None:
+ # requests has a stable `created` partition key; members has none.
+ assert deepgram_source("t", "requests", MagicMock(), MagicMock()).partition_mode == "datetime"
+ assert deepgram_source("t", "members", MagicMock(), MagicMock()).partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram_source.py
new file mode 100644
index 000000000000..efa7fa20ca1b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram_source.py
@@ -0,0 +1,107 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.deepgram import DeepgramResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.source import DeepgramSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DeepgramSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "requests",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestDeepgramSourceClass:
+ def setup_method(self) -> None:
+ self.source = DeepgramSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DEEPGRAM
+
+ def test_config_has_required_password_api_key(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.name == "api_key"
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+
+ def test_config_stays_unreleased_alpha_with_docs(self) -> None:
+ config = self.source.get_source_config
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/deepgram"
+
+ @parameterized.expand(
+ [
+ ("requests_incremental", "requests", True),
+ ("members_full_refresh", "members", False),
+ ("balances_full_refresh", "balances", False),
+ ("projects_full_refresh", "projects", False),
+ ]
+ )
+ def test_only_requests_supports_incremental(self, _name: str, endpoint: str, incremental: bool) -> None:
+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental is incremental
+
+ def test_schemas_expose_composite_primary_keys(self) -> None:
+ # Fan-out children must key on [project_id, ...] to stay unique table-wide; a regression to a
+ # bare id would seed duplicate rows across projects.
+ schemas = {s.name: s.detected_primary_keys for s in self.source.get_schemas(MagicMock(), team_id=1)}
+ assert schemas["members"] == ["project_id", "member_id"]
+ assert schemas["requests"] == ["project_id", "request_id"]
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["requests"])
+ assert [s.name for s in schemas] == ["requests"]
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, api_ok: bool, expected: bool) -> None:
+ with patch.object(source_module, "validate_deepgram_credentials", return_value=api_ok):
+ ok, _error = self.source.validate_credentials(DeepgramSourceConfig(api_key="k"), team_id=1)
+ assert ok is expected
+
+ def test_non_retryable_errors_cover_auth(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DeepgramResumeConfig
+
+ @parameterized.expand([("incremental_on", True), ("incremental_off", False)])
+ def test_source_for_pipeline_gates_last_value_on_incremental(self, _name: str, use_incremental: bool) -> None:
+ config = DeepgramSourceConfig(api_key="k")
+ inputs = _inputs(should_use_incremental_field=use_incremental, db_incremental_field_last_value="2026-01-01")
+ with patch.object(source_module, "deepgram_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "k"
+ assert kwargs["should_use_incremental_field"] is use_incremental
+ # The last value is only forwarded when the sync is actually incremental.
+ assert kwargs["db_incremental_field_last_value"] == ("2026-01-01" if use_incremental else 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 754358d5253e..55ceb8f10df8 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
@@ -1029,7 +1029,7 @@ class DeelSourceConfig(config.Config):
@config.config
class DeepgramSourceConfig(config.Config):
- pass
+ api_key: str
@config.config