: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
fix(data-warehouse): correct AppsFlyer v5 report slug, CSV format, and validation errors (#64894)
Luke Belton6111751782ea
diff --git a/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.pyindex a0ef2c80b51b..233371296f2b 100644--- a/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py+++ b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py@@ -37,7 +37,12 @@ class AppsFlyerCredentialsError(Exception):def _get_session(api_token: str) -> requests.Session:- return make_tracked_session(headers={"Authorization": f"Bearer {api_token}"}, redact_values=(api_token,))+ # the v5 docs are a bit ambiguous about whether the return format defaults to CSV+ # or JSON, so we explicitly request CSV for safety.+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_token}", "Accept": "text/csv"},+ redact_values=(api_token,),+ )def _validate_app_id(app_id: str) -> str:@@ -87,8 +92,10 @@ def validate_credentials(api_token: str, app_id: str) -> bool:Returns ``True`` when the probe succeeds. Raises ``AppsFlyerCredentialsError`` with auser-facing message when AppsFlyer rejects the token or app id (the status code tells the- two apart), ``AppsFlyerRetryableError`` on rate-limit / 5xx responses, and lets transport- errors propagate so the caller can tell a transient failure apart from a bad credential.+ two apart) or returns any other unexpected status, ``AppsFlyerRetryableError`` on+ rate-limit / 5xx responses, and lets transport errors propagate so the caller can tell a+ transient failure apart from a bad credential. Never returns ``False`` — a non-200 always+ raises so the failure is never silently conflated with a bad credential."""try:app = _validate_app_id(app_id)@@ -99,7 +106,7 @@ def validate_credentials(api_token: str, app_id: str) -> bool:) from Nonetoday = datetime.now(UTC).strftime("%Y-%m-%d")response = _get_session(api_token).get(- f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/dailyreport/v5"+ f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/daily_report/v5"f"?{urlencode({'from': today, 'to': today})}",timeout=30,)@@ -121,7 +128,12 @@ def validate_credentials(api_token: str, app_id: str) -> bool:)if response.status_code == 404:raise AppsFlyerCredentialsError("AppsFlyer couldn't find an app with that app id. Please check the app id.")- return False+ # Any other status is unexpected (e.g. a 400 from a malformed request) — surface the real+ # code rather than blaming the token or app id, which sends users debugging the wrong thing.+ raise AppsFlyerCredentialsError(+ f"AppsFlyer returned an unexpected response (HTTP {response.status_code}) while validating credentials. "+ "If your app id and API token (V2) look correct, please try again shortly or contact support."+ )def get_rows(diff --git a/posthog/temporal/data_imports/sources/appsflyer/settings.py b/posthog/temporal/data_imports/sources/appsflyer/settings.pyindex 0abe0d50e8b3..966d85e4f911 100644--- a/posthog/temporal/data_imports/sources/appsflyer/settings.py+++ b/posthog/temporal/data_imports/sources/appsflyer/settings.py@@ -32,7 +32,7 @@ class AppsFlyerEndpointConfig:APPSFLYER_ENDPOINTS: dict[str, AppsFlyerEndpointConfig] = {"daily_report": AppsFlyerEndpointConfig(name="daily_report",- report="dailyreport",+ report="daily_report",),"geo_report": AppsFlyerEndpointConfig(name="geo_report",diff --git a/posthog/temporal/data_imports/sources/appsflyer/source.py b/posthog/temporal/data_imports/sources/appsflyer/source.pyindex 56195efca041..54fd0c629edc 100644--- a/posthog/temporal/data_imports/sources/appsflyer/source.py+++ b/posthog/temporal/data_imports/sources/appsflyer/source.py@@ -109,8 +109,10 @@ You can find your API token (V2) in AppsFlyer under your account menu > Securityself, config: AppsFlyerSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:try:- if validate_appsflyer_credentials(config.api_token, config.app_id):- return True, None+ # validate_credentials returns True or raises — it never returns False — so an+ # unexpected status surfaces its real cause instead of a conflated credential error.+ validate_appsflyer_credentials(config.api_token, config.app_id)+ return True, Noneexcept AppsFlyerCredentialsError as e:# The token or app id was rejected — surface which one rather than a conflated message.return False, str(e)@@ -121,8 +123,6 @@ You can find your API token (V2) in AppsFlyer under your account menu > Security"Could not reach AppsFlyer to validate credentials. This may be a temporary rate-limit or network issue — please try again.",)- return False, "Invalid AppsFlyer API token or app id"-def source_for_pipeline(self, config: AppsFlyerSourceConfig, inputs: SourceInputs) -> SourceResponse:return appsflyer_source(api_token=config.api_token,diff --git a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.pyindex ffc12e094af5..13dd08a87aca 100644--- a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py@@ -117,6 +117,15 @@ class TestValidateCredentials:assert "app id" in str(exc.value)mock_session.return_value.get.assert_not_called()+ @pytest.mark.parametrize("status_code", [400, 418, 451])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_raises_with_status_on_unexpected_code(self, mock_session, status_code):+ mock_session.return_value.get.return_value = _response("", status=status_code)++ with pytest.raises(AppsFlyerCredentialsError) as exc:+ validate_credentials("token", "id123")+ assert str(status_code) in str(exc.value)+@pytest.mark.parametrize("status_code", [429, 500, 503])@mock.patch(f"{_MODULE}.make_tracked_session")def test_validate_raises_on_transient_status(self, mock_session, status_code):@@ -140,7 +149,24 @@ class TestGetRows:query = parse_qs(urlparse(url).query)window = date.fromisoformat(query["to"][0]) - date.fromisoformat(query["from"][0])assert window.days == MAX_WINDOW_DAYS- assert urlparse(url).path == "/api/agg-data/export/app/id123/dailyreport/v5"+ assert urlparse(url).path == "/api/agg-data/export/app/id123/daily_report/v5"++ @pytest.mark.parametrize(+ "endpoint, expected_path",+ [+ ("daily_report", "/api/agg-data/export/app/id123/daily_report/v5"),+ ("geo_report", "/api/agg-data/export/app/id123/geo_by_date_report/v5"),+ ("partners_report", "/api/agg-data/export/app/id123/partners_by_date_report/v5"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_report_slug_matches_appsflyer_api(self, mock_session, endpoint, expected_path):+ mock_session.return_value.get.return_value = _response(_CSV)++ list(get_rows("token", "id123", endpoint, mock.MagicMock()))++ url = mock_session.return_value.get.call_args.args[0]+ assert urlparse(url).path == expected_path@mock.patch(f"{_MODULE}.make_tracked_session")def test_incremental_starts_at_watermark_minus_lookback(self, mock_session):@@ -173,6 +199,15 @@ class TestGetRows:assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_requests_csv_explicitly(self, mock_session):+ mock_session.return_value.get.return_value = _response(_CSV)++ list(get_rows("token", "id123", "daily_report", mock.MagicMock()))++ headers = mock_session.call_args.kwargs["headers"]+ assert headers["Accept"] == "text/csv"+@mock.patch(f"{_MODULE}.make_tracked_session")def test_empty_report_yields_nothing(self, mock_session):mock_session.return_value.get.return_value = _response("Date,Media Source (pid)\n")diff --git a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.pyindex 56bb70461512..3ecf7996b3d8 100644--- a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py@@ -48,9 +48,9 @@ class TestAppsFlyerSource:@pytest.mark.parametrize("observed_error",[- "401 Client Error: Unauthorized for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/dailyreport/v5",+ "401 Client Error: Unauthorized for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/daily_report/v5","403 Client Error: Forbidden for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/geo_by_date_report/v5",- "404 Client Error: Not Found for url: https://hq1.appsflyer.com/api/agg-data/export/app/nope/dailyreport/v5",+ "404 Client Error: Not Found for url: https://hq1.appsflyer.com/api/agg-data/export/app/nope/daily_report/v5",],)def test_non_retryable_errors_match_auth_failures(self, observed_error):@@ -61,7 +61,7 @@ class TestAppsFlyerSource:"other_vendor_error",["401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",- "500 Server Error for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/dailyreport/v5",+ "500 Server Error for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/daily_report/v5",],)def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):@@ -90,21 +90,12 @@ class TestAppsFlyerSource:def test_get_schemas_filtered_unknown_name_returns_empty(self):assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []- @pytest.mark.parametrize(- "mock_return, expected_valid, expected_message",- [- (True, True, None),- (False, False, "Invalid AppsFlyer API token or app id"),- ],- )@mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.validate_appsflyer_credentials")- def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):- mock_validate.return_value = mock_return-+ def test_validate_credentials_succeeds(self, mock_validate):is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)- assert is_valid is expected_valid- assert error_message == expected_message+ assert is_valid is True+ assert error_message is Nonemock_validate.assert_called_once_with("token", "id123")@pytest.mark.parametrize(