: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(data-warehouse): implement groq import source (#69994)
Tom Owers4b2bd8414c76
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4bf9fcf3ab20..e062b60c79d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -201,6 +201,7 @@ the row lists both.| gorgias | HTTP | requests | ✅ || greenhouse | HTTP | requests | ✅ || gridly | HTTP | requests | ✅ |+| groq | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || harvey | HTTP | requests | ✅ |@@ -589,7 +590,6 @@ doesn't conflict with concurrent PRs.- google_workspace_admin_reports- grafana- greythr-- groq- growthbook- gumloop- gustodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex b2a2eee35602..b39e4dd7363e 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@@ -1639,7 +1639,7 @@ class GridlySourceConfig(config.Config):@config.configclass GroqSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/canonical_descriptions.pynew file mode 100644index 000000000000..e10f85da8c74--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/canonical_descriptions.py@@ -0,0 +1,56 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from Groq's OpenAI-compatible API docs (https://console.groq.com/docs/api-reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "batches": {+ "description": "Batch inference jobs submitted to the Batch API, with lifecycle status, request counts, and the file IDs holding the input, output, and errors.",+ "docs_url": "https://console.groq.com/docs/api-reference#batches",+ "columns": {+ "id": "Unique identifier for the batch job.",+ "object": "Object type, always `batch`.",+ "endpoint": "The API endpoint the batch runs against (e.g. /v1/chat/completions).",+ "input_file_id": "ID of the uploaded file containing the batch's input requests.",+ "completion_window": "Time frame within which the batch should be processed.",+ "status": "Current lifecycle status of the batch (e.g. validating, in_progress, completed, failed, expired).",+ "output_file_id": "ID of the file containing successful request outputs, once available.",+ "error_file_id": "ID of the file containing failed request errors, once available.",+ "created_at": "Unix timestamp (seconds) for when the batch was created.",+ "in_progress_at": "Unix timestamp (seconds) for when the batch started processing.",+ "expires_at": "Unix timestamp (seconds) for when the batch will expire.",+ "finalizing_at": "Unix timestamp (seconds) for when the batch started finalizing.",+ "completed_at": "Unix timestamp (seconds) for when the batch completed.",+ "failed_at": "Unix timestamp (seconds) for when the batch failed.",+ "expired_at": "Unix timestamp (seconds) for when the batch expired.",+ "cancelled_at": "Unix timestamp (seconds) for when the batch was cancelled.",+ "request_counts": "Object with total, completed, and failed request counts for the batch.",+ "metadata": "Set of key-value pairs attached to the batch at creation.",+ },+ },+ "files": {+ "description": "Metadata for files uploaded to Groq (typically batch inputs and outputs).",+ "docs_url": "https://console.groq.com/docs/api-reference#files",+ "columns": {+ "id": "Unique identifier for the file.",+ "object": "Object type, always `file`.",+ "bytes": "Size of the file in bytes.",+ "created_at": "Unix timestamp (seconds) for when the file was created.",+ "filename": "Name of the uploaded file.",+ "purpose": "Intended purpose of the file (e.g. batch, batch_output).",+ },+ },+ "models": {+ "description": "Catalog of models available to your organization through the Groq API.",+ "docs_url": "https://console.groq.com/docs/api-reference#models",+ "columns": {+ "id": "Model identifier used in API requests.",+ "object": "Object type, always `model`.",+ "created": "Unix timestamp (seconds) for when the model was created.",+ "owned_by": "Organization that owns the model.",+ "active": "Whether the model is currently active.",+ "context_window": "Maximum number of tokens the model can process in a single request.",+ "max_completion_tokens": "Maximum number of tokens the model can generate in a completion.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/groq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/groq.pynew file mode 100644index 000000000000..339135ee051d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/groq.py@@ -0,0 +1,160 @@+from collections.abc import Iterator+from typing import Any++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.groq.settings import (+ GROQ_ENDPOINTS,+ GroqEndpointConfig,+)++GROQ_BASE_URL = "https://api.groq.com/openai/v1"++# Bounds cursor pagination on `batches` so a malformed `next_cursor` (or an API that echoes the same+# cursor) can't loop forever. A structured warning is logged if the cap is ever reached. Per-org+# batch-job history is tiny, so this ceiling is far above any realistic page count.+MAX_PAGES = 1000+++class GroqRetryableError(Exception):+ pass+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type(+ (+ GroqRetryableError,+ 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,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response = session.get(url, headers=headers, params=params, timeout=60)++ # Groq applies org-level rate limits and returns 429 with a Retry-After header; tenacity's+ # backoff covers the wait. 5xx are transient too.+ if response.status_code == 429 or response.status_code >= 500:+ raise GroqRetryableError(f"Groq API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Groq API error: status={response.status_code}, body={response.text}, url={url}")+ # The API key rides in the Authorization header, not the URL, so raise_for_status()'s message+ # (which includes the URL) is safe to surface.+ response.raise_for_status()++ body = response.json()+ if not isinstance(body, dict):+ raise GroqRetryableError(f"Groq API returned an unexpected non-object response for url={url}")+ return body+++def _next_cursor(body: dict[str, Any]) -> str | None:+ """Extract the next-page cursor from a Groq list response.++ Groq's batches endpoint documents cursor pagination via a `paging` object carrying `next_cursor`,+ passed back as the `cursor` query param. This could not be verified against the live API (no+ credentials were available), so absence of a `paging` object is treated as "single page" — the+ common case for the tiny per-org datasets these endpoints return.+ """+ paging = body.get("paging")+ if isinstance(paging, dict):+ cursor = paging.get("next_cursor")+ if cursor:+ return str(cursor)+ return None+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = GROQ_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across pages so urllib3 keeps the connection alive. The API key rides in the+ # Authorization header, so it's redacted from logged URLs and captured samples, and redirects are+ # disabled so the bearer token is never replayed to another host.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ url = f"{GROQ_BASE_URL}{config.path}"++ cursor: str | None = None+ for page in range(MAX_PAGES):+ params = {"cursor": cursor} if cursor else None+ body = _fetch_page(session, url, headers, logger, params=params)++ # All three list endpoints wrap results as {"object": "list", "data": [...]}.+ items = body.get("data", [])+ if not isinstance(items, list):+ raise GroqRetryableError(f"Groq API returned an unexpected non-list data field for url={url}")+ if items:+ yield items++ if not config.paginated:+ return++ cursor = _next_cursor(body)+ if not cursor:+ return++ if page == MAX_PAGES - 1:+ logger.warning(+ f"Groq: hit MAX_PAGES={MAX_PAGES} paginating {endpoint}; stopping. Some rows may be missing."+ )+++def groq_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config: GroqEndpointConfig = GROQ_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],+ )+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Confirm the API key is usable by listing models (cheap, always available with a valid key).++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` when the request never completed.+ """+ if not api_key.strip():+ return False, None++ try:+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ response = session.get(f"{GROQ_BASE_URL}/models", headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False, None++ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/settings.pynew file mode 100644index 000000000000..49b1fbe9db4e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/settings.py@@ -0,0 +1,57 @@+import dataclasses++from products.warehouse_sources.backend.types import IncrementalField++# Groq exposes an OpenAI-compatible REST API under a single global base URL. The queryable+# (list) endpoints are job/asset bookkeeping: batch jobs, uploaded files, and the model catalog.+# None of them offer a server-side timestamp filter (no `created_after` / `since`), so every table+# is full refresh only. Volumes are tiny (per-org job records), and batch artifacts expire upstream+# after ~30 days regardless, so a full refresh each run is cheap and correct.+++class GroqEndpointConfig:+ name: str+ path: str+ # Unique across the whole table. Every Groq object carries a globally-unique `id`.+ primary_keys: list[str]+ # A stable creation timestamp (unix epoch seconds) used for datetime partitioning. Never a+ # mutable field. All three endpoints expose one, though the column name differs.+ partition_key: str+ # Whether this endpoint paginates via a body cursor. Only `batches` does; files and models are+ # returned as a single flat `data` array with no documented pagination.+ paginated: bool = False+ description: str | None = None+ should_sync_default: bool = True+++GROQ_ENDPOINTS: dict[str, GroqEndpointConfig] = {+ "batches": GroqEndpointConfig(+ name="batches",+ path="/batches",+ primary_keys=["id"],+ partition_key="created_at",+ paginated=True,+ description="Batch inference jobs with status, request counts, input/output/error file IDs, and timestamps. Full refresh (batch inputs/outputs expire upstream after ~30 days).",+ ),+ "files": GroqEndpointConfig(+ name="files",+ path="/files",+ primary_keys=["id"],+ partition_key="created_at",+ description="Uploaded file metadata (filename, purpose, byte size, creation time). Full refresh.",+ ),+ "models": GroqEndpointConfig(+ name="models",+ path="/models",+ primary_keys=["id"],+ partition_key="created",+ description="Catalog of models available to your organization, including context window and ownership. Full refresh.",+ ),+}++ENDPOINTS = tuple(GROQ_ENDPOINTS.keys())++# Groq exposes no server-side timestamp filter on any list endpoint, so there is no reliable+# incremental cursor. Every table ships full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in GROQ_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/source.pyindex 78b729c80b5e..e54f1579d833 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/source.py@@ -1,19 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+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, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GroqSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.groq.groq import (+ groq_source,+ validate_credentials as validate_groq_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.groq.settings import GROQ_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass GroqSource(SimpleSource[GroqSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GROQ@@ -24,8 +42,88 @@ class GroqSource(SimpleSource[GroqSourceConfig]):name=SchemaExternalDataSourceType.GROQ,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Groq",- iconPath="/static/services/groq.png",+ releaseStatus=ReleaseStatus.ALPHA,keywords=["llm", "ai", "inference", "batch"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="""Enter your Groq API key to pull your Groq batch jobs, files, and model catalog into the PostHog Data warehouse.++Create an API key in the [Groq console](https://console.groq.com/keys). Groq exposes no usage or spend API, so this source covers batch-job and file bookkeeping plus the model catalog.""",+ iconPath="/static/services/groq.png",+ docsUrl="https://posthog.com/docs/cdp/sources/groq",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="gsk_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.groq.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the+ # stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.groq.com": "Your Groq API key is invalid or has been revoked. Create a new key in the Groq console, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.groq.com": "Your Groq API key is missing the permissions needed to sync this data. Check the key in the Groq console, then reconnect.",+ }++ def get_schemas(+ self,+ config: GroqSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Groq exposes no server-side timestamp filter on any list endpoint, so every table is full+ # refresh only.+ schemas = [+ SourceSchema(+ name=endpoint.name,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=endpoint.primary_keys,+ should_sync_default=endpoint.should_sync_default,+ description=endpoint.description,+ )+ for endpoint in GROQ_ENDPOINTS.values()+ ]++ 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: GroqSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_groq_credentials(config.api_key)+ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Groq API key"+ if status_code == 403:+ return False, "Your Groq API key is missing the permissions needed to sync this data"+ return False, "Could not connect to Groq with the provided API key"++ def source_for_pipeline(self, config: GroqSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return groq_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq.pynew file mode 100644index 000000000000..669cc5d6e771--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq.py@@ -0,0 +1,182 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.groq.groq import (+ GROQ_BASE_URL,+ GroqRetryableError,+ _fetch_page,+ _get_headers,+ _next_cursor,+ get_rows,+ groq_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.groq.groq"+++def _response(*, body: Any = None, status: int = 200, ok: bool = True) -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ response.text = "" if body is None else str(body)+ response.json.return_value = body if body is not None else {}+ if not ok:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status} Client Error: Unauthorized for url: {GROQ_BASE_URL}/models", response=response+ )+ return response+++def _session_returning(responses: list[MagicMock]) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = responses+ return session+++def _collect_rows(batches: Any) -> list[dict]:+ rows: list[dict] = []+ for batch in batches:+ rows.extend(batch)+ return rows+++class TestGroq:+ def test_get_headers_uses_bearer_auth(self) -> None:+ headers = _get_headers("gsk_secret")+ assert headers["Authorization"] == "Bearer gsk_secret"+ assert headers["Accept"] == "application/json"++ @parameterized.expand(+ [+ ("cursor_present", {"paging": {"next_cursor": "abc"}}, "abc"),+ ("no_paging", {"data": []}, None),+ ("empty_cursor", {"paging": {"next_cursor": ""}}, None),+ ("null_cursor", {"paging": {"next_cursor": None}}, None),+ ("paging_not_dict", {"paging": "nope"}, None),+ ]+ )+ def test_next_cursor(self, _name: str, body: dict, expected: str | None) -> None:+ assert _next_cursor(body) == expected++ def test_fetch_page_returns_body_on_success(self) -> None:+ session = _session_returning([_response(body={"object": "list", "data": [{"id": "batch_1"}]})])+ body = _fetch_page(session, f"{GROQ_BASE_URL}/batches", _get_headers("k"), MagicMock())+ assert body == {"object": "list", "data": [{"id": "batch_1"}]}++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ def test_fetch_page_client_error_raises(self, _name: str, status: int) -> None:+ session = _session_returning([_response(status=status, ok=False)])+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, f"{GROQ_BASE_URL}/models", _get_headers("k"), MagicMock())++ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_fetch_page_retryable_status_retries_then_raises(self, _name: str, status: int) -> None:+ session = _session_returning([_response(status=status, ok=False)] * 5)+ with patch("time.sleep"), pytest.raises(GroqRetryableError):+ _fetch_page(session, f"{GROQ_BASE_URL}/models", _get_headers("k"), MagicMock())+ assert session.get.call_count == 5++ def test_fetch_page_non_dict_body_is_retryable(self) -> None:+ session = _session_returning([_response(body=["unexpected"])] * 5)+ with patch("time.sleep"), pytest.raises(GroqRetryableError):+ _fetch_page(session, f"{GROQ_BASE_URL}/models", _get_headers("k"), MagicMock())++ @parameterized.expand([("files",), ("models",)])+ def test_get_rows_non_paginated_reads_single_page(self, endpoint: str) -> None:+ # files and models are flat `data` arrays; the transport must not attempt a second request+ # even if a stray cursor is present in the body.+ responses = [_response(body={"data": [{"id": "a"}, {"id": "b"}], "paging": {"next_cursor": "x"}})]+ session = _session_returning(responses)+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ rows = _collect_rows(get_rows("k", endpoint, MagicMock()))+ assert [r["id"] for r in rows] == ["a", "b"]+ assert session.get.call_count == 1++ def test_get_rows_batches_follows_cursor_across_pages(self) -> None:+ responses = [+ _response(body={"data": [{"id": "batch_1"}], "paging": {"next_cursor": "cur1"}}),+ _response(body={"data": [{"id": "batch_2"}], "paging": {"next_cursor": "cur2"}}),+ _response(body={"data": [{"id": "batch_3"}]}), # no cursor -> last page+ ]+ session = _session_returning(responses)+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ rows = _collect_rows(get_rows("k", "batches", MagicMock()))+ assert [r["id"] for r in rows] == ["batch_1", "batch_2", "batch_3"]+ assert session.get.call_count == 3+ # The cursor from each page must be forwarded as the `cursor` param on the next request.+ cursors = [call.kwargs["params"] for call in session.get.call_args_list]+ assert cursors == [None, {"cursor": "cur1"}, {"cursor": "cur2"}]++ def test_get_rows_skips_empty_data_page(self) -> None:+ responses = [_response(body={"data": []})]+ session = _session_returning(responses)+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ rows = _collect_rows(get_rows("k", "models", MagicMock()))+ assert rows == []++ def test_get_rows_non_list_data_is_retryable(self) -> None:+ # A `data` field that isn't a list (error payload or changed API shape) must not be yielded as+ # a page of rows; it breaks the Iterator[list[dict]] contract.+ responses = [_response(body={"data": {"unexpected": "object"}})]+ session = _session_returning(responses)+ with patch(f"{MODULE}.make_tracked_session", return_value=session), pytest.raises(GroqRetryableError):+ _collect_rows(get_rows("k", "models", MagicMock()))++ @parameterized.expand(+ [+ ("batches", "created_at"),+ ("files", "created_at"),+ ("models", "created"),+ ]+ )+ def test_groq_source_maps_primary_keys_and_partitioning(self, endpoint: str, partition_key: str) -> None:+ response = groq_source("k", endpoint, MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]++ @parameterized.expand(+ [+ ("empty_key", " ", None, None, False, None),+ ("valid", "gsk_ok", 200, True, True, 200),+ ("invalid", "gsk_bad", 401, False, False, 401),+ ]+ )+ def test_validate_credentials(+ self,+ _name: str,+ api_key: str,+ status: int | None,+ ok: bool,+ expected_ok: bool,+ expected_status: int | None,+ ) -> None:+ session = MagicMock()+ if status is not None:+ session.get.return_value = _response(status=status, ok=ok, body={})+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ result_ok, result_status = validate_credentials(api_key)+ assert result_ok is expected_ok+ assert result_status == expected_status++ def test_validate_credentials_empty_key_skips_request(self) -> None:+ with patch(f"{MODULE}.make_tracked_session") as make_session:+ ok, status = validate_credentials(" ")+ assert ok is False+ assert status is None+ make_session.assert_not_called()++ def test_validate_credentials_swallows_transport_error(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ ok, status = validate_credentials("gsk_x")+ assert ok is False+ assert status is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq_source.pynew file mode 100644index 000000000000..c165519f9a5c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/groq/tests/test_groq_source.py@@ -0,0 +1,117 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.groq.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.groq.source import GroqSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.groq.source"+++def _make_config(api_key: str = "gsk_test") -> Any:+ config = MagicMock()+ config.api_key = api_key+ return config+++class TestGroqSource:+ def test_source_type(self) -> None:+ assert GroqSource().source_type == ExternalDataSourceType.GROQ++ def test_source_config_has_single_password_api_key_field(self) -> None:+ config = GroqSource().get_source_config+ assert [f.name for f in config.fields] == ["api_key"]+ (api_key_field,) = config.fields+ assert isinstance(api_key_field, SourceFieldInputConfig)+ # The API key is a secret credential, so it must render as a password input.+ assert api_key_field.type == "password"+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_source_config_stays_unreleased_alpha(self) -> None:+ config = GroqSource().get_source_config+ assert config.releaseStatus == "alpha"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/groq"++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render tables.+ assert GroqSource.lists_tables_without_credentials is True++ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:+ schemas = GroqSource().get_schemas(_make_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Groq exposes no server-side timestamp filter, so nothing supports incremental/append.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_exposes_primary_keys(self) -> None:+ schemas = {s.name: s for s in GroqSource().get_schemas(_make_config(), team_id=1)}+ assert schemas["batches"].detected_primary_keys == ["id"]+ assert schemas["files"].detected_primary_keys == ["id"]+ assert schemas["models"].detected_primary_keys == ["id"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = GroqSource().get_schemas(_make_config(), team_id=1, names=["batches", "models"])+ assert {s.name for s in schemas} == {"batches", "models"}++ @parameterized.expand(+ [+ ("valid", True, 200, True, None),+ ("invalid_key", False, 401, False, "Invalid Groq API key"),+ (+ "forbidden",+ False,+ 403,+ False,+ "Your Groq API key is missing the permissions needed to sync this data",+ ),+ ("other_failure", False, 500, False, "Could not connect to Groq with the provided API key"),+ ("no_connection", False, None, False, "Could not connect to Groq with the provided API key"),+ ]+ )+ def test_validate_credentials(+ self,+ _name: str,+ probe_ok: bool,+ probe_status: int | None,+ expected_ok: bool,+ expected_message: str | None,+ ) -> None:+ with patch(f"{MODULE}.validate_groq_credentials", return_value=(probe_ok, probe_status)):+ ok, message = GroqSource().validate_credentials(_make_config(), team_id=1)+ assert ok is expected_ok+ assert message == expected_message++ def test_source_for_pipeline_plumbs_key_and_endpoint(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "batches"+ inputs.logger = MagicMock()+ with patch(f"{MODULE}.groq_source") as source_fn:+ GroqSource().source_for_pipeline(_make_config("gsk_abc"), inputs)+ source_fn.assert_called_once()+ kwargs = source_fn.call_args.kwargs+ assert kwargs["api_key"] == "gsk_abc"+ assert kwargs["endpoint"] == "batches"++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.groq.com"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.groq.com"),+ ]+ )+ def test_non_retryable_errors_cover_auth_failures(self, _name: str, expected_key: str) -> None:+ errors = GroqSource().get_non_retryable_errors()+ assert expected_key in errors+ assert errors[expected_key]++ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:+ descriptions = GroqSource().get_canonical_descriptions()+ # Every documented entry must map to a real endpoint or the docs render orphaned tables.+ assert set(descriptions.keys()) <= set(ENDPOINTS)+ assert {"batches", "files", "models"} <= set(descriptions.keys())