:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add cortex initiatives, groups and team hierarchy tables (#104390)
Tom Owers0bea6e57d5f3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 471eae223703..dcfe08d12a5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2062,18 +2062,18 @@ Note: The source runs DataPrime direct-archive queries and its two tables map to## Cortex — gaps-Today (11): `custom_events`, `dependencies`, `deploys`, `entities`, `entity_types`, `relationship_types`, `relationships`, `scorecard_scores`, `scorecards`, `teams`, `users`+Today (14): `custom_events`, `dependencies`, `deploys`, `entities`, `entity_groups`, `entity_types`, `initiatives`, `relationship_types`, `relationships`, `scorecard_scores`, `scorecards`, `team_hierarchies`, `teams`, `users`Diffed against: <https://docs.cortex.io/llms.txt>- [x] `GET /api/v1/catalog/{tagOrId}/deploys` — deployment events per entity - deploy frequency and lead time, the headline Eng Intelligence metric (high)- [x] `GET /api/v1/users` — user lookup with profile and role assignments; resolves entity owners and team members (high)- [x] `GET /api/v1/catalog/{tagOrId}/custom-events` — arbitrary per-entity event stream (incidents, migrations, releases) pushed into Cortex (high)-- [ ] `GET /api/v1/initiatives` — scorecard-driven improvement campaigns and their progress - the main remediation-tracking object (high)+- [x] `GET /api/v1/initiatives` — scorecard-driven improvement campaigns and their progress - the main remediation-tracking object (high)- [x] `GET /api/v1/catalog/{callerTag}/dependencies` — service dependency graph edges; distinct from the entity-relationships already synced (high)-- [ ] `GET /api/v1/catalog/{tagOrId}/groups` — entity group membership junction - the tagging dimension most scorecard filters use (medium)-- [ ] `GET /api/v1/teams/relationships (team hierarchies)` — parent/child team edges; teams sync today with no hierarchy to roll up by (medium)-- [ ] `Custom metrics data points (Eng Intelligence)` — per-entity time series for custom KPIs alongside scorecard scores (medium)+- [x] `GET /api/v1/catalog/{tagOrId}/groups` — entity group membership junction - the tagging dimension most scorecard filters use (medium)+- [x] `GET /api/v1/teams/relationships (team hierarchies)` — parent/child team edges; teams sync today with no hierarchy to roll up by (medium)+- [ ] `Custom metrics data points (Eng Intelligence)` — per-entity time series for custom KPIs alongside scorecard scores (medium). Not buildable: the data points live at `/eng-intel/custom-metrics/{customMetricKey}/entity/{tagOrId}`, and no endpoint enumerates a workspace's custom metric keys — they are created in the UI — so there is no parent to fan out from, and the key would have to be user-supplied per workspace.- [ ] `GET /api/v1/catalog/{tagOrId}/packages` — package and library inventory per entity, for dependency and vulnerability rollups (medium)- [ ] `Audit logs (retrieve audit logs)` — who changed catalog, scorecards and settings over time (medium)- [ ] `GET /api/v1/catalog/{tagOrId}/custom-data` — per-entity custom key/value data - user-defined dimensions for slicing entities (medium)diff --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.pyindex 3da2dc16ecbb..7d0875137594 100644--- 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.py@@ -61,6 +61,25 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"ruleExemptions": "Rule exemptions requested or granted for this entity on this scorecard.",},},+ "initiatives": {+ "description": "A Cortex Initiative: a time-boxed campaign to bring entities up to part of a scorecard, with the rules or ladder levels it emphasizes.",+ "docs_url": "https://docs.cortex.io/api/readme/initiatives",+ "columns": {+ "cid": "18-character unique identifier for the Initiative.",+ "name": "Name of the Initiative.",+ "description": "Optional description of the Initiative.",+ "scorecardTag": "Tag of the scorecard the Initiative drives entities against.",+ "scorecardName": "Display name of that scorecard.",+ "targetDate": "Date the Initiative is meant to be completed by.",+ "isDraft": "Whether the Initiative is still a draft and not yet notifying anyone.",+ "emphasizedRules": "Scorecard rules the Initiative asks entities to pass.",+ "emphasizedLevels": "Scorecard ladder levels the Initiative asks entities to reach.",+ "filter": "Entity types, groups, and CQL query limiting which entities are in scope.",+ "notificationSchedule": "Reminder cadence and reply-to addresses for the Initiative.",+ "dateCreated": "Timestamp the Initiative was created.",+ "dateUpdated": "Timestamp the Initiative was last updated.",+ },+ },"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",@@ -89,6 +108,15 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"idpGroup": "Backing identity-provider group and its members, present for IDP-backed teams.",},},+ "team_hierarchies": {+ "description": "A parent/child edge between two teams, one row per edge in the team hierarchy.",+ "docs_url": "https://docs.cortex.io/api/readme/team-hierarchies",+ "columns": {+ "parentTeamTag": "Tag of the parent team in the edge.",+ "childTeamTag": "Tag of the child team in the edge.",+ "provider": "Identity provider that supplied the edge, when it was imported rather than set in Cortex.",+ },+ },"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",@@ -181,4 +209,13 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"providerType": "Provider that supplied the relationship, when it was created via an integration.",},},+ "entity_groups": {+ "description": "One entity's membership of one group, the tagging dimension most scorecard and Initiative filters are written against.",+ "docs_url": "https://docs.cortex.io/api/readme/groups",+ "columns": {+ "entity_id": "CID of the entity that belongs to the group.",+ "entity_tag": "Tag of the entity that belongs to the group.",+ "tag": "Tag of the group the entity belongs to.",+ },+ },}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.pyindex 82616e554704..36c2822c06c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/cortex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/cortex.py@@ -149,9 +149,11 @@ _FANOUT_FLATTENERS = {def get_resource(config: CortexEndpointConfig) -> EndpointResource:+ params: dict[str, Any] = {"pageSize": config.page_size} if config.paginated else {}+ params.update(config.extra_params)endpoint_config: Endpoint = {"path": config.path,- "params": {"pageSize": config.page_size} if config.paginated else {},+ "params": params,"data_selector": config.data_selector,"paginator": _list_paginator(config),}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.pyindex 323fc9ac3815..29d101bd6ef2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cortex/settings.py@@ -31,6 +31,9 @@ class CortexEndpointConfig:# 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+ # Extra query params for a top-level list request. A fan-out child takes its own params+ # from `DependentEndpointConfig.child_params` instead.+ extra_params: dict[str, str] = field(default_factory=dict)# Only the per-entity custom event stream documents a server-side time filter (`startTime`);# every other Cortex list endpoint is full-refresh only.incremental_fields: list[IncrementalField] = field(default_factory=list)@@ -75,6 +78,17 @@ CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {total_path="totalPages",partition_key="dateCreated",),+ # Scorecard-driven remediation campaigns. Drafts and expired Initiatives are both left out+ # by default, which would drop rows the table is expected to carry.+ "initiatives": CortexEndpointConfig(+ name="initiatives",+ path="/initiatives",+ data_selector="initiatives",+ primary_key=["cid"],+ total_path="totalPages",+ partition_key="dateCreated",+ extra_params={"includeDrafts": "true", "includeExpired": "true"},+ ),"entity_types": CortexEndpointConfig(name="entity_types",path="/catalog/definitions",@@ -89,6 +103,15 @@ CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {primary_key=["id"],paginated=False,),+ # Parent/child team edges. Like `teams`, the endpoint returns its whole collection in one+ # response with no page/pageSize params documented.+ "team_hierarchies": CortexEndpointConfig(+ name="team_hierarchies",+ path="/teams/relationships",+ data_selector="edges",+ primary_key=["parentTeamTag", "childTeamTag"],+ paginated=False,+ ),"relationship_types": CortexEndpointConfig(name="relationship_types",path="/relationship-types",@@ -188,6 +211,16 @@ CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {child_params={"includeOutgoing": "true", "includeIncoming": "false"},),),+ # Fans out over every entity and pulls the groups it belongs to. A row carries only the+ # group's own `tag`, so the entity has to come from the fan-out to key the membership.+ "entity_groups": CortexEndpointConfig(+ name="entity_groups",+ path="/catalog/{tagOrId}/groups",+ data_selector="groups",+ primary_key=["entity_id", "tag"],+ total_path="totalPages",+ fanout=_entity_fanout("tagOrId", {"tag": "entity_tag", "id": "entity_id"}),+ ),}ENDPOINTS = tuple(CORTEX_ENDPOINTS)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 b599a6dfdaae..195fb24dba63 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@@ -92,9 +92,9 @@ class CortexSource(SimpleSource[CortexSourceConfig]):name=ExternalDataSourceType.CORTEX,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cortex",- caption="""Enter your Cortex API key to sync your service catalog, scorecards, teams, users, deploys, dependencies, and entity relationships into the PostHog Data warehouse.+ caption="""Enter your Cortex API key to sync your service catalog, scorecards, initiatives, teams, users, deploys, dependencies, 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. Syncing the users table also needs the `View Roles` permission, which the built-in viewer, user, and manager key roles do not include.""",+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. The entity groups and team hierarchies tables need the `Edit entities` permission. Syncing the users table also needs the `View Roles` permission, which the built-in viewer, user, and manager key roles do not include. Syncing the initiatives table needs `View Initiatives`.""",docsUrl="https://posthog.com/docs/cdp/sources/cortex",iconPath="/static/services/cortex.png",keywords=["service catalog", "developer portal", "scorecards"],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.pyindex 4f5aebb3bff8..fc646c14d607 100644--- 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.py@@ -92,6 +92,25 @@ class TestCortexTransport:assert resource["endpoint"]["params"] == {}assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)+ @parameterized.expand(+ [+ # `includeDrafts` and `includeExpired` both default to false, so leaving them off+ # would silently drop Initiatives from the table.+ (+ "initiatives",+ {"pageSize": 250, "includeDrafts": "true", "includeExpired": "true"},+ PageNumberPaginator,+ ),+ ("team_hierarchies", {}, SinglePagePaginator),+ ]+ )+ def test_get_resource_sends_the_declared_list_params(+ self, name: str, expected_params: dict[str, Any], paginator_type: type+ ) -> None:+ resource = cast(dict[str, Any], get_resource(CORTEX_ENDPOINTS[name]))+ assert resource["endpoint"]["params"] == expected_params+ assert isinstance(resource["endpoint"]["paginator"], paginator_type)+@parameterized.expand(list(CORTEX_ENDPOINTS.keys()))def test_get_resource_matches_declared_primary_key_and_endpoint(self, name: str) -> None:config = CORTEX_ENDPOINTS[name]@@ -269,7 +288,7 @@ class TestCortexTransport:assert response.partition_keys == ["joinedAt"]assert response.sort_mode == "asc"- @parameterized.expand(["custom_events", "deploys", "dependencies"])+ @parameterized.expand(["custom_events", "deploys", "dependencies", "entity_groups"])@patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")def test_entity_fanouts_bind_the_encoded_tag(self, endpoint: str, mock_build_dependent_resource: Mock, *_: Any@@ -341,3 +360,17 @@ class TestCortexTransport:}assert rows[0]["method"] == "" and rows[0]["path"] == ""assert response.primary_keys == ["callerTag", "calleeTag", "method", "path"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")+ def test_entity_groups_keys_membership_on_a_column_the_fanout_injects(+ self, mock_build_dependent_resource: Mock+ ) -> None:+ # A group row carries only the group's own tag. If the parent rename stops producing+ # `entity_id`, the key column is never populated and every entity in a group merges+ # onto one row.+ mock_build_dependent_resource.return_value = _FakeDltResource("entity_groups", [{"tag": "tier-1"}])++ response = cortex_source(api_key="cx_key", endpoint="entity_groups", team_id=1, job_id="job-1")++ injected = set(mock_build_dependent_resource.call_args.kwargs["fanout"].parent_field_renames.values())+ assert set(response.primary_keys or []) - {"tag"} <= injected