: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): sync vitally custom object records (#60730)
Tom Owers81acc1f02b63
diff --git a/posthog/temporal/data_imports/sources/vitally/settings.py b/posthog/temporal/data_imports/sources/vitally/settings.pyindex ce39bfa9d3b0..fb988c24501a 100644--- a/posthog/temporal/data_imports/sources/vitally/settings.py+++ b/posthog/temporal/data_imports/sources/vitally/settings.py@@ -13,6 +13,20 @@ ENDPOINTS = ("Messages",)+# Prefix used for schemas that sync the *instances* of a Vitally custom object.+# The `Custom_Objects` static endpoint syncs the definitions; one schema per object+# (named `Custom_Object_<machineName>`) syncs each object's actual records.+CUSTOM_OBJECT_SCHEMA_PREFIX = "Custom_Object_"++# Standard updated_at incremental field shared across all Vitally endpoints that+# expose an `updatedAt` server-side filter (which includes custom-object instances).+UPDATED_AT_INCREMENTAL_FIELD: IncrementalField = {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+}+INCREMENTAL_ENDPOINTS = ("Organizations","Accounts",diff --git a/posthog/temporal/data_imports/sources/vitally/source.py b/posthog/temporal/data_imports/sources/vitally/source.pyindex 3f9d84d9f46e..9a575a4e943e 100644--- a/posthog/temporal/data_imports/sources/vitally/source.py+++ b/posthog/temporal/data_imports/sources/vitally/source.py@@ -10,16 +10,20 @@ from posthog.schema import (SourceFieldSelectConfigOption,)+from posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import VitallySourceConfigfrom posthog.temporal.data_imports.sources.vitally.settings import (+ CUSTOM_OBJECT_SCHEMA_PREFIX,ENDPOINTS as VITALLY_ENDPOINTS,INCREMENTAL_FIELDS as VITALLY_INCREMENTAL_FIELDS,+ UPDATED_AT_INCREMENTAL_FIELD,)from posthog.temporal.data_imports.sources.vitally.vitally import (+ list_custom_object_definitions,validate_credentials as validate_vitally_credentials,vitally_source,)@@ -41,7 +45,7 @@ class VitallySource(SimpleSource[VitallySourceConfig]):names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [+ schemas: list[SourceSchema] = [SourceSchema(name=endpoint,supports_incremental=VITALLY_INCREMENTAL_FIELDS.get(endpoint, None) is not None,@@ -50,6 +54,38 @@ class VitallySource(SimpleSource[VitallySourceConfig]):)for endpoint in VITALLY_ENDPOINTS]++ # Discover custom objects and expose one schema per object so users can sync the+ # underlying records. The static `Custom_Objects` endpoint only returns the+ # definitions; instances live at `/resources/customObjects/:id/instances`.+ # Skip the outbound request when the caller only wants static schemas, and never+ # let a discovery failure take down the static endpoints that need no network call.+ if names is None or any(name.startswith(CUSTOM_OBJECT_SCHEMA_PREFIX) for name in names):+ try:+ definitions = list_custom_object_definitions(+ config.secret_token, config.region.selection, config.region.subdomain+ )+ except Exception as e:+ capture_exception(e)+ definitions = []++ for definition in definitions:+ machine_name = definition.get("name")+ if not machine_name:+ continue+ schema_name = f"{CUSTOM_OBJECT_SCHEMA_PREFIX}{machine_name}"+ if schema_name in VITALLY_ENDPOINTS:+ continue+ schemas.append(+ SourceSchema(+ name=schema_name,+ label=definition.get("label") or machine_name,+ supports_incremental=True,+ supports_append=True,+ incremental_fields=[UPDATED_AT_INCREMENTAL_FIELD],+ )+ )+if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]diff --git a/posthog/temporal/data_imports/sources/vitally/tests/test_vitally.py b/posthog/temporal/data_imports/sources/vitally/tests/test_vitally.pynew file mode 100644index 000000000000..2176af4e32cc--- /dev/null+++ b/posthog/temporal/data_imports/sources/vitally/tests/test_vitally.py@@ -0,0 +1,237 @@+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, Mock, patch++from posthog.temporal.data_imports.sources.vitally.settings import CUSTOM_OBJECT_SCHEMA_PREFIX+from posthog.temporal.data_imports.sources.vitally.source import VitallySource+from posthog.temporal.data_imports.sources.vitally.vitally import (+ get_custom_object_records_resource,+ list_custom_object_definitions,+ vitally_source,+)+++def _make_response(json_data: dict[str, Any], status_code: int = 200) -> Mock:+ response = Mock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = json_data+ response.raise_for_status = Mock()+ return response+++def _make_session(responses: list[Mock]) -> MagicMock:+ session = MagicMock()+ session.__enter__.return_value = session+ session.__exit__.return_value = False+ session.send.side_effect = responses+ # prepare_request returns its argument unchanged so the paginator's url updates+ # propagate to the next send() call.+ session.prepare_request.side_effect = lambda r: r+ return session+++FEATURE_REQUEST_DEFINITION = {+ "id": "f5dcbbd6-c69d-4402-b00e-7a34a27aded5",+ "name": "featureRequest",+ "label": "Feature Request",+}+OPPORTUNITY_DEFINITION = {+ "id": "5b50ffc0-849e-47e4-9954-25071a7d3636",+ "name": "Opportunity",+ "label": "Opportunity",+}+++class TestListCustomObjectDefinitions:+ @pytest.mark.parametrize(+ "pages,expected_defs,expected_call_count",+ [+ pytest.param(+ [{"results": [FEATURE_REQUEST_DEFINITION], "next": None}],+ [FEATURE_REQUEST_DEFINITION],+ 1,+ id="single_page",+ ),+ pytest.param(+ [+ {"results": [FEATURE_REQUEST_DEFINITION], "next": "cursor-2"},+ {"results": [OPPORTUNITY_DEFINITION], "next": None},+ ],+ [FEATURE_REQUEST_DEFINITION, OPPORTUNITY_DEFINITION],+ 2,+ id="paginates_until_next_is_null",+ ),+ pytest.param([{"results": [], "next": None}], [], 1, id="empty_results"),+ ],+ )+ @patch("posthog.temporal.data_imports.sources.vitally.vitally.make_tracked_session")+ def test_returns_definitions(self, mock_session_factory, pages, expected_defs, expected_call_count):+ session = _make_session([_make_response(page) for page in pages])+ mock_session_factory.return_value = session++ defs = list_custom_object_definitions("secret", "EU", None)++ assert defs == expected_defs+ assert session.send.call_count == expected_call_count++ @patch("posthog.temporal.data_imports.sources.vitally.vitally.make_tracked_session")+ def test_raises_on_http_error(self, mock_session_factory):+ bad = _make_response({}, status_code=401)+ bad.raise_for_status.side_effect = RuntimeError("401 Unauthorized")+ mock_session_factory.return_value = _make_session([bad])++ with pytest.raises(RuntimeError, match="401 Unauthorized"):+ list_custom_object_definitions("secret", "EU", None)+++class TestGetCustomObjectRecordsResource:+ @pytest.mark.parametrize("should_use_incremental_field", [False, True])+ def test_builds_resource(self, should_use_incremental_field):+ resource = get_custom_object_records_resource(+ "featureRequest", "f5dcbbd6", should_use_incremental_field=should_use_incremental_field+ )+ endpoint = cast(dict[str, Any], resource["endpoint"])++ assert endpoint["path"] == "/resources/customObjects/f5dcbbd6/instances"+ assert resource["name"] == f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest"+ assert resource["table_name"] == "custom_object_featurerequest"++ params = cast(dict[str, Any], endpoint["params"])+ if should_use_incremental_field:+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ assert params["sortBy"] == "updatedAt"+ updated_at_config = params["updatedAt"]+ assert isinstance(updated_at_config, dict)+ assert updated_at_config["type"] == "incremental"+ assert updated_at_config["cursor_path"] == "updatedAt"+ else:+ assert resource["write_disposition"] == "replace"+ assert params["updatedAt"] is None+++class TestVitallySourceCustomObjectRouting:+ @patch("posthog.temporal.data_imports.sources.vitally.vitally.rest_api_resource")+ @patch("posthog.temporal.data_imports.sources.vitally.vitally.list_custom_object_definitions")+ def test_resolves_machine_name_to_custom_object_id(self, mock_list, mock_rest_api):+ mock_list.return_value = [FEATURE_REQUEST_DEFINITION, OPPORTUNITY_DEFINITION]+ mock_rest_api.return_value = iter([{"id": "rec-1"}, {"id": "rec-2"}])++ rows = list(+ vitally_source(+ secret_token="secret",+ region="EU",+ subdomain=None,+ endpoint=f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest",+ team_id=1,+ job_id="job-1",+ logger=MagicMock(),+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ )+ )++ assert rows == [{"id": "rec-1"}, {"id": "rec-2"}]+ rest_call_kwargs = mock_rest_api.call_args+ config = rest_call_kwargs.args[0]+ assert len(config["resources"]) == 1+ assert (+ config["resources"][0]["endpoint"]["path"]+ == "/resources/customObjects/f5dcbbd6-c69d-4402-b00e-7a34a27aded5/instances"+ )++ @patch("posthog.temporal.data_imports.sources.vitally.vitally.list_custom_object_definitions")+ def test_raises_for_unknown_custom_object(self, mock_list):+ mock_list.return_value = [OPPORTUNITY_DEFINITION]++ with pytest.raises(ValueError, match="featureRequest"):+ list(+ vitally_source(+ secret_token="secret",+ region="EU",+ subdomain=None,+ endpoint=f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest",+ team_id=1,+ job_id="job-1",+ logger=MagicMock(),+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ )+ )+++class TestVitallySourceGetSchemas:+ def _make_config(self):+ config = MagicMock()+ config.secret_token = "secret"+ config.region.selection = "EU"+ config.region.subdomain = None+ return config++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_includes_static_endpoints_and_dynamic_custom_objects(self, mock_list):+ mock_list.return_value = [FEATURE_REQUEST_DEFINITION, OPPORTUNITY_DEFINITION]++ schemas = VitallySource().get_schemas(self._make_config(), team_id=1)++ names = {s.name for s in schemas}+ # Static endpoints+ assert {"Accounts", "Conversations", "Custom_Objects", "Messages"} <= names+ # Dynamic custom object schemas+ assert f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest" in names+ assert f"{CUSTOM_OBJECT_SCHEMA_PREFIX}Opportunity" in names++ feature_request = next(s for s in schemas if s.name == f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest")+ assert feature_request.label == "Feature Request"+ assert feature_request.supports_incremental is True+ assert feature_request.supports_append is True+ assert len(feature_request.incremental_fields) == 1++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_skips_definitions_without_a_name(self, mock_list):+ mock_list.return_value = [{"id": "abc", "name": "", "label": "empty"}, FEATURE_REQUEST_DEFINITION]++ schemas = VitallySource().get_schemas(self._make_config(), team_id=1)++ dynamic = [s for s in schemas if s.name.startswith(CUSTOM_OBJECT_SCHEMA_PREFIX)]+ assert len(dynamic) == 1+ assert dynamic[0].name == f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest"++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_falls_back_to_machine_name_when_label_missing(self, mock_list):+ mock_list.return_value = [{"id": "abc", "name": "widget"}]++ schemas = VitallySource().get_schemas(self._make_config(), team_id=1)++ widget = next(s for s in schemas if s.name == f"{CUSTOM_OBJECT_SCHEMA_PREFIX}widget")+ assert widget.label == "widget"++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_names_filter_applies_to_both_static_and_dynamic(self, mock_list):+ mock_list.return_value = [FEATURE_REQUEST_DEFINITION]++ schemas = VitallySource().get_schemas(+ self._make_config(),+ team_id=1,+ names=["Accounts", f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest"],+ )++ assert {s.name for s in schemas} == {"Accounts", f"{CUSTOM_OBJECT_SCHEMA_PREFIX}featureRequest"}++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_skips_discovery_when_only_static_schemas_requested(self, mock_list):+ schemas = VitallySource().get_schemas(self._make_config(), team_id=1, names=["Accounts", "Conversations"])++ mock_list.assert_not_called()+ assert {s.name for s in schemas} == {"Accounts", "Conversations"}++ @patch("posthog.temporal.data_imports.sources.vitally.source.list_custom_object_definitions")+ def test_static_schemas_survive_discovery_failure(self, mock_list):+ mock_list.side_effect = RuntimeError("Vitally API unavailable")++ schemas = VitallySource().get_schemas(self._make_config(), team_id=1)++ names = {s.name for s in schemas}+ assert {"Accounts", "Conversations", "Custom_Objects", "Messages"} <= names+ assert not any(s.name.startswith(CUSTOM_OBJECT_SCHEMA_PREFIX) for s in schemas)diff --git a/posthog/temporal/data_imports/sources/vitally/vitally.py b/posthog/temporal/data_imports/sources/vitally/vitally.pyindex 1d772727d45b..02c193f6d550 100644--- a/posthog/temporal/data_imports/sources/vitally/vitally.py+++ b/posthog/temporal/data_imports/sources/vitally/vitally.py@@ -10,6 +10,7 @@ from posthog.temporal.data_imports.sources.common.http import make_tracked_sessifrom posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resourcefrom posthog.temporal.data_imports.sources.common.rest_source.paginators import BasePaginatorfrom posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from posthog.temporal.data_imports.sources.vitally.settings import CUSTOM_OBJECT_SCHEMA_PREFIXdef get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:@@ -263,6 +264,73 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResoureturn resources[name]+def get_custom_object_records_resource(+ custom_object_machine_name: str, custom_object_id: str, should_use_incremental_field: bool+) -> EndpointResource:+ """Build an EndpointResource that pulls records (instances) for a single Vitally custom object.++ See https://docs.vitally.io/pushing-data-to-vitally/rest-api/custom-objects — list endpoint is+ `/resources/customObjects/:customObjectId/instances`.+ """+ return {+ "name": f"{CUSTOM_OBJECT_SCHEMA_PREFIX}{custom_object_machine_name}",+ "table_name": f"custom_object_{custom_object_machine_name.lower()}",+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "data_selector": "results",+ "path": f"/resources/customObjects/{custom_object_id}/instances",+ "params": {+ "limit": 100,+ "sortBy": "updatedAt",+ "updatedAt": {+ "type": "incremental",+ "cursor_path": "updatedAt",+ "initial_value": "1970-01-01",+ "convert": lambda x: parser.parse(x).timestamp() if not isinstance(x, datetime) else x,+ }+ if should_use_incremental_field+ else None,+ },+ },+ "table_format": "delta",+ }+++def list_custom_object_definitions(secret_token: str, region: str, subdomain: Optional[str]) -> list[dict[str, Any]]:+ """Page through the Vitally custom object *definitions* endpoint.++ Used at schema discovery time to enumerate every custom object the workspace has,+ and at sync time to resolve a `Custom_Object_<machineName>` schema back to its UUID+ (Vitally instance endpoints require the id, not the name)."""+ paginator = VitallyPaginator(incremental_start_value=None, should_use_incremental_field=False)+ basic_token = base64.b64encode(f"{secret_token}:".encode("ascii")).decode("ascii")++ request = Request(+ "get",+ url=f"{get_base_url(region, subdomain)}resources/customObjects",+ params={"limit": 100},+ headers={"Authorization": f"Basic {basic_token}"},+ )++ results: list[dict[str, Any]] = []+ with make_tracked_session() as session:+ while paginator.has_next_page:+ paginator.update_request(request)+ prepared = session.prepare_request(request)+ response = session.send(prepared)+ response.raise_for_status()+ data = response.json()+ results.extend(data.get("results") or [])+ paginator.update_state(response)++ return results++class VitallyPaginator(BasePaginator):_incremental_start_value: Any_should_use_incremental_field: bool = False@@ -422,6 +490,19 @@ def vitally_source()return+ if endpoint.startswith(CUSTOM_OBJECT_SCHEMA_PREFIX):+ machine_name = endpoint[len(CUSTOM_OBJECT_SCHEMA_PREFIX) :]+ definitions = list_custom_object_definitions(secret_token, region, subdomain)+ match = next((d for d in definitions if d.get("name") == machine_name), None)+ if match is None or not match.get("id"):+ raise ValueError(+ f"Vitally custom object '{machine_name}' could not be resolved. "+ "It may have been deleted or renamed in Vitally; refresh source schemas to pick up the new name."+ )+ endpoint_resource = get_custom_object_records_resource(machine_name, match["id"], should_use_incremental_field)+ else:+ endpoint_resource = get_resource(endpoint, should_use_incremental_field)+config: RESTAPIConfig = {"client": {"base_url": get_base_url(region, subdomain),@@ -443,11 +524,10 @@ def vitally_source(if should_use_incremental_fieldelse "replace",},- "resources": [get_resource(endpoint, should_use_incremental_field)],+ "resources": [endpoint_resource],}- resource = rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)- yield from resource+ yield from rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)def validate_credentials(secret_token: str, region: str, subdomain: Optional[str]) -> bool: