: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): add Cortex source (#73188)
Tom Owers027c7b2c07f6
diff --git a/frontend/public/services/cortex.png b/frontend/public/services/cortex.pngindex 36a958a2de5f..efe890f2a542 100644Binary files a/frontend/public/services/cortex.png and b/frontend/public/services/cortex.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4024b9c140a7..71f0c6f14bfa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -160,6 +160,7 @@ the row lists both.| convex | HTTP | requests | ✅ || copper | HTTP | requests | ✅ || coralogix | HTTP | requests | ✅ |+| cortex | HTTP | requests + `rest_source.RESTClient` | ✅ || coupa | HTTP | requests | ✅ || courier | HTTP | requests + `rest_source.RESTClient` | ✅ || coveralls | HTTP | requests | ✅ |@@ -852,7 +853,6 @@ doesn't conflict with concurrent PRs.- conta_azul- contentsquare- copper-- cortex- cosmosdb- couchbase- crispdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/canonical_descriptions.pynew file mode 100644index 000000000000..f1563dfb27af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/canonical_descriptions.py@@ -0,0 +1,127 @@+"""Canonical, documentation-sourced descriptions for Cortex endpoints and columns.++Sourced from the official Cortex API reference (https://docs.cortex.io/api). Keyed by the+resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Cortex 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 = {+ "entities": {+ "description": "A catalog entity (service, resource, or domain) tracked in Cortex.",+ "docs_url": "https://docs.cortex.io/api/readme/catalog-entities",+ "columns": {+ "id": "18-character unique identifier (CID) for the entity.",+ "tag": "Human-readable unique identifier (x-cortex-tag) for the entity.",+ "name": "Display name of the entity.",+ "type": "Entity type: service, resource, or domain (or a custom entity type).",+ "description": "Optional markdown description of the entity.",+ "isArchived": "Whether the entity has been archived.",+ "lastUpdated": "Timestamp the entity was last updated in Cortex.",+ "groups": "List of x-cortex-groups values assigned to the entity.",+ "hierarchy": "Parent and child entities in the ownership hierarchy.",+ "links": "Links attached to the entity (documentation, dashboards, etc.).",+ "slackChannels": "Slack channels associated with the entity.",+ "owners": "Individuals and teams that own the entity.",+ "git": "Linked git repository details, when configured.",+ "metadata": "Custom metadata key/value pairs defined on the entity.",+ },+ },+ "scorecards": {+ "description": "A Cortex scorecard: a set of rules used to grade catalog entities against a standard.",+ "docs_url": "https://docs.cortex.io/api/readme/scorecards",+ "columns": {+ "tag": "Unique identifier (tag) for the scorecard.",+ "name": "Display name of the scorecard.",+ "description": "Description of what the scorecard measures.",+ "dateCreated": "Timestamp the scorecard was created.",+ "lastUpdated": "Timestamp the scorecard was last updated.",+ "isDraft": "Whether the scorecard is still a draft (not yet evaluating entities).",+ "rules": "The rule expressions the scorecard evaluates.",+ "levels": "Ladder levels an entity can achieve based on its rule scores.",+ "notifications": "Notification settings for the scorecard.",+ "exemptions": "Rule exemption settings for the scorecard.",+ "evaluation": "Evaluation settings, such as the scoring window.",+ },+ },+ "scorecard_scores": {+ "description": "A single entity's score against a scorecard, one row per scorecard/entity pair.",+ "docs_url": "https://docs.cortex.io/api/readme/scorecards",+ "columns": {+ "scorecard_tag": "Tag of the scorecard this score belongs to.",+ "service": "The scored entity's identifying fields (tag, id, name, groups, owners).",+ "service_tag": "Tag of the scored entity.",+ "service_id": "CID of the scored entity.",+ "service_name": "Display name of the scored entity.",+ "score": "The score summary, rule-by-rule breakdown, and ladder level achieved.",+ "lastEvaluated": "Timestamp the score was last evaluated.",+ "ruleExemptions": "Rule exemptions requested or granted for this entity on this scorecard.",+ },+ },+ "entity_types": {+ "description": "A custom entity type (definition) available in the Cortex catalog, beyond the built-in service/domain/team types.",+ "docs_url": "https://docs.cortex.io/api/readme/entity-types",+ "columns": {+ "type": "Unique identifier for the entity type.",+ "name": "Display name of the entity type.",+ "description": "Description of the entity type.",+ "schema": "JSON schema describing the entity type's custom fields.",+ "source": "Whether the type is a built-in Cortex type or a custom one.",+ "iconTag": "Icon tag shown for entities of this type in the Cortex UI.",+ },+ },+ "teams": {+ "description": "A team in Cortex, either managed directly in Cortex or backed by an identity provider group.",+ "docs_url": "https://docs.cortex.io/api/readme/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "teamTag": "Human-readable unique identifier for the team.",+ "catalogEntityTag": "Tag of the catalog entity (of type team) associated with this team.",+ "type": "Whether the team is Cortex-managed (CORTEX) or identity-provider-backed (IDP).",+ "isArchived": "Whether the team has been archived.",+ "metadata": "Team name, description, and summary.",+ "links": "Links attached to the team.",+ "slackChannels": "Slack channels associated with the team.",+ "cortexTeam": "Member list, present for Cortex-managed teams.",+ "idpGroup": "Backing identity-provider group and its members, present for IDP-backed teams.",+ },+ },+ "relationship_types": {+ "description": "A type of relationship (e.g. 'depends-on') that can connect two catalog entities.",+ "docs_url": "https://docs.cortex.io/api/readme/entity-relationship-types",+ "columns": {+ "tag": "Unique identifier for the relationship type.",+ "name": "Display name of the relationship type.",+ "description": "Description of what the relationship type represents.",+ "allowCycles": "Whether cyclical relationships of this type are allowed.",+ "definitionLocation": "Whether the relationship can be defined from the source, destination, or both.",+ "isSingleSource": "Whether a destination entity can have only one source of this type.",+ "isSingleDestination": "Whether a source entity can have only one destination of this type.",+ "isCortexManaged": "Whether this is a built-in Cortex-managed relationship type.",+ "sourcesFilter": "Restrictions on which entity types/providers can be a source of this relationship.",+ "destinationsFilter": "Restrictions on which entity types/providers can be a destination of this relationship.",+ "sourceLabelSingular": "Singular display label for a source entity of this relationship.",+ "sourceLabelPlural": "Plural display label for source entities of this relationship.",+ "destinationLabelSingular": "Singular display label for a destination entity of this relationship.",+ "destinationLabelPlural": "Plural display label for destination entities of this relationship.",+ },+ },+ "relationships": {+ "description": "A single edge between two catalog entities for a given relationship type.",+ "docs_url": "https://docs.cortex.io/api/readme/entity-relationships",+ "columns": {+ "relationship_type_tag": "Tag of the relationship type this edge belongs to.",+ "relationshipTypeTag": "Tag of the relationship type this edge belongs to, as echoed by the API.",+ "sourceEntity": "Identifying fields of the source entity in the relationship.",+ "source_entity_tag": "Tag of the source entity in the relationship.",+ "source_entity_id": "CID of the source entity in the relationship.",+ "destinationEntity": "Identifying fields of the destination entity in the relationship.",+ "destination_entity_tag": "Tag of the destination entity in the relationship.",+ "destination_entity_id": "CID of the destination entity in the relationship.",+ "providerType": "Provider that supplied the relationship, when it was created via an integration.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/cortex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/cortex.pynew file mode 100644index 000000000000..146987232774--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/cortex.py@@ -0,0 +1,177 @@+from collections.abc import Iterable+from typing import Any, Optional, cast++from requests.exceptions import RequestException++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.settings import (+ CORTEX_BASE_URL,+ CORTEX_ENDPOINTS,+ CortexEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": CORTEX_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ }+++def _list_paginator(config: CortexEndpointConfig) -> BasePaginator:+ if not config.paginated:+ return SinglePagePaginator()+ return PageNumberPaginator(page_param="page", total_path=config.total_path)+++def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ """Probe List Entities with `pageSize=1` — the cheapest authenticated call.++ Accepts a 403 at source-create (a key may legitimately lack scope for some resources, which+ the user can still deselect); a 403 for a specific schema is surfaced as a permission error.+ """+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{CORTEX_BASE_URL}/catalog",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ params={"page": 0, "pageSize": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except RequestException as exc:+ return False, f"Could not reach the Cortex API: {exc}"++ if response.status_code == 401:+ return False, "Invalid Cortex API key."+ if response.status_code == 403:+ if schema_name is not None:+ return False, "Your Cortex API key is missing the scope required for this table."+ return True, None+ if response.status_code != 200:+ return False, f"Cortex API returned an unexpected status ({response.status_code})."++ return True, None+++def _flatten_scorecard_score(item: dict[str, Any]) -> dict[str, Any]:+ """Pull the nested `service` identifiers to the row root so they can back the primary key."""+ service = item.get("service") or {}+ item["service_tag"] = service.get("tag")+ item["service_id"] = service.get("id")+ item["service_name"] = service.get("name")+ return item+++def _flatten_relationship(item: dict[str, Any]) -> dict[str, Any]:+ """Pull the nested source/destination entity identifiers to the row root for the primary key."""+ source_entity = item.get("sourceEntity") or {}+ destination_entity = item.get("destinationEntity") or {}+ item["source_entity_tag"] = source_entity.get("tag")+ item["source_entity_id"] = source_entity.get("id")+ item["destination_entity_tag"] = destination_entity.get("tag")+ item["destination_entity_id"] = destination_entity.get("id")+ return item+++_FANOUT_FLATTENERS = {+ "scorecard_scores": _flatten_scorecard_score,+ "relationships": _flatten_relationship,+}+++def get_resource(config: CortexEndpointConfig) -> EndpointResource:+ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {"pageSize": config.page_size} if config.paginated else {},+ "data_selector": config.data_selector,+ "paginator": _list_paginator(config),+ }+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(config: CortexEndpointConfig, items_fn: Any) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key,+ # Full refresh only — Cortex's list endpoints expose no stable updated-since cursor.+ sort_mode="asc",+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def cortex_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:+ config = CORTEX_ENDPOINTS[endpoint]+ client_config = _client_config(api_key)++ if config.fanout is not None:+ parent_config = CORTEX_ENDPOINTS[config.fanout.parent_name]+ resource = cast(+ Any,+ build_dependent_resource(+ endpoint_configs=CORTEX_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ page_size_param="pageSize",+ parent_endpoint_extra={+ "paginator": _list_paginator(parent_config),+ "data_selector": parent_config.data_selector,+ },+ child_endpoint_extra={+ "paginator": _list_paginator(config),+ "data_selector": config.data_selector,+ },+ ),+ )+ flatten_fn = _FANOUT_FLATTENERS.get(config.name)+ if flatten_fn is not None:+ resource = resource.add_map(flatten_fn)+ dependent_resource = cast(Iterable[Any], resource)+ return _make_source_response(config, lambda: dependent_resource)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(config)],+ }+ resource_response = rest_api_resource(rest_config, team_id, job_id, None)+ return _make_source_response(config, lambda: resource_response)+++__all__ = ["cortex_source", "get_resource", "validate_credentials"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/settings.pynew file mode 100644index 000000000000..2c66beac1db4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/settings.py@@ -0,0 +1,120 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# Cortex is a single global SaaS deployment (no regional hosts, no per-tenant subdomain).+CORTEX_BASE_URL = "https://api.getcortexapp.com/api/v1"++# List endpoints default to 250 and cap at 1000 per the API docs.+DEFAULT_PAGE_SIZE = 250+++@dataclass+class CortexEndpointConfig:+ name: str+ path: str+ # jsonpath selector into the response body for the list of rows.+ data_selector: str+ primary_key: list[str]+ # Every top-level list endpoint uses 0-indexed page/pageSize pagination; `teams` returns its+ # full collection in one response with no page/pageSize params documented.+ paginated: bool = True+ # jsonpath to the response's `totalPages` field, used to terminate pagination without an+ # extra trailing empty-page request. Endpoints that don't expose it stop on a short page.+ total_path: str | None = None+ page_size: int = DEFAULT_PAGE_SIZE+ # Stable creation-time field to partition by. Left None for endpoints with no such field+ # (never a mutable field like lastUpdated/lastEvaluated).+ partition_key: str | None = None+ # Cortex's documented list endpoints expose no updated-since/created-since filter, so every+ # endpoint is full-refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ fanout: DependentEndpointConfig | None = None+++CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {+ "entities": CortexEndpointConfig(+ name="entities",+ path="/catalog",+ data_selector="entities",+ # `id` (the 18-char CID) is globally unique; `tag` is also unique but can be renamed.+ primary_key=["id"],+ total_path="totalPages",+ # No creation-time field is exposed on the list response (only the mutable `lastUpdated`).+ ),+ "scorecards": CortexEndpointConfig(+ name="scorecards",+ path="/scorecards",+ data_selector="scorecards",+ primary_key=["tag"],+ total_path="totalPages",+ partition_key="dateCreated",+ ),+ "entity_types": CortexEndpointConfig(+ name="entity_types",+ path="/catalog/definitions",+ data_selector="definitions",+ primary_key=["type"],+ total_path="totalPages",+ ),+ "teams": CortexEndpointConfig(+ name="teams",+ path="/teams",+ data_selector="teams",+ primary_key=["id"],+ paginated=False,+ ),+ "relationship_types": CortexEndpointConfig(+ name="relationship_types",+ path="/relationship-types",+ data_selector="relationshipTypes",+ primary_key=["tag"],+ total_path="totalPages",+ ),+ # Fans out over every scorecard and pulls its per-entity scores. `scorecardTag` is only+ # present on the response wrapper (not on each `serviceScores` item), so the parent tag is+ # injected via fan-out and flattened alongside the nested `service` object (see+ # `_flatten_scorecard_score` in cortex.py) to build the composite primary key.+ "scorecard_scores": CortexEndpointConfig(+ name="scorecard_scores",+ path="/scorecards/{tag}/scores",+ data_selector="serviceScores",+ primary_key=["scorecard_tag", "service_tag"],+ total_path="totalPages",+ fanout=DependentEndpointConfig(+ parent_name="scorecards",+ resolve_param="tag",+ resolve_field="tag",+ include_from_parent=["tag"],+ parent_field_renames={"tag": "scorecard_tag"},+ ),+ ),+ # Fans out over every relationship type and pulls its edges. Each row aggregates edges across+ # every type, so the parent's type tag (defensively re-derived via fan-out rather than trusting+ # the row's own echoed `relationshipTypeTag`) plus the flattened source/destination entity tags+ # (see `_flatten_relationship`) keep the key unique table-wide.+ "relationships": CortexEndpointConfig(+ name="relationships",+ path="/relationships/{relationshipTypeTag}",+ data_selector="relationships",+ primary_key=["relationship_type_tag", "source_entity_tag", "destination_entity_tag"],+ total_path="totalPages",+ fanout=DependentEndpointConfig(+ parent_name="relationship_types",+ resolve_param="relationshipTypeTag",+ resolve_field="tag",+ include_from_parent=["tag"],+ parent_field_renames={"tag": "relationship_type_tag"},+ ),+ ),+}++ENDPOINTS = tuple(CORTEX_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CORTEX_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/source.pyindex dadac88ddab7..15af43e20172 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/source.py@@ -1,30 +1,115 @@-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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex import (+ cortex_source,+ validate_credentials as validate_cortex_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cortex import CortexSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass CortexSource(SimpleSource[CortexSourceConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+ api_docs_url = "https://docs.cortex.io/api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CORTEX+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Cortex API key is invalid or has been revoked. Generate a new key in workspace Settings and reconnect.",+ "403 Client Error": "Your Cortex API key does not have the required read permissions. Check the key's permissions in workspace Settings and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CortexSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CortexSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_cortex_credentials(config.api_key, schema_name=schema_name)++ def source_for_pipeline(self, config: CortexSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return cortex_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CORTEX,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cortex",+ caption="""Enter your Cortex API key to sync your service catalog, scorecards, teams, and entity relationships into the PostHog Data warehouse.++Create an API key in your Cortex workspace under **Settings → API Keys**. The key needs read access to the catalog, scorecards, and teams you want to sync.""",+ docsUrl="https://posthog.com/docs/cdp/sources/cortex",iconPath="/static/services/cortex.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["service catalog", "developer portal", "scorecards"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex.pynew file mode 100644index 000000000000..a2401e825424--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex.py@@ -0,0 +1,223 @@+from typing import Any, cast++from unittest.mock import Mock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex import (+ _flatten_relationship,+ _flatten_scorecard_score,+ cortex_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.settings import CORTEX_ENDPOINTS+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper: Any) -> "_FakeDltResource":+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self) -> Any:+ return iter(self._rows)+++class TestCortexTransport:+ @parameterized.expand(+ [+ ("unauthorized", 401, None, False),+ ("forbidden_at_create", 403, None, True),+ ("forbidden_for_schema", 403, "entities", False),+ ("ok", 200, None, True),+ ("unexpected", 500, None, False),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, _name: str, status_code: int, schema_name: str | None, expected_ok: bool, mock_session: Mock+ ) -> None:+ response = Mock(status_code=status_code)+ mock_session.return_value.get.return_value = response++ is_valid, _message = validate_credentials(api_key="cx_key", schema_name=schema_name)++ assert is_valid is expected_ok++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.make_tracked_session")+ def test_validate_credentials_probes_catalog_with_bearer(self, mock_session: Mock) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_key="cx_key")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.getcortexapp.com/api/v1/catalog"+ assert call.kwargs["headers"]["Authorization"] == "Bearer cx_key"+ assert call.kwargs["params"] == {"page": 0, "pageSize": 1}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.make_tracked_session")+ def test_validate_credentials_handles_request_exception(self, mock_session: Mock) -> None:+ mock_session.return_value.get.side_effect = requests.exceptions.RequestException("boom")+ is_valid, message = validate_credentials(api_key="cx_key")+ assert is_valid is False+ assert message is not None and "boom" in message++ def test_get_resource_entities_page_number_paginated(self) -> None:+ resource = cast(dict[str, Any], get_resource(CORTEX_ENDPOINTS["entities"]))+ assert resource["name"] == "entities"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/catalog"+ assert resource["endpoint"]["data_selector"] == "entities"+ assert resource["endpoint"]["params"] == {"pageSize": 250}+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, PageNumberPaginator)+ assert paginator.total_path == "totalPages"++ def test_get_resource_teams_single_page(self) -> None:+ resource = cast(dict[str, Any], get_resource(CORTEX_ENDPOINTS["teams"]))+ assert resource["endpoint"]["data_selector"] == "teams"+ assert resource["endpoint"]["params"] == {}+ assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)++ @parameterized.expand(list(CORTEX_ENDPOINTS.keys()))+ def test_get_resource_matches_declared_primary_key_and_endpoint(self, name: str) -> None:+ config = CORTEX_ENDPOINTS[name]+ resource = cast(dict[str, Any], get_resource(config))+ assert resource["name"] == name+ assert resource["endpoint"]["path"] == config.path++ def test_flatten_scorecard_score_pulls_service_identifiers(self) -> None:+ item = {"service": {"tag": "svc-a", "id": "cid123", "name": "Service A"}, "score": {"summary": {"score": 90}}}+ flattened = _flatten_scorecard_score(item)+ assert flattened["service_tag"] == "svc-a"+ assert flattened["service_id"] == "cid123"+ assert flattened["service_name"] == "Service A"++ def test_flatten_scorecard_score_handles_missing_service(self) -> None:+ flattened = _flatten_scorecard_score({})+ assert flattened["service_tag"] is None+ assert flattened["service_id"] is None++ def test_flatten_relationship_pulls_source_and_destination_identifiers(self) -> None:+ item = {+ "relationshipTypeTag": "depends-on",+ "sourceEntity": {"tag": "service-a", "id": "cid1"},+ "destinationEntity": {"tag": "service-b", "id": "cid2"},+ }+ flattened = _flatten_relationship(item)+ assert flattened["source_entity_tag"] == "service-a"+ assert flattened["source_entity_id"] == "cid1"+ assert flattened["destination_entity_tag"] == "service-b"+ assert flattened["destination_entity_id"] == "cid2"++ def test_flatten_relationship_handles_missing_entities(self) -> None:+ flattened = _flatten_relationship({})+ assert flattened["source_entity_tag"] is None+ assert flattened["destination_entity_tag"] is None++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.rest_api_resource")+ def test_cortex_source_entities_top_level(self, mock_rest_api_resource: Mock) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = cortex_source(api_key="cx_key", endpoint="entities", team_id=1, job_id="job-1")++ assert response.name == "entities"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_keys is None++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.rest_api_resource")+ def test_cortex_source_scorecards_partitions_on_date_created(self, mock_rest_api_resource: Mock) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = cortex_source(api_key="cx_key", endpoint="scorecards", team_id=1, job_id="job-1")++ assert response.primary_keys == ["tag"]+ assert response.partition_keys == ["dateCreated"]+ assert response.partition_mode == "datetime"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")+ def test_cortex_source_scorecard_scores_fanout_flattens_and_injects_parent_tag(+ self, mock_build_dependent_resource: Mock+ ) -> None:+ # `build_dependent_resource` has already applied its own parent-field rename by the time+ # it returns, so the fake child row carries the renamed `scorecard_tag` (not the raw+ # `_scorecards_tag`); this test only exercises our own `_flatten_scorecard_score` add_map.+ mock_build_dependent_resource.return_value = _FakeDltResource(+ "scorecard_scores",+ [{"service": {"tag": "svc-a", "id": "cid1"}, "scorecard_tag": "scorecard-1"}],+ )++ response = cortex_source(api_key="cx_key", endpoint="scorecard_scores", team_id=1, job_id="job-1")+ rows = list(cast(Any, response.items()))++ assert rows == [+ {+ "service": {"tag": "svc-a", "id": "cid1"},+ "scorecard_tag": "scorecard-1",+ "service_tag": "svc-a",+ "service_id": "cid1",+ "service_name": None,+ }+ ]+ assert response.primary_keys == ["scorecard_tag", "service_tag"]++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["fanout"].parent_name == "scorecards"+ assert kwargs["fanout"].resolve_param == "tag"+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["child_endpoint_extra"]["data_selector"] == "serviceScores"+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], PageNumberPaginator)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")+ def test_cortex_source_relationships_fanout_flattens_entities(self, mock_build_dependent_resource: Mock) -> None:+ mock_build_dependent_resource.return_value = _FakeDltResource(+ "relationships",+ [+ {+ "relationshipTypeTag": "depends-on",+ "sourceEntity": {"tag": "service-a"},+ "destinationEntity": {"tag": "service-b"},+ }+ ],+ )++ response = cortex_source(api_key="cx_key", endpoint="relationships", team_id=1, job_id="job-1")+ rows = list(cast(Any, response.items()))++ assert rows[0]["source_entity_tag"] == "service-a"+ assert rows[0]["destination_entity_tag"] == "service-b"+ assert response.primary_keys == ["relationship_type_tag", "source_entity_tag", "destination_entity_tag"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_cortex_source_relationships_fanout_injects_parent_relationship_type_tag(+ self, mock_rest_api_resources: Mock+ ) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("relationship_types", [{"tag": "depends-on"}]),+ _FakeDltResource(+ "relationships",+ [+ {+ "sourceEntity": {"tag": "service-a"},+ "destinationEntity": {"tag": "service-b"},+ "_relationship_types_tag": "depends-on",+ }+ ],+ ),+ ]++ response = cortex_source(api_key="cx_key", endpoint="relationships", team_id=1, job_id="job-1")+ rows = list(cast(Any, response.items()))++ assert rows[0]["relationship_type_tag"] == "depends-on"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex_source.pynew file mode 100644index 000000000000..83940a83229f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/tests/test_cortex_source.py@@ -0,0 +1,112 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.source import CortexSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cortex import CortexSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCortexSource:+ def setup_method(self) -> None:+ self.source = CortexSource()+ self.team_id = 123+ self.config = CortexSourceConfig(api_key="cx_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CORTEX++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Cortex"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cortex"++ def test_source_is_released_not_hidden(self) -> None:+ # A finished source must be visible: `unreleasedSource` hides it from every user.+ assert not self.source.get_source_config.unreleasedSource++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ input_fields = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert input_fields == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_all_full_refresh(self) -> None:+ # Cortex exposes no server-side updated-since cursor, so no stream is incremental.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["entities"])+ assert [s.name for s in schemas] == ["entities"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — powers the public docs table list.+ assert self.source.lists_tables_without_credentials is True++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.getcortexapp.com/api/v1/catalog"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.getcortexapp.com/api/v1/catalog"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(+ key in "503 Server Error for url: https://api.getcortexapp.com/api/v1/catalog" for key in non_retryable+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cortex.source.validate_cortex_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="entities")++ assert result == (True, None)+ mock_validate.assert_called_once_with("cx_key", schema_name="entities")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.source.cortex_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_cortex_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "scorecard_scores"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_cortex_source.call_args.kwargs+ assert kwargs["api_key"] == "cx_key"+ assert kwargs["endpoint"] == "scorecard_scores"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cortex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cortex.pyindex fa102dcc676f..8cb6192f9273 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cortex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cortex.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CortexSourceConfig(config.Config):- pass+ api_key: str