: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 cohere import source (#69989)
Tom Owersb30f1e7e0174
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 582b299f9839..e1ab1b421ff0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -109,6 +109,7 @@ the row lists both.| coassemble | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || codefresh | HTTP | requests | ✅ |+| cohere | HTTP | requests | ✅ || coin_api | HTTP | requests | ✅ || coingecko | HTTP | requests | ✅ || coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -527,7 +528,6 @@ doesn't conflict with concurrent PRs.- coassemble- cockroachdb- cody-- cohere- constant_contact- copper- cosmosdbdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/canonical_descriptions.pynew file mode 100644index 000000000000..61c6fecde471--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/canonical_descriptions.py@@ -0,0 +1,86 @@+"""Canonical, documentation-sourced descriptions for Cohere endpoints and columns.++Sourced from the official Cohere API reference (https://docs.cohere.com/reference). Keyed by the+endpoint names in `settings.py` `COHERE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Cohere table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "datasets": {+ "description": "A dataset uploaded to Cohere for fine-tuning or embedding jobs.",+ "docs_url": "https://docs.cohere.com/reference/list-datasets",+ "columns": {+ "id": "Unique identifier for the dataset.",+ "name": "Human-readable name of the dataset.",+ "dataset_type": "The type of dataset (e.g. embed-input, chat-finetune-input).",+ "validation_status": "Whether the dataset passed validation (e.g. validated, failed).",+ "validation_error": "The validation error, if the dataset failed validation.",+ "created_at": "Time at which the dataset was created.",+ "updated_at": "Time at which the dataset was last updated.",+ "download_urls": "Signed URLs to download the dataset parts.",+ "schema": "The inferred schema of the dataset.",+ },+ },+ "connectors": {+ "description": "A connector that lets Cohere's chat models retrieve documents from an external data source.",+ "docs_url": "https://docs.cohere.com/reference/list-connectors",+ "columns": {+ "id": "Unique identifier for the connector.",+ "name": "Human-readable name of the connector.",+ "description": "A description of the connector.",+ "url": "The URL Cohere queries to retrieve documents.",+ "created_at": "Time at which the connector was created.",+ "updated_at": "Time at which the connector was last updated.",+ "organization_id": "The organization that owns the connector.",+ "active": "Whether the connector is active.",+ "auth_status": "The authentication status of the connector (e.g. valid, expired).",+ },+ },+ "models": {+ "description": "A model available to your account in the Cohere model catalog.",+ "docs_url": "https://docs.cohere.com/reference/list-models",+ "columns": {+ "name": "The model name, used as the identifier when calling the API.",+ "endpoints": "The API endpoints the model supports (e.g. generate, embed, chat, rerank).",+ "finetuned": "Whether the model is a fine-tuned model.",+ "context_length": "The maximum number of tokens the model accepts as input.",+ "tokenizer_url": "URL to the model's tokenizer configuration.",+ "default_endpoints": "The endpoints for which this model is the default.",+ },+ },+ "finetuned_models": {+ "description": "A fine-tuned model trained on your data.",+ "docs_url": "https://docs.cohere.com/reference/listfinetunedmodels",+ "columns": {+ "id": "Unique identifier for the fine-tuned model.",+ "name": "Human-readable name of the fine-tuned model.",+ "creator_id": "The user that created the fine-tuned model.",+ "organization_id": "The organization that owns the fine-tuned model.",+ "settings": "The fine-tuning configuration (base model, hyperparameters, dataset).",+ "status": "The lifecycle status of the fine-tuned model (e.g. STATUS_READY, STATUS_FAILED).",+ "created_at": "Time at which the fine-tuned model was created.",+ "updated_at": "Time at which the fine-tuned model was last updated.",+ "completed_at": "Time at which fine-tuning completed.",+ "last_used": "Time at which the fine-tuned model was last used.",+ },+ },+ "embed_jobs": {+ "description": "An asynchronous job that embeds a dataset into vectors.",+ "docs_url": "https://docs.cohere.com/reference/list-embed-jobs",+ "columns": {+ "job_id": "Unique identifier for the embed job.",+ "name": "Human-readable name of the embed job.",+ "status": "The status of the job (e.g. processing, complete, failed).",+ "created_at": "Time at which the embed job was created.",+ "input_dataset_id": "The dataset that was embedded.",+ "output_dataset_id": "The dataset holding the resulting embeddings.",+ "model": "The embedding model used for the job.",+ "truncate": "How inputs longer than the context length were truncated.",+ "meta": "Billed-unit metadata and API version info for the job.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.pynew file mode 100644index 000000000000..e9d8d43e6016--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/cohere.py@@ -0,0 +1,178 @@+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.cohere.settings import (+ COHERE_ENDPOINTS,+ CohereEndpointConfig,+ CoherePagination,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session++# Cohere serves a single global API host; there are no regional variants.+COHERE_BASE_URL = "https://api.cohere.com/v1"+++class CohereRetryableError(Exception):+ pass+++class CohereError(Exception):+ pass+++def _extract_items(data: dict[str, Any], config: CohereEndpointConfig, url: str) -> list[dict[str, Any]]:+ # A successful response that omits the envelope key is a shape mismatch, not empty data.+ # Every Cohere schema is full-refresh-only, so silently treating a missing key as an empty+ # page would clear the existing warehouse table; fail loudly instead of destroying data.+ if config.data_key not in data:+ raise CohereError(f"Cohere response missing expected '{config.data_key}' key: url={url}")+ return data[config.data_key]+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def validate_credentials(api_key: str) -> bool:+ # /models is the cheapest authenticated probe: a 200 confirms the key is genuine without+ # touching a user's data. An invalid key returns 401 ("invalid api token").+ url = f"{COHERE_BASE_URL}/models"+ try:+ # `redact_values` masks the API key in logged URLs and captured HTTP samples.+ response = make_tracked_session(redact_values=(api_key,)).get(+ url, headers=_get_headers(api_key), params={"page_size": 1}, timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ # ChunkedEncodingError is a mid-stream connection break; transient like ConnectionError/ReadTimeout.+ retry=retry_if_exception_type(+ (+ CohereRetryableError,+ 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],+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, headers=headers, params=params, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise CohereRetryableError(f"Cohere API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Cohere API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = COHERE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive.+ # `redact_values` masks the API key in logged URLs and captured HTTP samples.+ session = make_tracked_session(redact_values=(api_key,))+ url = f"{COHERE_BASE_URL}{config.path}"++ if config.pagination == CoherePagination.NONE:+ data = _fetch_page(session, url, headers, {}, logger)+ items = _extract_items(data, config, url)+ if items:+ yield items+ return++ if config.pagination == CoherePagination.OFFSET:+ yield from _paginate_offset(session, url, headers, config, logger)+ return++ yield from _paginate_page_token(session, url, headers, config, logger)+++def _paginate_offset(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ config: CohereEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ offset = 0+ while True:+ data = _fetch_page(session, url, headers, {"limit": config.page_size, "offset": offset}, logger)+ items = _extract_items(data, config, url)+ if not items:+ break+ yield items+ # A short page means the last page; stop rather than issue an extra empty request.+ if len(items) < config.page_size:+ break+ offset += len(items)+++def _paginate_page_token(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ config: CohereEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {"page_size": config.page_size}+ if page_token:+ params["page_token"] = page_token+ data = _fetch_page(session, url, headers, params, logger)+ items = _extract_items(data, config, url)+ if items:+ yield items+ page_token = data.get(config.next_token_key)+ if not page_token:+ break+++def cohere_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = COHERE_ENDPOINTS[endpoint]+ partitioned = config.partition_key is not None++ # Leave every partition field unset for endpoints without a creation timestamp (the model+ # catalog). Setting partition_count/size here would make the warehouse writer fall back to+ # primary_keys and md5-partition the table by `name`; None keeps it unpartitioned as intended.+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),+ primary_keys=config.primary_keys,+ partition_count=1 if partitioned else None,+ partition_size=1 if partitioned else None,+ partition_mode="datetime" if partitioned else None,+ partition_format="month" if partitioned else None,+ partition_keys=[config.partition_key] if config.partition_key is not None else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/settings.pynew file mode 100644index 000000000000..4a6931be3845--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/settings.py@@ -0,0 +1,73 @@+from dataclasses import dataclass, field+from enum import Enum+++class CoherePagination(Enum):+ # ?limit=&offset= — used by /datasets and /connectors. Terminate when a page returns+ # fewer rows than the page size.+ OFFSET = "offset"+ # ?page_size=&page_token= with a next_page_token in the body — used by /models and+ # /finetuning/finetuned-models. Terminate when the response omits the token.+ PAGE_TOKEN = "page_token"+ # Single unpaginated request returning every row — used by /embed-jobs.+ NONE = "none"+++@dataclass+class CohereEndpointConfig:+ name: str+ path: str+ # Envelope key holding the list of rows in the JSON response (e.g. {"datasets": [...]}).+ data_key: str+ pagination: CoherePagination+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable creation timestamp used for datetime partitioning. None for endpoints whose+ # objects expose no creation time (the model catalog), which skips partitioning.+ partition_key: str | None = "created_at"+ page_size: int = 100+ # Body key carrying the cursor for PAGE_TOKEN endpoints.+ next_token_key: str = "next_page_token"+++# The list endpoints a user connecting Cohere actually wants to warehouse: syncable asset and+# job-history entities. Cohere is mostly an inference API; these are the objects with durable+# rows worth pulling. Every endpoint is full refresh only — see CohereSource.get_schemas for why.+COHERE_ENDPOINTS: dict[str, CohereEndpointConfig] = {+ "datasets": CohereEndpointConfig(+ name="datasets",+ path="/datasets",+ data_key="datasets",+ pagination=CoherePagination.OFFSET,+ ),+ "connectors": CohereEndpointConfig(+ name="connectors",+ path="/connectors",+ data_key="connectors",+ pagination=CoherePagination.OFFSET,+ ),+ # The model catalog has no per-model creation timestamp, so it can't be partitioned by one.+ "models": CohereEndpointConfig(+ name="models",+ path="/models",+ data_key="models",+ pagination=CoherePagination.PAGE_TOKEN,+ primary_keys=["name"],+ partition_key=None,+ page_size=1000, # /models caps page_size at 1000+ ),+ "finetuned_models": CohereEndpointConfig(+ name="finetuned_models",+ path="/finetuning/finetuned-models",+ data_key="finetuned_models",+ pagination=CoherePagination.PAGE_TOKEN,+ ),+ "embed_jobs": CohereEndpointConfig(+ name="embed_jobs",+ path="/embed-jobs",+ data_key="embed_jobs",+ pagination=CoherePagination.NONE,+ primary_keys=["job_id"],+ ),+}++ENDPOINTS = tuple(COHERE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/source.pyindex 700cc8ba718f..20489bf32e39 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/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.cohere.cohere import (+ cohere_source,+ validate_credentials as validate_cohere_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cohere.settings import ENDPOINTSfrom 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 CohereSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass CohereSource(SimpleSource[CohereSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COHERE@@ -24,8 +42,82 @@ class CohereSource(SimpleSource[CohereSourceConfig]):name=SchemaExternalDataSourceType.COHERE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cohere",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Cohere API key to pull your Cohere assets and job history into the PostHog Data warehouse.++Create an API key in your [Cohere dashboard](https://dashboard.cohere.com/api-keys). Prefer a production key: trial keys are capped at 1,000 API calls per month, which a recurring sync can exhaust.+""",iconPath="/static/services/cohere.png",+ docsUrl="https://posthog.com/docs/cdp/sources/cohere",keywords=["llm", "ai", "embeddings", "fine-tuning"],- 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.cohere.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked key surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync. Match+ # the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.cohere.com": "Your Cohere API key is invalid or has been revoked. Create a new key in your Cohere dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.cohere.com": "Your Cohere API key is missing the permissions needed to sync this data. Check the key permissions in your Cohere dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: CohereSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Cohere exposes no reliable server-side timestamp range filter across these list endpoints+ # (only /datasets documents before/after created-at filters, and the entities are mutable+ # with tiny row counts), so every endpoint is full refresh only. Statuses and timestamps+ # mutate in place, so append-only would drop those updates.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: CohereSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_cohere_credentials(config.api_key):+ return True, None++ return False, "Invalid Cohere API key"++ def source_for_pipeline(self, config: CohereSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return cohere_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.pynew file mode 100644index 000000000000..f86717b8298b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere.py@@ -0,0 +1,189 @@+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.cohere import cohere+from products.warehouse_sources.backend.temporal.data_imports.sources.cohere.cohere import (+ CohereError,+ CohereRetryableError,+ _paginate_offset,+ _paginate_page_token,+ cohere_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cohere.settings import (+ COHERE_ENDPOINTS,+ CohereEndpointConfig,+ CoherePagination,+)+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(cohere, "make_tracked_session", return_value=session):+ assert validate_credentials("test-key") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(cohere, "make_tracked_session", return_value=session):+ assert validate_credentials("test-key") is False++ def test_session_redacts_api_key(self) -> None:+ # The bearer token must be masked in captured HTTP samples and logged URLs.+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(cohere, "make_tracked_session", return_value=session) as make_session:+ validate_credentials("secret-key")+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_status_raises_retryable_error(self, _name: str, status_code: int) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(cohere._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(CohereRetryableError):+ cohere._fetch_page(session, "https://api.cohere.com/v1/datasets", {}, {}, MagicMock())++ @parameterized.expand([("read_timeout", requests.ReadTimeout()), ("connection", requests.ConnectionError())])+ def test_transient_errors_are_retried_then_succeed(self, _name: str, transient: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"datasets": []}+ session = MagicMock()+ session.get.side_effect = [transient, good]+ with patch.object(cohere._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = cohere._fetch_page(session, "https://api.cohere.com/v1/datasets", {}, {}, MagicMock())+ assert result == {"datasets": []}++ def test_unauthorized_raises_for_status(self) -> None:+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized", response=requests.Response()+ )+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ cohere._fetch_page(session, "https://api.cohere.com/v1/datasets", {}, {}, MagicMock())+++class TestPaginateOffset:+ def test_stops_on_short_page(self) -> None:+ config = CohereEndpointConfig(+ name="datasets", path="/datasets", data_key="datasets", pagination=CoherePagination.OFFSET, page_size=2+ )+ requested_offsets: list[int] = []++ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict[str, Any], _logger: Any) -> dict:+ requested_offsets.append(params["offset"])+ rows = {0: [{"id": "a"}, {"id": "b"}], 2: [{"id": "c"}]}.get(params["offset"], [])+ return {"datasets": rows}++ with patch.object(cohere, "_fetch_page", side_effect=fake_fetch):+ pages = list(_paginate_offset(MagicMock(), "url", {}, config, MagicMock()))++ assert [r["id"] for page in pages for r in page] == ["a", "b", "c"]+ # A full page advances the offset; the short second page ends pagination without a third request.+ assert requested_offsets == [0, 2]++ def test_empty_first_page_yields_nothing(self) -> None:+ config = CohereEndpointConfig(+ name="datasets", path="/datasets", data_key="datasets", pagination=CoherePagination.OFFSET, page_size=2+ )+ with patch.object(cohere, "_fetch_page", return_value={"datasets": []}):+ assert list(_paginate_offset(MagicMock(), "url", {}, config, MagicMock())) == []+++class TestPaginatePageToken:+ def test_follows_next_page_token(self) -> None:+ config = COHERE_ENDPOINTS["finetuned_models"]+ requested_tokens: list[Any] = []++ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict[str, Any], _logger: Any) -> dict:+ token = params.get("page_token")+ requested_tokens.append(token)+ if token is None:+ return {"finetuned_models": [{"id": "a"}], "next_page_token": "t2"}+ return {"finetuned_models": [{"id": "b"}]}++ with patch.object(cohere, "_fetch_page", side_effect=fake_fetch):+ pages = list(_paginate_page_token(MagicMock(), "url", {}, config, MagicMock()))++ assert [r["id"] for page in pages for r in page] == ["a", "b"]+ # First request has no token; the second carries the token from the first response.+ assert requested_tokens == [None, "t2"]+++class TestGetRows:+ def test_unpaginated_endpoint_makes_single_request(self) -> None:+ calls: list[Any] = []++ def fake_fetch(_session: Any, url: str, _headers: Any, _params: Any, _logger: Any) -> dict:+ calls.append(url)+ return {"embed_jobs": [{"job_id": "j1"}, {"job_id": "j2"}]}++ with patch.object(cohere, "_fetch_page", side_effect=fake_fetch):+ with patch.object(cohere, "make_tracked_session", return_value=MagicMock()):+ rows = [r for page in get_rows("test-key", "embed_jobs", MagicMock()) for r in page]++ assert [r["job_id"] for r in rows] == ["j1", "j2"]+ assert len(calls) == 1++ def test_missing_envelope_key_raises_instead_of_emptying(self) -> None:+ # A successful response whose shape lacks the envelope key must fail loudly, not be+ # treated as an empty page that clears the full-refresh table.+ with patch.object(cohere, "_fetch_page", return_value={"unexpected": []}):+ with patch.object(cohere, "make_tracked_session", return_value=MagicMock()):+ with pytest.raises(CohereError):+ list(get_rows("test-key", "datasets", MagicMock()))++ def test_session_redacts_api_key(self) -> None:+ with patch.object(cohere, "_fetch_page", return_value={"embed_jobs": []}):+ with patch.object(cohere, "make_tracked_session", return_value=MagicMock()) as make_session:+ list(get_rows("secret-key", "embed_jobs", MagicMock()))+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestCohereSource:+ @parameterized.expand([(e,) for e in COHERE_ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ config = COHERE_ENDPOINTS[endpoint]+ response = cohere_source(api_key="test-key", endpoint=endpoint, logger=MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ assert response.partition_count == 1+ assert response.partition_size == 1+ else:+ # The model catalog has no creation timestamp, so it must stay fully unpartitioned.+ # partition_count/size are left None too: a stray count makes the writer fall back to+ # primary_keys and md5-partition by name.+ assert response.partition_mode is None+ assert response.partition_keys is None+ assert response.partition_count is None+ assert response.partition_size is None++ def test_models_primary_key_is_name_not_id(self) -> None:+ # Model catalog rows are keyed by name; there is no id field to dedupe on.+ assert cohere_source(api_key="test-key", endpoint="models", logger=MagicMock()).primary_keys == ["name"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere_source.pynew file mode 100644index 000000000000..f0ea0b7774a6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cohere/tests/test_cohere_source.py@@ -0,0 +1,94 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.cohere import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.cohere.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cohere.source import CohereSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CohereSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> CohereSourceConfig:+ return CohereSourceConfig(api_key="test-key")+++class TestCohereSourceClass:+ def setup_method(self) -> None:+ self.source = CohereSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.COHERE++ def test_source_config_identity(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Cohere"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cohere"++ def test_source_config_field_is_a_secret_api_key(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_key"}+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].secret is True+ assert fields["api_key"].required is True++ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_get_schemas_are_full_refresh_only(self, endpoint: str) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ assert endpoint in schemas+ # Cohere has no reliable server-side timestamp filter, so incremental/append must be off.+ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False+ assert schemas[endpoint].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["datasets"])+ assert [s.name for s in schemas] == ["datasets"]++ def test_lists_tables_without_credentials_for_public_docs(self) -> None:+ # get_schemas is a static catalog with no I/O, so the table list is safe to publish.+ assert self.source.lists_tables_without_credentials is True+ assert {t["name"] for t in self.source.get_documented_tables()} == set(ENDPOINTS)++ @parameterized.expand([("unauthorized", "401 Client Error"), ("forbidden", "403 Client Error")])+ def test_non_retryable_errors(self, _name: str, expected_key_prefix: str) -> None:+ errors = self.source.get_non_retryable_errors()+ assert any(key.startswith(expected_key_prefix) for key in errors)++ def test_validate_credentials_success(self) -> None:+ with patch.object(source_module, "validate_cohere_credentials", return_value=True):+ assert self.source.validate_credentials(_config(), self.team_id) == (True, None)++ def test_validate_credentials_failure(self) -> None:+ with patch.object(source_module, "validate_cohere_credentials", return_value=False):+ ok, error = self.source.validate_credentials(_config(), self.team_id)+ assert ok is False+ assert error is not None++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "datasets"+ with patch.object(source_module, "cohere_source") as mock_source:+ self.source.source_for_pipeline(_config(), inputs)+ mock_source.assert_called_once_with(+ api_key="test-key",+ endpoint="datasets",+ logger=inputs.logger,+ )++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ for table in descriptions.values():+ assert table["description"]+ assert table["columns"]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.pyindex 24ecf376e27c..013f4c63db5f 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@@ -842,7 +842,7 @@ class CodySourceConfig(config.Config):@config.configclass CohereSourceConfig(config.Config):- pass+ api_key: str@config.config