Skip to content

: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.

feat(cortex): sync deploys, custom events, dependencies and users (#103724)

Tom Owersad51874bbc81
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.md
index 12726af2e301..8ca775ee2ef2 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,15 +2062,15 @@ Note: The source runs DataPrime direct-archive queries and its two tables map to
## Cortex — gaps
-Today (7): `entities`, `entity_types`, `relationship_types`, `relationships`, `scorecard_scores`, `scorecards`, `teams`
+Today (11): `custom_events`, `dependencies`, `deploys`, `entities`, `entity_types`, `relationship_types`, `relationships`, `scorecard_scores`, `scorecards`, `teams`, `users`
Diffed against: <https://docs.cortex.io/llms.txt>
-- [ ] `GET /api/v1/catalog/{tagOrId}/deploys` — deployment events per entity - deploy frequency and lead time, the headline Eng Intelligence metric (high)
-- [ ] `GET /api/v1/users` — user lookup with profile and role assignments; resolves entity owners and team members (high)
-- [ ] `GET /api/v1/catalog/{tagOrId}/custom-events` — arbitrary per-entity event stream (incidents, migrations, releases) pushed into Cortex (high)
+- [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)
-- [ ] `GET /api/v1/catalog/{callerTag}/dependencies` — service dependency graph edges; distinct from the entity-relationships already synced (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)
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.py
index f1563dfb27af..3da2dc16ecbb 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
@@ -109,6 +109,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"destinationLabelPlural": "Plural display label for destination entities of this relationship.",
},
},
+ "users": {
+ "description": "A user in the Cortex workspace, with the profile metadata used for access reviews and for resolving entity owners.",
+ "docs_url": "https://docs.cortex.io/api/readme/users",
+ "columns": {
+ "email": "Email address of the user.",
+ "name": "Display name of the user.",
+ "joinedAt": "Timestamp the user was first added to Cortex.",
+ "lastActiveAt": "Timestamp the user last logged in; null if they never have.",
+ },
+ },
+ "custom_events": {
+ "description": "A custom event recorded against a catalog entity, such as an incident, a migration, or a release.",
+ "docs_url": "https://docs.cortex.io/api/readme/custom-events",
+ "columns": {
+ "entity_tag": "Tag of the entity the event was recorded against.",
+ "entity_id": "CID of the entity the event was recorded against.",
+ "uuid": "Automatically generated identifier for the event.",
+ "type": "Type of the custom event.",
+ "title": "Name of the custom event.",
+ "description": "Optional description of the custom event.",
+ "timestamp": "Time the event occurred.",
+ "url": "Optional URL associated with the event.",
+ "customData": "Optional key/value data stored alongside the event.",
+ },
+ },
+ "deploys": {
+ "description": "A deployment event recorded against a catalog entity, the grain behind deploy frequency and lead time.",
+ "docs_url": "https://docs.cortex.io/api/readme/deploys",
+ "columns": {
+ "entity_tag": "Tag of the entity that was deployed.",
+ "entity_id": "CID of the entity that was deployed.",
+ "uuid": "Automatically generated identifier for the deploy.",
+ "type": "Kind of deploy event: DEPLOY, SCALE, ROLLBACK, or RESTART.",
+ "title": "Human readable title for the deploy, usually the commit message or pull request title.",
+ "timestamp": "Time the deploy happened, as a UTC ISO-8601 instant.",
+ "environment": "Environment the deploy went out to.",
+ "sha": "Commit SHA the deploy corresponds to, when supplied.",
+ "deployer": "Name and email of whoever ran the deploy.",
+ "url": "Optional URL associated with the deploy.",
+ "customData": "Arbitrary key/value data stored alongside the deploy.",
+ },
+ },
+ "dependencies": {
+ "description": "A dependency edge from one catalog entity to another, optionally scoped to a single endpoint of the callee.",
+ "docs_url": "https://docs.cortex.io/api/readme/dependencies",
+ "columns": {
+ "caller_entity_id": "CID of the calling entity.",
+ "callerTag": "Tag of the calling entity.",
+ "callerType": "Entity type of the caller.",
+ "calleeTag": "Tag of the entity being depended on.",
+ "calleeType": "Entity type of the callee.",
+ "method": "HTTP method of the callee endpoint the dependency refers to; empty when the dependency covers the whole entity.",
+ "path": "Path of the callee endpoint the dependency refers to; empty when the dependency covers the whole entity.",
+ "description": "Description of the dependency.",
+ "metadata": "Arbitrary JSON metadata attached to the dependency.",
+ },
+ },
"relationships": {
"description": "A single edge between two catalog entities for a given relationship type.",
"docs_url": "https://docs.cortex.io/api/readme/entity-relationships",
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.py
index 5436d55d34cc..82616e554704 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
@@ -1,8 +1,13 @@
from collections.abc import Iterable
+from datetime import UTC, datetime
from typing import Any, Optional, cast
+from urllib.parse import quote
from requests.exceptions import RequestException
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
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,
@@ -20,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
ClientConfig,
Endpoint,
EndpointResource,
+ IncrementalConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.settings import (
@@ -45,6 +51,36 @@ def _list_paginator(config: CortexEndpointConfig) -> BasePaginator:
return PageNumberPaginator(page_param="page", total_path=config.total_path)
+def _format_cortex_datetime(value: Any) -> str:
+ """Format a cursor value as the zone-less ISO-8601 instant Cortex's `startTime` documents."""
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ return min(normalized, datetime.now(UTC)).strftime("%Y-%m-%dT%H:%M:%S")
+
+
+def _incremental_window(cursor_path: str) -> IncrementalConfig:
+ return {
+ "cursor_path": cursor_path,
+ "start_param": "startTime",
+ "initial_value": "1970-01-01T00:00:00",
+ "convert": _format_cortex_datetime,
+ }
+
+
+def _encode_entity_tag(row: dict[str, Any]) -> dict[str, Any]:
+ """Derive the path-safe form of an entity tag for per-entity child paths.
+
+ Cortex matches a tag exactly as encoded, so a tag containing forward slashes only addresses
+ its entity once each `/` is percent-encoded.
+ """
+ row["tag_encoded"] = quote(str(row.get("tag") or ""), safe="")
+ return row
+
+
+_PARENT_DATA_MAPS = {"entities": _encode_entity_tag}
+
+
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.
@@ -93,9 +129,22 @@ def _flatten_relationship(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _normalize_dependency(item: dict[str, Any]) -> dict[str, Any]:
+ """Guarantee the key columns exist on every dependency row.
+
+ `method` and `path` are absent when an entity depends on the callee as a whole rather than on
+ one of its endpoints, and they are part of what identifies the edge. A missing or null key
+ column never matches on merge, so absent values normalize to an empty string.
+ """
+ for key in ("method", "path"):
+ item[key] = item.get(key) or ""
+ return item
+
+
_FANOUT_FLATTENERS = {
"scorecard_scores": _flatten_scorecard_score,
"relationships": _flatten_relationship,
+ "dependencies": _normalize_dependency,
}
@@ -120,8 +169,7 @@ def _make_source_response(config: CortexEndpointConfig, items_fn: Any) -> Source
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",
+ sort_mode=config.sort_mode,
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,
@@ -130,7 +178,15 @@ def _make_source_response(config: CortexEndpointConfig, items_fn: Any) -> Source
)
-def cortex_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+def cortex_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
config = CORTEX_ENDPOINTS[endpoint]
client_config = _client_config(api_key)
@@ -146,8 +202,11 @@ def cortex_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> Sou
path_format_values={},
team_id=team_id,
job_id=job_id,
- db_incremental_field_last_value=None,
- should_use_incremental_field=False,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=_incremental_window,
+ parent_data_map=_PARENT_DATA_MAPS.get(config.fanout.parent_name),
page_size_param="pageSize",
parent_endpoint_extra={
"paginator": _list_paginator(parent_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.py
index 2c66beac1db4..323fc9ac3815 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
@@ -3,6 +3,8 @@ 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.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField
# Cortex is a single global SaaS deployment (no regional hosts, no per-tenant subdomain).
@@ -12,7 +14,7 @@ CORTEX_BASE_URL = "https://api.getcortexapp.com/api/v1"
DEFAULT_PAGE_SIZE = 250
-@dataclass
+@dataclass(frozen=True)
class CortexEndpointConfig:
name: str
path: str
@@ -29,13 +31,32 @@ 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
- # Cortex's documented list endpoints expose no updated-since/created-since filter, so every
- # endpoint is full-refresh only.
+ # 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)
default_incremental_field: str | None = None
+ # Rows from a fan-out arrive grouped per parent, so the run only knows its true high-water
+ # mark once every parent has been walked. "desc" is what defers the watermark commit to the
+ # end of the run; committing per batch would skip history for parents not yet visited.
+ sort_mode: SortMode = "asc"
fanout: DependentEndpointConfig | None = None
+def _entity_fanout(resolve_param: str, parent_field_renames: dict[str, str]) -> DependentEndpointConfig:
+ """Fan out over the catalog, binding each entity to a per-entity child path.
+
+ Resolves on `tag_encoded` rather than `tag`: Cortex entity tags may contain forward slashes,
+ which have to be percent-encoded to address the entity (see `_encode_entity_tag` in cortex.py).
+ """
+ return DependentEndpointConfig(
+ parent_name="entities",
+ resolve_param=resolve_param,
+ resolve_field="tag_encoded",
+ include_from_parent=list(parent_field_renames),
+ parent_field_renames=parent_field_renames,
+ )
+
+
CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {
"entities": CortexEndpointConfig(
name="entities",
@@ -111,6 +132,62 @@ CORTEX_ENDPOINTS: dict[str, CortexEndpointConfig] = {
parent_field_renames={"tag": "relationship_type_tag"},
),
),
+ "users": CortexEndpointConfig(
+ name="users",
+ path="/users",
+ data_selector="users",
+ # The API exposes no user id; email is the documented unique handle for a workspace user.
+ primary_key=["email"],
+ total_path="totalPages",
+ partition_key="joinedAt",
+ ),
+ # Fans out over every entity and pulls its custom event stream (incidents, migrations,
+ # releases). `startTime` filters server-side on the event timestamp, so this is the one
+ # Cortex endpoint that can sync incrementally.
+ "custom_events": CortexEndpointConfig(
+ name="custom_events",
+ path="/catalog/{tagOrId}/custom-events",
+ data_selector="events",
+ primary_key=["entity_id", "uuid"],
+ total_path="totalPages",
+ partition_key="timestamp",
+ incremental_fields=[incremental_field("timestamp")],
+ default_incremental_field="timestamp",
+ sort_mode="desc",
+ fanout=_entity_fanout("tagOrId", {"tag": "entity_tag", "id": "entity_id"}),
+ ),
+ # Fans out over every entity and pulls its deployment events. The tenant-wide
+ # `/deploys/search` endpoint returns the same rows without the entity they belong to, so
+ # deploy frequency per entity has to come from the per-entity path.
+ "deploys": CortexEndpointConfig(
+ name="deploys",
+ path="/catalog/{tagOrId}/deploys",
+ data_selector="deployments",
+ primary_key=["entity_id", "uuid"],
+ total_path="totalPages",
+ partition_key="timestamp",
+ fanout=_entity_fanout("tagOrId", {"tag": "entity_tag", "id": "entity_id"}),
+ ),
+ # Fans out over every entity and pulls the dependency edges it calls. Each edge is
+ # identified by the caller, the callee and the optional endpoint it depends on, and the row
+ # carries its own `callerTag`, so the parent identifier is already part of the key.
+ "dependencies": CortexEndpointConfig(
+ name="dependencies",
+ path="/catalog/{callerTag}/dependencies",
+ data_selector="dependencies",
+ primary_key=["callerTag", "calleeTag", "method", "path"],
+ total_path="totalPages",
+ fanout=DependentEndpointConfig(
+ parent_name="entities",
+ resolve_param="callerTag",
+ resolve_field="tag_encoded",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "caller_entity_id"},
+ # Outgoing only: an edge is listed by both of its endpoints, so including incoming
+ # edges would fetch every edge twice under two different callers.
+ child_params={"includeOutgoing": "true", "includeIncoming": "false"},
+ ),
+ ),
}
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.py
index 65856e658919..b599a6dfdaae 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
@@ -79,6 +79,11 @@ class CortexSource(SimpleSource[CortexSourceConfig]):
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
@property
@@ -87,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, and entity relationships into the PostHog Data warehouse.
+ caption="""Enter your Cortex API key to sync your service catalog, scorecards, 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.""",
+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.""",
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.py
index a2401e825424..4f5aebb3bff8 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
@@ -1,3 +1,4 @@
+from datetime import UTC, datetime
from typing import Any, cast
from unittest.mock import Mock, patch
@@ -10,8 +11,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex import (
+ _encode_entity_tag,
_flatten_relationship,
_flatten_scorecard_score,
+ _format_cortex_datetime,
+ _normalize_dependency,
cortex_source,
get_resource,
validate_credentials,
@@ -221,3 +225,119 @@ class TestCortexTransport:
rows = list(cast(Any, response.items()))
assert rows[0]["relationship_type_tag"] == "depends-on"
+
+ @parameterized.expand(
+ [
+ ("plain", "payments-api", "payments-api"),
+ ("slashes", "/services/payments-api", "%2Fservices%2Fpayments-api"),
+ ("space_and_colon", "payments api:v2", "payments%20api%3Av2"),
+ ("missing", None, ""),
+ ]
+ )
+ def test_encode_entity_tag_makes_the_tag_addressable(self, _name: str, tag: str | None, expected: str) -> None:
+ # Cortex matches a tag exactly as encoded, so an unencoded slash addresses the wrong path.
+ assert _encode_entity_tag({"tag": tag})["tag_encoded"] == expected
+
+ @parameterized.expand(
+ [
+ ("absent", {}, "", ""),
+ ("null", {"method": None, "path": None}, "", ""),
+ ("present", {"method": "GET", "path": "/2.0/users"}, "GET", "/2.0/users"),
+ ]
+ )
+ def test_normalize_dependency_fills_the_key_columns(
+ self, _name: str, item: dict[str, Any], method: str, path: str
+ ) -> None:
+ normalized = _normalize_dependency(dict(item))
+ assert normalized["method"] == method
+ assert normalized["path"] == path
+
+ def test_format_cortex_datetime_drops_the_zone(self) -> None:
+ # Cortex documents startTime as a date-time without a time zone.
+ assert _format_cortex_datetime(datetime(2024, 3, 1, 9, 30, tzinfo=UTC)) == "2024-03-01T09:30:00"
+
+ def test_format_cortex_datetime_caps_a_future_cursor_at_now(self) -> None:
+ formatted = _format_cortex_datetime(datetime(2999, 1, 1, tzinfo=UTC))
+ assert formatted <= datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S")
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.rest_api_resource")
+ def test_cortex_source_users_partitions_on_joined_at(self, mock_rest_api_resource: Mock) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ response = cortex_source(api_key="cx_key", endpoint="users", team_id=1, job_id="job-1")
+
+ assert response.primary_keys == ["email"]
+ assert response.partition_keys == ["joinedAt"]
+ assert response.sort_mode == "asc"
+
+ @parameterized.expand(["custom_events", "deploys", "dependencies"])
+ @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
+ ) -> None:
+ mock_build_dependent_resource.return_value = _FakeDltResource(endpoint, [])
+
+ cortex_source(api_key="cx_key", endpoint=endpoint, team_id=1, job_id="job-1")
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["fanout"].parent_name == "entities"
+ assert kwargs["fanout"].resolve_field == "tag_encoded"
+ # Without the parent map the derived resolve field never exists on a parent row.
+ assert kwargs["parent_data_map"] is _encode_entity_tag
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")
+ def test_cortex_source_custom_events_incremental_passes_the_watermark(
+ self, mock_build_dependent_resource: Mock
+ ) -> None:
+ mock_build_dependent_resource.return_value = _FakeDltResource("custom_events", [])
+
+ response = cortex_source(
+ api_key="cx_key",
+ endpoint="custom_events",
+ team_id=1,
+ job_id="job-1",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "timestamp"
+ assert kwargs["db_incremental_field_last_value"] == datetime(2024, 3, 1, tzinfo=UTC)
+ window = kwargs["incremental_config_factory"]("timestamp")
+ assert window["start_param"] == "startTime"
+ assert window["cursor_path"] == "timestamp"
+ # Fan-out rows arrive grouped per entity, so the watermark may only commit once the whole
+ # run is done — an asc sync would checkpoint one entity's latest event over every entity
+ # it has not reached yet.
+ assert response.sort_mode == "desc"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")
+ def test_cortex_source_custom_events_full_refresh_omits_the_watermark(
+ self, mock_build_dependent_resource: Mock
+ ) -> None:
+ mock_build_dependent_resource.return_value = _FakeDltResource("custom_events", [])
+
+ cortex_source(api_key="cx_key", endpoint="custom_events", team_id=1, job_id="job-1")
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cortex.cortex.build_dependent_resource")
+ def test_cortex_source_dependencies_requests_outgoing_edges_only(self, mock_build_dependent_resource: Mock) -> None:
+ mock_build_dependent_resource.return_value = _FakeDltResource(
+ "dependencies", [{"callerTag": "a", "calleeTag": "b"}]
+ )
+
+ response = cortex_source(api_key="cx_key", endpoint="dependencies", team_id=1, job_id="job-1")
+ rows = list(cast(Any, response.items()))
+
+ # Each edge is listed by both of its endpoints; pulling incoming edges too would fetch
+ # every edge twice, under two different callers.
+ assert mock_build_dependent_resource.call_args.kwargs["fanout"].child_params == {
+ "includeOutgoing": "true",
+ "includeIncoming": "false",
+ }
+ assert rows[0]["method"] == "" and rows[0]["path"] == ""
+ assert response.primary_keys == ["callerTag", "calleeTag", "method", "path"]
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.py
index eeb8bd239b83..370ac5d6a56a 100644
--- 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.py
@@ -14,10 +14,18 @@ class TestCortexSource:
# A finished source must be visible: `unreleasedSource` hides it from every user.
assert not self.source.get_source_config.unreleasedSource
- def test_get_schemas_are_all_full_refresh(self) -> None:
- # Cortex exposes no server-side updated-since cursor, so no stream is incremental.
+ def test_only_custom_events_syncs_incrementally(self) -> None:
+ # `startTime` on the custom event stream is the only server-side time filter Cortex
+ # documents; every other list endpoint has to be re-read in full.
+ incremental = {
+ schema.name for schema in self.source.get_schemas(self.config, self.team_id) if schema.supports_incremental
+ }
+ assert incremental == {"custom_events"}
+
+ def test_full_refresh_schemas_advertise_no_cursor(self) -> None:
for schema in self.source.get_schemas(self.config, self.team_id):
- assert schema.supports_incremental is False
+ if schema.name == "custom_events":
+ continue
assert schema.supports_append is False
assert schema.incremental_fields == []