: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add deepgram usage, billing and model tables (#105188)
Tom Owers416f2d5879c2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 74ab96e60797..c04db356476e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2381,14 +2381,14 @@ Today (6): `balances`, `invites`, `keys`, `members`, `projects`, `requests`Diffed against: <https://developers.deepgram.com/openapi.json>-- [ ] `/v1/projects/{project_id}/usage (+ /usage/breakdown)` — the headline metric: transcription/TTS usage per project, sliced by model and feature (high)-- [ ] `/v1/projects/{project_id}/billing/breakdown` — spend broken down per project — pairs with balances to explain credit burn (high)-- [ ] `/v1/models and /v1/projects/{project_id}/models` — lookup table resolving the model IDs that appear on synced request rows (high)+- [x] `/v1/projects/{project_id}/usage (+ /usage/breakdown)` — the headline metric: transcription/TTS usage per project, sliced by model and feature (high)+- [x] `/v1/projects/{project_id}/billing/breakdown` — spend broken down per project — pairs with balances to explain credit burn (high)+- [x] `/v1/models and /v1/projects/{project_id}/models` — lookup table resolving the model IDs that appear on synced request rows (high)- [ ] `/v1/projects/{project_id}/purchases` — credit purchase transactions behind the balance (medium)-- [ ] `/v1/projects/{project_id}/usage/fields and /billing/fields` — the set of models, methods and features seen in a period — breakdown dimensions for usage (medium)+- [x] `/v1/projects/{project_id}/usage/fields and /billing/fields` — the set of models, methods and features seen in a period — breakdown dimensions for usage (medium)- [ ] `/v1/projects/{project_id}/members/{member_id}/scopes` — membership permissions per project member (low)-Note: The Management API is only ~28 GET operations; the missing pieces are almost entirely the usage/billing analytics half of it. Agent configuration endpoints (/agents, /agent-variables) were excluded as config.+Note: The Management API is only ~28 GET operations; the missing pieces are almost entirely the usage/billing analytics half of it. Agent configuration endpoints (/agents, /agent-variables) were excluded as config. Of the ticked entries, `/v1/projects/{project_id}/usage` itself was left out: its response carries only the requested window and resolution, with no results payload, and the vendor points at `/usage/breakdown` for the numbers. `/v1/models` was covered by the project-scoped variant, which returns the same models plus the project's non-public ones.## Deepsource — gapsdiff --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.pyindex 5f237fee2c83..875ce8a392a2 100644--- 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@@ -83,4 +83,89 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"callback": "Callback delivery metadata, when the request used a callback URL.",},},+ "models": {+ "description": "A model the project can call, public or non-public, with the identifier that "+ "request rows refer to. Speech-to-text and text-to-speech models share the table and are told "+ "apart by `model_type`.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Identifier of the project the model is available to.",+ "uuid": "Unique identifier for the model, as carried on request rows.",+ "model_type": "Whether the model came from the speech-to-text (stt) or text-to-speech (tts) catalogue.",+ "name": "The model's short name, for example nova-3.",+ "canonical_name": "The fully qualified model name used when calling the API.",+ "architecture": "The model family the model belongs to.",+ "languages": "IETF language tags the model supports.",+ "version": "Version identifier of the model.",+ "batch": "Whether the model can be used for batch (pre-recorded) speech-to-text.",+ "streaming": "Whether the model can be used for streaming speech-to-text.",+ "formatted_output": "Whether the model can return formatted output.",+ "metadata": "Voice metadata for a text-to-speech model, such as accent, age and sample audio.",+ },+ },+ "usage_breakdown": {+ "description": "Usage totals for one period of a project, broken down by the dimensions the "+ "request grouped on. Synced incrementally on the period's start date.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Identifier of the project the usage belongs to.",+ "start": "First day of the period the row covers.",+ "end": "Last day of the period the row covers.",+ "grouping_key": "The dimension values this row aggregates, joined into one value. Empty when the row covers a whole period rather than a slice of it.",+ "hours": "Audio hours processed.",+ "total_hours": "Total hours including all processing.",+ "agent_hours": "Agent hours used.",+ "tokens_in": "Number of input tokens.",+ "tokens_out": "Number of output tokens.",+ "tts_characters": "Number of text-to-speech characters processed.",+ "requests": "Number of requests.",+ "accessor": "The accessor the usage is attributed to, when grouped by accessor.",+ "endpoint": "The API endpoint the usage came from, when grouped by endpoint.",+ "feature_set": "The set of features used, when grouped by feature set.",+ "models": "The models used, when grouped by model.",+ "method": "The processing method used, when grouped by method.",+ "tags": "The tags the requests carried, when grouped by tags.",+ "deployment": "The deployment the usage ran on, when grouped by deployment.",+ },+ },+ "billing_breakdown": {+ "description": "What a project was billed for one period, broken down by the dimensions the "+ "request grouped on. Synced incrementally on the period's start date.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Identifier of the project the spend belongs to.",+ "start": "First day of the period the row covers.",+ "end": "Last day of the period the row covers.",+ "grouping_key": "The dimension values this row aggregates, joined into one value. Empty when the row covers a whole period rather than a slice of it.",+ "dollars": "Cost in US dollars for the row's period and grouping.",+ "accessor": "The accessor the spend is attributed to, when grouped by accessor.",+ "deployment": "The deployment the spend ran on, when grouped by deployment.",+ "line_item": "The billed line item, for example streaming::nova-3, when grouped by line item.",+ "tags": "The tags the billed requests carried, when grouped by tags.",+ },+ },+ "usage_fields": {+ "description": "The models, tags, processing methods and features the project used in the "+ "period. These are the dimensions a usage breakdown can be sliced by. One row per value.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Identifier of the project the value was seen in.",+ "field": "Which set the value belongs to: models, tags, processing_methods or features.",+ "value": "The value itself. For a model this is the model identifier.",+ "name": "The model's name. Only set for a model row.",+ "language": "The IETF language tag the model supports. Only set for a model row.",+ "version": "Version identifier of the model. Only set for a model row.",+ },+ },+ "billing_fields": {+ "description": "The accessors, deployments, tags and line items the project was billed on in "+ "the period. These are the dimensions a billing breakdown can be sliced by. One row per value.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Identifier of the project the value was seen in.",+ "field": "Which set the value belongs to: accessors, deployments, tags or line_items.",+ "value": "The value itself. For a line item this is the line item name.",+ "description": "The human-readable description of the line item. Only set for a line item row.",+ },+ },}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.pyindex b72160b69e6b..1c7890357b19 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/deepgram.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/deepgram.py@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.sDEEPGRAM_ENDPOINTS,DeepgramEndpointConfig,)+from products.warehouse_sources.backend.types import IncrementalFieldTypeDEEPGRAM_BASE_URL = "https://api.deepgram.com/v1"@@ -114,6 +115,26 @@ def _format_start_value(value: Any) -> str:return str(value)+def _format_start_date(value: Any) -> str:+ """Format an incremental cursor value for the usage and billing endpoints' `start` filter.++ Those endpoints accept whole days only (YYYY-MM-DD) and reject a timestamp, so a datetime cursor+ is truncated to its UTC date. The boundary day is therefore re-read in full each sync. The merge+ collapses that re-read on the composite primary key, which is also what keeps an in-progress+ day's totals current. Future-dated cursors are capped at today so we never ask for a window that+ has not started.+ """+ today = datetime.now(UTC).date()+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ resolved = aware.astimezone(UTC).date()+ elif isinstance(value, date):+ resolved = value+ else:+ return str(value)[:10]+ return min(resolved, today).isoformat()++def _redact_url_userinfo(url: str) -> str:"""Strip embedded userinfo (`user:pass@`) from a URL.@@ -131,48 +152,135 @@ def _redact_url_userinfo(url: str) -> str:return urlunsplit(parts._replace(netloc=host))-def _make_child_map(config: DeepgramEndpointConfig) -> Callable[[dict[str, Any]], dict[str, Any]]:+def _grouping_key(row: dict[str, Any], dimensions: list[str]) -> str:+ """Build the stable slice identifier an aggregate row is keyed on.++ Each dimension is null unless the request grouped by it, so no single dimension can key the row.+ Joining all of them gives one non-null value per slice, and an empty string when the response is+ grouped by period alone. The merge predicate then stays exact whichever grouping comes back.+ """+ parts = []+ for dimension in dimensions:+ value = row.get(dimension)+ if isinstance(value, list):+ parts.append(",".join(str(item) for item in value))+ else:+ parts.append("" if value is None else str(value))+ return "|".join(parts)+++def _expand_models(row: dict[str, Any]) -> list[dict[str, Any]]:+ # The catalogue arrives as two parallel arrays; each model becomes a row tagged with the array it+ # came from, which is the only place the speech-to-text / text-to-speech split is recorded.+ parent_id = row.get(_PARENT_ID_KEY)+ return [+ {**model, "model_type": model_type, _PARENT_ID_KEY: parent_id}+ for model_type in ("stt", "tts")+ for model in row.get(model_type) or []+ ]+++def _expand_usage_fields(row: dict[str, Any]) -> list[dict[str, Any]]:+ parent_id = row.get(_PARENT_ID_KEY)+ rows: list[dict[str, Any]] = [+ {+ _PARENT_ID_KEY: parent_id,+ "field": "models",+ "value": model.get("model_id"),+ "name": model.get("name"),+ "language": model.get("language"),+ "version": model.get("version"),+ }+ for model in row.get("models") or []+ ]+ rows.extend(+ {_PARENT_ID_KEY: parent_id, "field": field, "value": value}+ for field in ("tags", "processing_methods", "features")+ for value in row.get(field) or []+ )+ return rows+++def _expand_billing_fields(row: dict[str, Any]) -> list[dict[str, Any]]:+ parent_id = row.get(_PARENT_ID_KEY)+ rows: list[dict[str, Any]] = [+ {_PARENT_ID_KEY: parent_id, "field": field, "value": value}+ for field in ("accessors", "deployments", "tags")+ for value in row.get(field) or []+ ]+ # Line items arrive as a name -> human-readable description map rather than a list.+ rows.extend(+ {_PARENT_ID_KEY: parent_id, "field": "line_items", "value": name, "description": description}+ for name, description in (row.get("line_items") or {}).items()+ )+ return rows+++# Endpoints whose response body is several parallel collections instead of one list of rows. Each+# expander turns one body into the rows the table holds; `data_key="$"` hands it the whole body.+_ROW_EXPANDERS: dict[str, Callable[[dict[str, Any]], list[dict[str, Any]]]] = {+ "models": _expand_models,+ "usage_fields": _expand_usage_fields,+ "billing_fields": _expand_billing_fields,+}+++def _normalize_row(config: DeepgramEndpointConfig, row: dict[str, Any]) -> 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.+ if _PARENT_ID_KEY in row:+ row[_PARENT_ID_FIELD] = row.pop(_PARENT_ID_KEY)+ # 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"])+ if config.grouping_dimensions:+ row["grouping_key"] = _grouping_key(row, config.grouping_dimensions)+ # 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 _make_child_map(+ config: DeepgramEndpointConfig,+) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:"""Per-row transform for a fanned-out (project-scoped) endpoint.Reproduces the old ``_transform_row``: flatten a nested sub-object into the row root, lift theframework's parent-id key back to the flat ``project_id`` column, redact any callback credentials,- and fail loud on a row missing a required primary key.+ and fail loud on a row missing a required primary key. Endpoints with a row expander return the+ several rows their single response body carries."""+ expand = _ROW_EXPANDERS.get(config.name)- def _map(row: dict[str, Any]) -> 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.- if _PARENT_ID_KEY in row:- row[_PARENT_ID_FIELD] = row.pop(_PARENT_ID_KEY)- # 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 _map(row: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:+ if expand is None:+ return _normalize_row(config, row)+ return [_normalize_row(config, expanded) for expanded in expand(row)]return _mapdef _incremental_config(- should_use_incremental_field: bool, db_incremental_field_last_value: Any+ config: DeepgramEndpointConfig, should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> IncrementalConfig | None:- """Server-side `start` filter for the requests log, only when we have a cursor to filter on.+ """Server-side `start` filter for an incremental endpoint, only when we have a cursor to filter on.- Mirrors the old behaviour: no filter on a first (full) sync, and the persisted watermark is- formatted (and future-clamped) the way Deepgram's `start` expects.+ No filter on a first (full) sync. The persisted watermark is formatted (and future-clamped) the+ way the endpoint's `start` expects: whole seconds for the requests log, whole days for the usage+ and billing aggregates."""if not should_use_incremental_field or db_incremental_field_last_value is None:return None+ cursor = config.incremental_fields[0]return {"start_param": "start",- "cursor_path": "created",- "convert": _format_start_value,+ "cursor_path": cursor["field"],+ "convert": _format_start_date if cursor["field_type"] == IncrementalFieldType.Date else _format_start_value,}@@ -248,7 +356,7 @@ def deepgram_source() -> SourceResponse:config = DEEPGRAM_ENDPOINTS[endpoint]incremental = (- _incremental_config(should_use_incremental_field, db_incremental_field_last_value)+ _incremental_config(config, should_use_incremental_field, db_incremental_field_last_value)if config.supports_incrementalelse None)@@ -291,11 +399,12 @@ def deepgram_source(name=endpoint,items=lambda: resource,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".+ # Deepgram documents no default order for any of the incremental endpoints, and it can't be+ # curl-verified without a live token, so we use "desc": the pipeline finalises the incremental+ # watermark 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,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.pyindex 388b3e222896..20ca984e1ce8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/settings.py@@ -1,17 +1,21 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@frozenclass 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": [...]}).+ # envelope, e.g. {"projects": [...]}, {"requests": [...]}). "$" selects the whole body, for the+ # endpoints whose payload is several parallel collections rather than one list; a row expander in+ # deepgram.py then splits it into rows.data_key: strprimary_keys: list[str]# Stable creation-time field used for datetime partitioning. Never a mutable field.@@ -26,6 +30,10 @@ class DeepgramEndpointConfig:# 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+ # Dimension columns of an aggregate endpoint. When set, the row gets a derived `grouping_key`+ # joining their values, so the primary key identifies the slice a row covers however Deepgram+ # groups the results. The dimensions themselves are null under some groupings and cannot key.+ grouping_dimensions: list[str] = field(default_factory=list)should_sync_default: bool = True@@ -86,6 +94,72 @@ DEEPGRAM_ENDPOINTS: dict[str, DeepgramEndpointConfig] = {},],),+ # The project's model catalogue: every model the project can call, public and non-public, so the+ # model ids carried on request rows resolve to a name, version and language. The response is two+ # parallel arrays ("stt", "tts") rather than one list, so the whole body is selected and split+ # into rows. The account-wide /v1/models lists only the public subset of the same models.+ "models": DeepgramEndpointConfig(+ name="models",+ path="/models",+ data_key="$",+ primary_keys=["project_id", "uuid"],+ ),+ # Transcription, TTS and agent usage per project over a date range. `start`/`end` filter+ # server-side on whole days, so the sync is incremental on the group's start date; the boundary+ # day is re-read each run and the merge collapses it, which keeps an in-progress day current.+ "usage_breakdown": DeepgramEndpointConfig(+ name="usage_breakdown",+ path="/usage/breakdown",+ data_key="results",+ primary_keys=["project_id", "start", "end", "grouping_key"],+ flatten_key="grouping",+ grouping_dimensions=["accessor", "endpoint", "feature_set", "models", "method", "tags", "deployment"],+ supports_incremental=True,+ incremental_fields=[+ {+ "label": "start",+ "type": IncrementalFieldType.Date,+ "field": "start",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+ # Spend per project over the same date range, which is what turns a balance into an explanation+ # of where the credit went.+ "billing_breakdown": DeepgramEndpointConfig(+ name="billing_breakdown",+ path="/billing/breakdown",+ data_key="results",+ primary_keys=["project_id", "start", "end", "grouping_key"],+ flatten_key="grouping",+ grouping_dimensions=["accessor", "deployment", "line_item", "tags"],+ supports_incremental=True,+ incremental_fields=[+ {+ "label": "start",+ "type": IncrementalFieldType.Date,+ "field": "start",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+ # The models, tags, processing methods and features the project used in the period, which are+ # the dimensions a usage breakdown can be sliced by. The response is one object of parallel+ # lists, so it is emitted long: one row per value, labelled with the list it came from.+ "usage_fields": DeepgramEndpointConfig(+ name="usage_fields",+ path="/usage/fields",+ data_key="$",+ primary_keys=["project_id", "field", "value"],+ ),+ # The same idea for billing: the accessors, deployments, tags and line items the project was+ # billed on in the period.+ "billing_fields": DeepgramEndpointConfig(+ name="billing_fields",+ path="/billing/fields",+ data_key="$",+ primary_keys=["project_id", "field", "value"],+ ),}ENDPOINTS = tuple(DEEPGRAM_ENDPOINTS.keys())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.pyindex 7ac845ae2f94..f58f38c6d5f6 100644--- 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@@ -13,8 +13,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.deepgram ifrom products.warehouse_sources.backend.temporal.data_imports.sources.deepgram.deepgram import (DEEPGRAM_BASE_URL,DeepgramResumeConfig,+ _format_start_date,_format_start_value,- _make_child_map,+ _normalize_row,_redact_url_userinfo,deepgram_source,validate_credentials,@@ -93,9 +94,9 @@ class TestFormatStartValue:assert _format_start_value(datetime(2027, 1, 1, tzinfo=UTC)) == "2026-06-15T12:00:00+00:00"-class TestChildMap:+class TestNormalizeRow:def test_injects_project_id(self) -> None:- row = _make_child_map(DEEPGRAM_ENDPOINTS["members"])({PARENT_KEY: "proj-1", "member_id": "m1"})+ row = _normalize_row(DEEPGRAM_ENDPOINTS["members"], {PARENT_KEY: "proj-1", "member_id": "m1"})assert row["project_id"] == "proj-1"assert row["member_id"] == "m1"assert PARENT_KEY not in row@@ -103,8 +104,9 @@ class TestChildMap: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 = _make_child_map(DEEPGRAM_ENDPOINTS["keys"])(- {PARENT_KEY: "proj-1", "api_key": {"api_key_id": "k1", "comment": "ci"}, "member": {"email": "[email protected]"}}+ row = _normalize_row(+ DEEPGRAM_ENDPOINTS["keys"],+ {PARENT_KEY: "proj-1", "api_key": {"api_key_id": "k1", "comment": "ci"}, "member": {"email": "[email protected]"}},)assert row["api_key_id"] == "k1"assert row["comment"] == "ci"@@ -121,15 +123,15 @@ class TestChildMap:)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 = _make_child_map(DEEPGRAM_ENDPOINTS["requests"])(- {PARENT_KEY: "proj-1", "request_id": "r1", "callback": callback}+ row = _normalize_row(+ DEEPGRAM_ENDPOINTS["requests"], {PARENT_KEY: "proj-1", "request_id": "r1", "callback": callback})assert row["callback"] == expecteddef 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"):- _make_child_map(DEEPGRAM_ENDPOINTS["requests"])({PARENT_KEY: "proj-1", "created": "2026-01-01"})+ _normalize_row(DEEPGRAM_ENDPOINTS["requests"], {PARENT_KEY: "proj-1", "created": "2026-01-01"})class TestRedactUrlUserinfo:@@ -393,3 +395,193 @@ class TestValidateCredentials:with mock.patch(DEEPGRAM_SESSION_PATCH) as mock_session:mock_session.return_value.get.side_effect = Exception("boom")assert validate_credentials("token") is False+++class TestFormatStartDate:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("iso_string", "2026-03-04T02:58:14+00:00", "2026-03-04"),+ ]+ )+ def test_truncates_to_whole_days(self, _name: str, value: Any, expected: str) -> None:+ # The usage and billing endpoints reject anything but YYYY-MM-DD with a 400.+ assert _format_start_date(value) == expected++ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)+ def test_future_date_clamped_to_today(self) -> None:+ assert _format_start_date(datetime(2027, 1, 1, tzinfo=UTC)) == "2026-06-15"+++class TestModelsEndpoint:+ @parameterized.expand(+ [+ (+ "both_catalogues",+ {"stt": [{"uuid": "u1", "name": "nova-3"}], "tts": [{"uuid": "u2", "name": "zeus"}]},+ [("u1", "stt"), ("u2", "tts")],+ ),+ # A project with no text-to-speech access omits the key entirely rather than sending [].+ ("missing_catalogue", {"stt": [{"uuid": "u1"}]}, [("u1", "stt")]),+ ("empty_catalogues", {"stt": [], "tts": []}, []),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_splits_parallel_catalogues_into_rows(+ self, _name: str, body: dict[str, Any], expected: list[tuple[str, str]], MockSession+ ) -> None:+ session = MockSession.return_value+ # The body is two parallel arrays, not one list of rows, and only the array a model came from+ # records whether it is speech-to-text or text-to-speech.+ _wire(session, [_response({"projects": [{"project_id": "p1"}]}), _response(body)])++ rows = _rows(_source("models", _make_manager()))++ assert [(r["uuid"], r["model_type"]) for r in rows] == expected+ assert all(r["project_id"] == "p1" for r in rows)+++class TestBreakdownEndpoints:+ @parameterized.expand(+ [+ (+ "usage",+ "usage_breakdown",+ "/usage/breakdown",+ {"hours": 1619.7, "requests": 373381},+ {"start": "2025-01-16", "end": "2025-01-16", "endpoint": "listen", "models": ["nova-3"]},+ "|listen||nova-3|||",+ ),+ (+ "billing",+ "billing_breakdown",+ "/billing/breakdown",+ {"dollars": "0.25"},+ {"start": "2025-01-16", "end": "2025-01-16", "line_item": "streaming::nova-3"},+ "||streaming::nova-3|",+ ),+ # Every dimension is null when the response is grouped by period only. The derived key+ # stays non-null so the merge predicate is still exact.+ (+ "ungrouped",+ "billing_breakdown",+ "/billing/breakdown",+ {"dollars": "1.00"},+ {"start": "2025-01-16", "end": "2025-01-16"},+ "|||",+ ),+ ]+ )+ def test_flattens_grouping_and_derives_grouping_key(+ self,+ _name: str,+ endpoint: str,+ path: str,+ measures: dict[str, Any],+ grouping: dict[str, Any],+ expected_key: str,+ ) -> None:+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response({"projects": [{"project_id": "p1"}]}),+ _response({"results": [{**measures, "grouping": grouping}]}),+ ],+ )++ rows = _rows(_source(endpoint, _make_manager()))++ assert snapshots[-1][0] == f"{DEEPGRAM_BASE_URL}/projects/p1{path}"+ assert len(rows) == 1+ # The period bounds live under "grouping"; they have to reach the row root or the primary key+ # can't be built.+ assert rows[0]["start"] == "2025-01-16"+ assert rows[0]["project_id"] == "p1"+ assert rows[0]["grouping_key"] == expected_key+ assert "grouping" not in rows[0]+ for measure, value in measures.items():+ assert rows[0][measure] == value++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_start_is_a_whole_day(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [_response({"projects": [{"project_id": "p1"}]}), _response({"results": []})],+ )++ _rows(+ _source(+ "usage_breakdown",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )++ # A timestamp here is rejected with a 400 because these endpoints filter on whole days only.+ assert snapshots[-1][1]["start"] == "2026-03-04"+++class TestFieldsEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_usage_fields_emits_one_row_per_value(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"projects": [{"project_id": "p1"}]}),+ _response(+ {+ "tags": ["tag=dev"],+ "models": [{"name": "2-medical-nova", "language": "en-MY", "version": "1", "model_id": "m1"}],+ "processing_methods": ["sync"],+ "features": ["punctuate"],+ }+ ),+ ],+ )++ rows = _rows(_source("usage_fields", _make_manager()))++ assert [(r["field"], r["value"]) for r in rows] == [+ ("models", "m1"),+ ("tags", "tag=dev"),+ ("processing_methods", "sync"),+ ("features", "punctuate"),+ ]+ assert rows[0]["name"] == "2-medical-nova"+ assert rows[0]["language"] == "en-MY"+ assert all(r["project_id"] == "p1" for r in rows)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_billing_fields_unpacks_the_line_item_map(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"projects": [{"project_id": "p1"}]}),+ _response(+ {+ "accessors": ["a1"],+ "deployments": ["hosted"],+ "tags": [],+ "line_items": {"streaming::nova-3": "Streaming Nova 3"},+ }+ ),+ ],+ )++ rows = _rows(_source("billing_fields", _make_manager()))++ assert [(r["field"], r["value"]) for r in rows] == [+ ("accessors", "a1"),+ ("deployments", "hosted"),+ ("line_items", "streaming::nova-3"),+ ]+ # Line items arrive as a name -> description map, so the description has to survive the unpack.+ assert rows[-1]["description"] == "Streaming Nova 3"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.pyindex eed0e41c1d8c..f6dba30e2c1c 100644--- 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@@ -38,12 +38,16 @@ class TestDeepgramSourceClass:@parameterized.expand([("requests_incremental", "requests", True),+ ("usage_breakdown_incremental", "usage_breakdown", True),+ ("billing_breakdown_incremental", "billing_breakdown", 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:+ def test_incremental_support_matches_the_server_side_date_filter(+ 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@@ -53,6 +57,9 @@ class TestDeepgramSourceClass: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"]+ # An aggregate row is identified by its period plus the slice it covers, never by the period+ # alone, because a grouped response returns several rows for the same period.+ assert schemas["usage_breakdown"] == ["project_id", "start", "end", "grouping_key"]def test_get_schemas_filters_by_name(self) -> None:schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["requests"])