: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 AppsFlyer raw data and Master API tables (#99211)
Tom Owersa4f084649777
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 c052ffde04a9..f9a6cacfb4ad 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@@ -433,14 +433,14 @@ Note: Full v2 endpoint list read from the docs nav (slugs encode the HTTP path).## AppsFlyer — **thin**-Today (3): `daily_report`, `geo_report`, `partners_report`+Today (9): `ad_revenue`, `ad_revenue_organic`, `ad_revenue_retargeting`, `daily_report`, `geo_report`, `in_app_events`, `installs`, `master_report`, `partners_report`Diffed against: <https://dev.appsflyer.com/hc/reference>-- [ ] `/api/raw-data/export/app/{app_id}/installs_report/v5` — install-level raw rows — the core AppsFlyer dataset for attribution modelling (high)-- [ ] `/api/raw-data/export/app/{app_id}/in_app_events_report/v5` — raw in-app event rows, needed to join revenue and funnel events to media source (high)-- [ ] `/api/master-agg-data/v4/app/{app_id} (Master API)` — single aggregated cross-app report with cohort KPIs, the vendor's recommended aggregate feed (high)-- [ ] `/api/raw-data/export/app/{app_id}/ad_revenue_raw/v5 (plus organic and retargeting variants)` — ad monetization revenue per user, missing entirely from the aggregate reports (high)+- [x] `/api/raw-data/export/app/{app_id}/installs_report/v5` — install-level raw rows — the core AppsFlyer dataset for attribution modelling (high)+- [x] `/api/raw-data/export/app/{app_id}/in_app_events_report/v5` — raw in-app event rows, needed to join revenue and funnel events to media source (high)+- [x] `/api/master-agg-data/v4/app/{app_id} (Master API)` — single aggregated cross-app report with cohort KPIs, the vendor's recommended aggregate feed (high)+- [x] `/api/raw-data/export/app/{app_id}/ad_revenue_raw/v5 (plus organic and retargeting variants)` — ad monetization revenue per user, missing entirely from the aggregate reports (high)- [ ] `/api/raw-data/export/app/{app_id}/uninstall_events_report/v5` — uninstall events, required for retention and LTV net of churn (high)- [ ] `/api/raw-data/export/app/{app_id}/organic_installs_report/v5 and organic_in_app_events_report/v5` — organic baseline without which paid lift cannot be computed (high)- [ ] `/api/raw-data/export/app/{app_id}/installs_retarget/v5 and in_app_events_retarget/v5` — retargeting conversions, reported separately from UA and otherwise invisible (high)@@ -450,7 +450,7 @@ Diffed against: <https://dev.appsflyer.com/hc/reference>- [ ] `/api/raw-data/export/app/{app_id}/reinstalls/v5 and reinstalls_organic/v5` — reinstall/resurrection cohorts, a distinct lifecycle state from installs (medium)- [ ] `/api/agg-data/export/app/{app_id}/geo_by_date_report/v5 and partners_by_date_report/v5` — daily time series of the geo and partner breakdowns we currently sync only as period totals (medium)-Note: PostHog exposes three aggregate Pull API v5 reports (daily, geo, partners). The entire raw-data pull API (install/event/uninstall level rows), ad revenue, retargeting, Protect360 fraud, SKAN and the cross-app Master API are absent — that is the bulk of what warehouse users pull from AppsFlyer. Reference index enumerated from the docs nav (~160 slugs).+Note: PostHog exposes three aggregate Pull API v5 reports (daily, geo, partners), the raw-data install and in-app-event reports, all three ad revenue raw reports, and the Master API LTV report. Still absent: uninstalls, reinstalls, the organic install/event baseline, retargeting conversions, Protect360 fraud, SKAN and the partner postback reports. Reference index enumerated from the docs nav (~160 slugs).## Appsignal — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.pyindex 9c07d51a7c3c..1847908b7a80 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/appsflyer.py@@ -1,16 +1,22 @@import ioimport reimport csv-from collections.abc import Iterator+from collections.abc import Iterable, Iteratorfrom datetime import UTC, date, datetime, timedelta-from typing import Any+from typing import IO, Any, castfrom urllib.parse import quote, urlencodeimport requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter-from products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.settings import APPSFLYER_ENDPOINTS+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.settings import (+ APPSFLYER_ENDPOINTS,+ AppsFlyerEndpointConfig,+ AppsFlyerReportKind,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -20,12 +26,38 @@ MAX_WINDOW_DAYS = 999# AppsFlyer doesn't finalize data until ~48h after the UTC day; re-fetch the# trailing days each incremental run (merge dedupes on the dimension key).LOOKBACK_DAYS = 2+# Raw-data pulls are refused beyond a 90-day historical lookback ("Raw reports historical+# lookback is limited to 90 days"), so never ask for a window that starts earlier.+RAW_MAX_LOOKBACK_DAYS = 89+# Raw reports are truncated server-side at this many rows; ask for the larger of the two+# allowed caps and warn when a window fills it, because the rest is dropped silently.+RAW_MAX_ROWS = 1_000_000+# Raw reports are pulled in chronological windows rather than one long range, so the stream is+# ascending across windows even though AppsFlyer documents no order within one. Keep the window+# wide enough that a 90-day backfill stays inside the account's daily report quota.+RAW_MAX_REQUEST_DAYS = 7+# An incremental run must be able to re-cover a whole window, because a worker shutdown can+# interrupt one mid-way and rows within it are not ordered. So never look back less than a window.+RAW_LOOKBACK_DAYS = RAW_MAX_REQUEST_DAYS+# The Master API serves at most 31 days per call, so a backfill walks it in windows.+MASTER_MAX_REQUEST_DAYS = 31+# Each window is one call against the account's daily report quota, so bound the backfill.+MASTER_MAX_LOOKBACK_DAYS = 365+# Master API KPIs are LTV measures that keep accruing after install day, so an incremental run+# re-pulls the trailing month. That also covers a whole request window, as above.+MASTER_LOOKBACK_DAYS = MASTER_MAX_REQUEST_DAYSREQUEST_TIMEOUT_SECONDS = 300MAX_RETRY_ATTEMPTS = 5# Yield rows in chunks so huge reports don't build one giant list.CHUNK_SIZE = 5000+@frozen+class _ReportWindow:+ start: date+ end: date++class AppsFlyerRetryableError(Exception):pass@@ -65,8 +97,10 @@ def _to_date(value: Any) -> date:return date.fromisoformat(str(value)[:10])-def _parse_csv_rows(text: str, logger: FilteringBoundLogger | None = None) -> Iterator[dict[str, Any]]:- reader = csv.reader(io.StringIO(text))+def _parse_csv_rows(+ source: str | Iterable[str], logger: FilteringBoundLogger | None = None+) -> Iterator[dict[str, Any]]:+ reader = csv.reader(io.StringIO(source) if isinstance(source, str) else source)headers: list[str] | None = Nonefor row in reader:if headers is None:@@ -87,6 +121,109 @@ def _parse_csv_rows(text: str, logger: FilteringBoundLogger | None = None) -> Ityield dict(zip(headers, row))+def _report_url(config: AppsFlyerEndpointConfig, app_id: str, params: dict[str, str]) -> str:+ if config.kind == AppsFlyerReportKind.MASTER:+ path = f"/api/master-agg-data/v4/app/{quote(app_id)}"+ elif config.kind == AppsFlyerReportKind.RAW:+ path = f"/api/raw-data/export/app/{quote(app_id)}/{config.report}/v5"+ else:+ path = f"/api/agg-data/export/app/{quote(app_id)}/{config.report}/v5"+ return f"{APPSFLYER_BASE_URL}{path}?{urlencode(params)}"+++def _request_params(config: AppsFlyerEndpointConfig, window: _ReportWindow) -> dict[str, str]:+ params = {"from": window.start.strftime("%Y-%m-%d"), "to": window.end.strftime("%Y-%m-%d")}+ if config.kind == AppsFlyerReportKind.RAW:+ params["maximum_rows"] = str(RAW_MAX_ROWS)+ params.update(config.extra_params)+ return params+++def _max_lookback_days(kind: AppsFlyerReportKind) -> int:+ if kind == AppsFlyerReportKind.RAW:+ return RAW_MAX_LOOKBACK_DAYS+ if kind == AppsFlyerReportKind.MASTER:+ return MASTER_MAX_LOOKBACK_DAYS+ return MAX_WINDOW_DAYS+++def _incremental_lookback_days(kind: AppsFlyerReportKind) -> int:+ if kind == AppsFlyerReportKind.RAW:+ return RAW_LOOKBACK_DAYS+ if kind == AppsFlyerReportKind.MASTER:+ return MASTER_LOOKBACK_DAYS+ return LOOKBACK_DAYS+++def _max_request_days(kind: AppsFlyerReportKind) -> int | None:+ """Days one request may span, or ``None`` when the whole range goes in a single request."""+ if kind == AppsFlyerReportKind.RAW:+ return RAW_MAX_REQUEST_DAYS+ if kind == AppsFlyerReportKind.MASTER:+ return MASTER_MAX_REQUEST_DAYS+ return None+++def _window_start(+ config: AppsFlyerEndpointConfig,+ today: date,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> date:+ earliest = today - timedelta(days=_max_lookback_days(config.kind))+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ start = _to_date(db_incremental_field_last_value) - timedelta(days=_incremental_lookback_days(config.kind))+ else:+ start = earliest+ return min(max(start, earliest), today)+++def _request_windows(kind: AppsFlyerReportKind, start: date, end: date) -> Iterator[_ReportWindow]:+ span = _max_request_days(kind)+ if span is None:+ yield _ReportWindow(start=start, end=end)+ return+ window_start = start+ while window_start <= end:+ window_end = min(window_start + timedelta(days=span - 1), end)+ yield _ReportWindow(start=window_start, end=window_end)+ window_start = window_end + timedelta(days=1)+++@retry(+ retry=retry_if_exception_type((AppsFlyerRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+)+def _open_report(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"AppsFlyer API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.close()+ response.raise_for_status()++ return response+++def _iter_report_rows(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:+ response = _open_report(session, url, logger)+ try:+ # Read physical lines off the socket rather than buffering the whole body: a raw-data+ # window can hold a million event rows. Wrapping the stream (instead of `iter_lines`)+ # keeps the line terminators csv needs for quoted multi-line values.+ response.raw.decode_content = True+ stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8", newline="")+ yield from _parse_csv_rows(stream, logger)+ finally:+ response.close()++def validate_credentials(api_token: str, app_id: str) -> bool:"""Confirm the token and app id are valid with a one-day report probe.@@ -149,38 +286,26 @@ def get_rows(app = _validate_app_id(app_id)today = datetime.now(UTC).date()- if should_use_incremental_field and db_incremental_field_last_value is not None:- start = _to_date(db_incremental_field_last_value) - timedelta(days=LOOKBACK_DAYS)- else:- start = today - timedelta(days=MAX_WINDOW_DAYS)- start = min(max(start, today - timedelta(days=MAX_WINDOW_DAYS)), today)-- @retry(- retry=retry_if_exception_type((AppsFlyerRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),- wait=wait_exponential_jitter(initial=5, max=120),- reraise=True,- )- def fetch_report() -> str:- params = {"from": start.strftime("%Y-%m-%d"), "to": today.strftime("%Y-%m-%d")}- url = f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/{config.report}/v5?{urlencode(params)}"- response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)-- if response.status_code == 429 or response.status_code >= 500:- raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}, url={url}")-- if not response.ok:- logger.error(f"AppsFlyer API error: status={response.status_code}, body={response.text[:500]}, url={url}")- response.raise_for_status()-- return response.text+ start = _window_start(config, today, should_use_incremental_field, db_incremental_field_last_value)chunk: list[dict[str, Any]] = []- for row in _parse_csv_rows(fetch_report(), logger):- chunk.append(row)- if len(chunk) >= CHUNK_SIZE:- yield chunk- chunk = []+ for window in _request_windows(config.kind, start, today):+ url = _report_url(config, app, _request_params(config, window))+ rows_in_window = 0+ for row in _iter_report_rows(session, url, logger):+ rows_in_window += 1+ chunk.append(row)+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []+ if config.kind == AppsFlyerReportKind.RAW and rows_in_window >= RAW_MAX_ROWS:+ logger.warning(+ "AppsFlyer truncated the raw report at its row cap; some rows in this window were not returned",+ report=endpoint,+ window_start=window.start.isoformat(),+ window_end=window.end.isoformat(),+ row_cap=RAW_MAX_ROWS,+ )if chunk:yield chunk@@ -209,8 +334,8 @@ def appsflyer_source(partition_count=1,partition_size=1,partition_mode="datetime",- partition_format="month",- partition_keys=["date"],+ partition_format=config.partition_format,+ partition_keys=[config.partition_key],sort_mode="asc",# Dimension keys can collide (e.g. blank campaign values) — an expected trait of report# data, not something the user can fix. Don't set has_duplicate_primary_keys: that flagdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/canonical_descriptions.pyindex df12667722ac..7feebd8f58d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/canonical_descriptions.py@@ -1,7 +1,7 @@-"""Canonical, documentation-sourced descriptions for AppsFlyer aggregate Pull API reports and columns.+"""Canonical, documentation-sourced descriptions for AppsFlyer Pull API reports and columns.-Sourced from the official AppsFlyer Pull API / aggregate report reference-(https://support.appsflyer.com/hc/en-us/articles/207034366-Pull-APIs-aggregate-and-raw-data).+Sourced from the official AppsFlyer references for the aggregate Pull API, the raw-data Pull API+and the Master API; each entry below links the page it came from.Keyed by the report names in `settings.py` `APPSFLYER_ENDPOINTS`, which match the`ExternalDataSchema.name` of a synced AppsFlyer table. Column names are the CSV headers normalized tosnake_case (see `_normalize_header`); columns absent here fall back to LLM enrichment.@@ -37,6 +37,56 @@ def _columns(**overrides: str) -> dict[str, str]:return {**_COMMON_COLUMNS, **overrides}+# Event-level columns shared by the raw-data reports (CSV headers normalized to snake_case). Raw+# reports are built from one wide schema, so a column that doesn't apply to a report comes back+# empty rather than absent.+_RAW_COLUMNS = {+ "appsflyer_id": "Unique AppsFlyer device identifier the event belongs to.",+ "customer_user_id": "Your own user identifier, if it was set in the SDK.",+ "event_time": "Time the event happened, in the report's timezone.",+ "install_time": "Time the user first opened the app.",+ "attributed_touch_type": "Touch that won attribution (click or impression).",+ "attributed_touch_time": "Time of the attributed click or impression.",+ "event_name": "Name of the recorded event.",+ "event_value": "Event parameters as sent by the SDK.",+ "event_revenue": "Revenue reported with the event, in the event's currency.",+ "event_revenue_currency": "Currency the event revenue was reported in.",+ "event_revenue_usd": "Event revenue converted to US dollars.",+ "media_source": "Media source the install is attributed to.",+ "channel": "Channel within the media source.",+ "campaign": "Campaign name the install is attributed to.",+ "campaign_id": "Campaign identifier from the media source.",+ "adset": "Ad set name the install is attributed to.",+ "ad": "Ad name the install is attributed to.",+ "site_id": "Publisher or site identifier reported by the media source.",+ "partner": "Agency or PMD partner credited for the activity.",+ "cost_model": "Cost model the campaign is billed on.",+ "cost_value": "Cost attributed to the install, in the cost currency.",+ "cost_currency": "Currency the cost is reported in.",+ "country_code": "Two-letter country code the event came from.",+ "city": "City the event came from.",+ "ip": "IP address the event came from.",+ "platform": "Device platform (ios, android, and so on).",+ "device_type": "Device make and model group.",+ "os_version": "Operating system version of the device.",+ "app_version": "Version of your app that sent the event.",+ "app_id": "App the event belongs to.",+ "is_retargeting": "Whether the record came from a retargeting campaign.",+ "is_primary_attribution": "Whether this is the primary attribution record for the install.",+ "advertising_id": "Google Advertising ID of the device.",+ "idfa": "Apple advertising identifier of the device.",+ "idfv": "Apple vendor identifier of the device.",+}++_AD_REVENUE_COLUMNS = {+ **_RAW_COLUMNS,+ "monetization_network": "Ad network that paid for the impressions.",+ "ad_unit": "Ad unit the impressions were served in.",+ "placement": "Placement the ad was shown in.",+ "impressions": "Number of impressions the revenue row aggregates.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"daily_report": {"description": "Daily aggregate performance per media source and campaign — installs, clicks, cost, and revenue by date.",@@ -55,4 +105,43 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"docs_url": "https://support.appsflyer.com/hc/en-us/articles/207034366-Pull-APIs-aggregate-and-raw-data","columns": _columns(),},+ "installs": {+ "description": "One row per attributed (non-organic) install, with the media source, campaign and touch that won attribution.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/get_app-id-installs-report-v5",+ "columns": _RAW_COLUMNS,+ },+ "in_app_events": {+ "description": "One row per in-app event from an attributed user, carrying the event name, value and revenue alongside the install's attribution.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/get_app-id-in-app-events-report-v5",+ "columns": _RAW_COLUMNS,+ },+ "ad_revenue": {+ "description": "Ad monetization revenue per user for attributed installs, aggregated by monetization network, ad unit and placement.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/get_app-id-ad-revenue-raw-v5",+ "columns": _AD_REVENUE_COLUMNS,+ },+ "ad_revenue_organic": {+ "description": "Ad monetization revenue per user for organic installs, aggregated by monetization network, ad unit and placement.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/get_app-id-ad-revenue-organic-raw-v5",+ "columns": _AD_REVENUE_COLUMNS,+ },+ "ad_revenue_retargeting": {+ "description": "Ad monetization revenue per user attributed to retargeting campaigns, aggregated by monetization network, ad unit and placement.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/get_app-id-ad-revenue-raw-retarget-v5",+ "columns": _AD_REVENUE_COLUMNS,+ },+ "master_report": {+ "description": "Master API LTV report: install-day cohorts broken down by agency, media source, campaign and country, with the generic lifetime-value KPIs.",+ "docs_url": "https://dev.appsflyer.com/hc/reference/master_api_get",+ "columns": {+ **{name: description for name, description in _COMMON_COLUMNS.items() if name != "date"},+ "install_time": "Install date of the cohort the metrics are reported for.",+ "country": "Country the cohort installed from.",+ "sessions": "Number of sessions the cohort has opened since install.",+ "cr": "Conversion rate from click to install.",+ "arpu": "Average revenue per user across the cohort's lifetime.",+ "uninstalls": "Number of users in the cohort who uninstalled the app.",+ "uninstall_rate": "Share of the cohort that uninstalled the app.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/settings.pyindex 742ef5680517..8bd9655ae52a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/settings.py@@ -1,5 +1,9 @@-from dataclasses import dataclass, field+from dataclasses import field+from enum import StrEnum+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormatfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [@@ -11,12 +15,69 @@ _DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [},]+_EVENT_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "event_time",+ "type": IncrementalFieldType.DateTime,+ "field": "event_time",+ "field_type": IncrementalFieldType.DateTime,+ },+]++_INSTALL_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "install_time",+ "type": IncrementalFieldType.Date,+ "field": "install_time",+ "field_type": IncrementalFieldType.Date,+ },+]+++class AppsFlyerReportKind(StrEnum):+ """Which Pull API serves a report. Each one has its own path, date window and row limits."""-@dataclass+ AGGREGATE = "aggregate"+ RAW = "raw"+ MASTER = "master"+++# The Master API needs both groupings and kpis. The groupings mirror the aggregate reports'+# dimensions so the two line up; the KPIs are the documented generic LTV set, because the+# pattern KPIs (cohort_*, retention_*, event_counter_*) depend on the account's package and a+# single unavailable KPI fails the whole report.+_MASTER_GROUPINGS = ("install_time", "af_prt", "pid", "c", "geo")+_MASTER_KPIS = (+ "impressions",+ "clicks",+ "installs",+ "cr",+ "sessions",+ "loyal_users",+ "loyal_users_rate",+ "cost",+ "revenue",+ "roi",+ "arpu_ltv",+ "average_ecpi",+ "uninstalls",+ "uninstalls_rate",+)++# Ad revenue's monetization columns are additional fields, so ask for them by name: they carry the+# grain AppsFlyer aggregates device-level ad revenue on, which is what the row key needs.+_AD_REVENUE_ADDITIONAL_FIELDS = ("monetization_network", "ad_unit", "placement", "impressions")++_RAW_EVENT_PRIMARY_KEYS = ["appsflyer_id", "event_time"]+_AD_REVENUE_PRIMARY_KEYS = [*_RAW_EVENT_PRIMARY_KEYS, "monetization_network", "ad_unit", "placement"]+++@frozenclass AppsFlyerEndpointConfig:name: str- # Report slug in /api/agg-data/export/app/{app_id}/{report}/v5.- report: str+ # Report slug in the Pull API path. Empty for the Master API, whose path carries no slug.+ report: str = ""+ kind: AppsFlyerReportKind = AppsFlyerReportKind.AGGREGATE# Aggregate reports have no row ids; the dimension columns (normalized# headers) form the key, and collisions are tolerated via the duplicate-pk# flag.@@ -24,11 +85,16 @@ class AppsFlyerEndpointConfig:default_factory=lambda: ["date", "agency_pmd_af_prt", "media_source_pid", "campaign_c"])incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DATE_INCREMENTAL_FIELDS))+ partition_key: str = "date"+ partition_format: PartitionFormat = "month"+ # Query params sent on every request for this report, on top of the date window.+ extra_params: dict[str, str] = field(default_factory=dict)# AppsFlyer's aggregate Pull API returns CSV per date window (max ~1000 days);-# headers are normalized to snake_case columns. Raw-data Pull APIs require-# separate subscriptions and are a follow-up.+# headers are normalized to snake_case columns. The raw-data Pull API returns+# event-level CSV rows over a 90-day window, and the Master API returns one+# aggregate LTV report per 31-day window.APPSFLYER_ENDPOINTS: dict[str, AppsFlyerEndpointConfig] = {"daily_report": AppsFlyerEndpointConfig(name="daily_report",@@ -43,6 +109,65 @@ APPSFLYER_ENDPOINTS: dict[str, AppsFlyerEndpointConfig] = {name="partners_report",report="partners_by_date_report",),+ "installs": AppsFlyerEndpointConfig(+ name="installs",+ report="installs_report",+ kind=AppsFlyerReportKind.RAW,+ primary_keys=list(_RAW_EVENT_PRIMARY_KEYS),+ incremental_fields=list(_EVENT_TIME_INCREMENTAL_FIELDS),+ partition_key="event_time",+ partition_format="day",+ ),+ "in_app_events": AppsFlyerEndpointConfig(+ name="in_app_events",+ report="in_app_events_report",+ kind=AppsFlyerReportKind.RAW,+ primary_keys=[*_RAW_EVENT_PRIMARY_KEYS, "event_name"],+ incremental_fields=list(_EVENT_TIME_INCREMENTAL_FIELDS),+ partition_key="event_time",+ partition_format="day",+ ),+ "ad_revenue": AppsFlyerEndpointConfig(+ name="ad_revenue",+ report="ad_revenue_raw",+ kind=AppsFlyerReportKind.RAW,+ primary_keys=list(_AD_REVENUE_PRIMARY_KEYS),+ incremental_fields=list(_EVENT_TIME_INCREMENTAL_FIELDS),+ partition_key="event_time",+ partition_format="day",+ extra_params={"additional_fields": ",".join(_AD_REVENUE_ADDITIONAL_FIELDS)},+ ),+ "ad_revenue_organic": AppsFlyerEndpointConfig(+ name="ad_revenue_organic",+ report="ad_revenue_organic_raw",+ kind=AppsFlyerReportKind.RAW,+ primary_keys=list(_AD_REVENUE_PRIMARY_KEYS),+ incremental_fields=list(_EVENT_TIME_INCREMENTAL_FIELDS),+ partition_key="event_time",+ partition_format="day",+ extra_params={"additional_fields": ",".join(_AD_REVENUE_ADDITIONAL_FIELDS)},+ ),+ "ad_revenue_retargeting": AppsFlyerEndpointConfig(+ name="ad_revenue_retargeting",+ report="ad-revenue-raw-retarget",+ kind=AppsFlyerReportKind.RAW,+ primary_keys=list(_AD_REVENUE_PRIMARY_KEYS),+ incremental_fields=list(_EVENT_TIME_INCREMENTAL_FIELDS),+ partition_key="event_time",+ partition_format="day",+ extra_params={"additional_fields": ",".join(_AD_REVENUE_ADDITIONAL_FIELDS)},+ ),+ "master_report": AppsFlyerEndpointConfig(+ name="master_report",+ kind=AppsFlyerReportKind.MASTER,+ primary_keys=["install_time", "agency_pmd_af_prt", "media_source_pid", "campaign_c", "country"],+ incremental_fields=list(_INSTALL_TIME_INCREMENTAL_FIELDS),+ partition_key="install_time",+ extra_params={+ "groupings": ",".join(_MASTER_GROUPINGS),+ "kpis": ",".join(_MASTER_KPIS),+ },+ ),}ENDPOINTS = tuple(APPSFLYER_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/source.pyindex aa7474b0c3e4..6cf08854d60f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/source.py@@ -56,8 +56,12 @@ class AppsFlyerSource(SimpleSource[AppsFlyerSourceConfig]):def get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://hq1.appsflyer.com": "AppsFlyer authentication failed. Please check your API token (V2).",- "403 Client Error: Forbidden for url: https://hq1.appsflyer.com": "AppsFlyer denied access. Please check that your account's subscription includes the aggregate Pull API and the app id is correct.",+ "403 Client Error: Forbidden for url: https://hq1.appsflyer.com": "AppsFlyer denied access. Please check that your account's subscription includes the report being synced and the app id is correct.","404 Client Error: Not Found for url: https://hq1.appsflyer.com": "AppsFlyer app not found. Please check the app id.",+ # A 400 from the Pull API is always a rejected request shape: the daily report quota is+ # used up, the date range predates the raw-data lookback limit, or the row cap is+ # invalid. None of those change if we send the identical call again.+ "400 Client Error: Bad Request for url: https://hq1.appsflyer.com": "AppsFlyer rejected the report request. Your account's daily quota for this report may be used up, which resets at 00:00 UTC. Otherwise please check that your subscription includes this report.",# AppsFlyer overloads 416 as a catch-all for request/authorization validation failures on# the aggregate Pull API (e.g. the account isn't authorized for this report or app id). The# request shape is fixed, so retrying the identical call can never satisfy it.@@ -70,9 +74,11 @@ class AppsFlyerSource(SimpleSource[AppsFlyerSourceConfig]):name=SchemaExternalDataSourceType.APPS_FLYER,category=DataWarehouseSourceCategory.ADVERTISING,label="AppsFlyer",- caption="""Enter your AppsFlyer credentials to pull aggregate performance reports into the PostHog Data warehouse.+ caption="""Enter your AppsFlyer credentials to pull aggregate performance reports and raw event data into the PostHog Data warehouse.-You can find your API token (V2) in AppsFlyer under your account menu > Security center > AppsFlyer API tokens. The app id is your app's identifier as shown in the dashboard (e.g. `id123456789` for iOS or the package name for Android) — add one source per app.""",+You can find your API token (V2) in AppsFlyer under your account menu > Security center > AppsFlyer API tokens. The app id is your app's identifier as shown in the dashboard (e.g. `id123456789` for iOS or the package name for Android). Add one source per app.++Raw data tables (installs, in-app events and ad revenue) and the Master API report need an AppsFlyer subscription that covers them, and AppsFlyer limits raw data to the last 90 days.""",iconPath="/static/services/appsflyer.png",docsUrl="https://posthog.com/docs/cdp/sources/appsflyer",releaseStatus=ReleaseStatus.ALPHA,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.pyindex 2a65ceeb31cd..fb8ac20c3552 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py@@ -1,4 +1,5 @@-from datetime import UTC, date, datetime+import io+from datetime import UTC, date, datetime, timedeltafrom urllib.parse import parse_qs, urlparseimport pytest@@ -8,7 +9,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.efrom products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.appsflyer import (CHUNK_SIZE,LOOKBACK_DAYS,+ MASTER_MAX_LOOKBACK_DAYS,+ MASTER_MAX_REQUEST_DAYS,MAX_WINDOW_DAYS,+ RAW_LOOKBACK_DAYS,+ RAW_MAX_LOOKBACK_DAYS,+ RAW_MAX_REQUEST_DAYS,+ RAW_MAX_ROWS,AppsFlyerCredentialsError,AppsFlyerRetryableError,_normalize_header,@@ -33,14 +40,34 @@ _CSV = ()+class _Raw(io.BytesIO):+ """Stands in for urllib3's raw stream, which the transport sets `decode_content` on."""++ decode_content = False++def _response(text: str, status: int = 200) -> mock.MagicMock:resp = mock.MagicMock()resp.text = text+ resp.raw = _Raw(text.encode())resp.status_code = statusresp.ok = status < 400return resp+def _serve(text: str = _CSV, status: int = 200):+ """A fresh response per call, since each request consumes its own stream."""+ return lambda *args, **kwargs: _response(text, status)+++def _requested_windows(mock_session: mock.MagicMock) -> list[tuple[date, date]]:+ windows = []+ for call in mock_session.return_value.get.call_args_list:+ query = parse_qs(urlparse(call.args[0]).query)+ windows.append((date.fromisoformat(query["from"][0]), date.fromisoformat(query["to"][0])))+ return windows++class TestHelpers:@pytest.mark.parametrize("header, expected",@@ -143,7 +170,7 @@ class TestValidateCredentials:class TestGetRows:@mock.patch(f"{_MODULE}.make_tracked_session")def test_full_pull_uses_max_window(self, mock_session):- mock_session.return_value.get.return_value = _response(_CSV)+ mock_session.return_value.get.side_effect = _serve()batches = list(get_rows("token", "id123", "daily_report", mock.MagicMock()))@@ -161,20 +188,26 @@ class TestGetRows:("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"),+ ("installs", "/api/raw-data/export/app/id123/installs_report/v5"),+ ("in_app_events", "/api/raw-data/export/app/id123/in_app_events_report/v5"),+ ("ad_revenue", "/api/raw-data/export/app/id123/ad_revenue_raw/v5"),+ ("ad_revenue_organic", "/api/raw-data/export/app/id123/ad_revenue_organic_raw/v5"),+ ("ad_revenue_retargeting", "/api/raw-data/export/app/id123/ad-revenue-raw-retarget/v5"),+ ("master_report", "/api/master-agg-data/v4/app/id123"),],)@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)+ mock_session.return_value.get.side_effect = _serve()list(get_rows("token", "id123", endpoint, mock.MagicMock()))- url = mock_session.return_value.get.call_args.args[0]- assert urlparse(url).path == expected_path+ for call in mock_session.return_value.get.call_args_list:+ assert urlparse(call.args[0]).path == expected_path@mock.patch(f"{_MODULE}.make_tracked_session")def test_incremental_starts_at_watermark_minus_lookback(self, mock_session):- mock_session.return_value.get.return_value = _response(_CSV)+ mock_session.return_value.get.side_effect = _serve()watermark = datetime.now(UTC).date()list(@@ -197,7 +230,7 @@ class TestGetRows:def test_rows_are_chunked(self, mock_session):header = "Date,Agency/PMD (af_prt),Media Source (pid),Campaign (c)\n"body = "".join(f"2024-01-01,a,m,c{i}\n" for i in range(CHUNK_SIZE + 1))- mock_session.return_value.get.return_value = _response(header + body)+ mock_session.return_value.get.side_effect = _serve(header + body)batches = list(get_rows("token", "id123", "daily_report", mock.MagicMock()))@@ -205,7 +238,7 @@ class TestGetRows:@mock.patch(f"{_MODULE}.make_tracked_session")def test_requests_csv_explicitly(self, mock_session):- mock_session.return_value.get.return_value = _response(_CSV)+ mock_session.return_value.get.side_effect = _serve()list(get_rows("token", "id123", "daily_report", mock.MagicMock()))@@ -214,11 +247,127 @@ class TestGetRows:@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")+ mock_session.return_value.get.side_effect = _serve("Date,Media Source (pid)\n")assert list(get_rows("token", "id123", "daily_report", mock.MagicMock())) == []+class TestRawAndMasterWindows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_raw_pull_walks_contiguous_windows_inside_the_lookback_limit(self, mock_session):+ # AppsFlyer refuses a raw window starting more than 90 days back, and the windows have to+ # tile the range exactly once: a gap loses rows, an overlap re-merges them, and a window+ # that doesn't advance loops forever.+ mock_session.return_value.get.side_effect = _serve()+ today = datetime.now(UTC).date()++ list(get_rows("token", "id123", "installs", mock.MagicMock()))++ windows = _requested_windows(mock_session)+ assert windows[0][0] == today - timedelta(days=RAW_MAX_LOOKBACK_DAYS)+ assert windows[-1][1] == today+ for window_start, window_end in windows:+ assert 0 <= (window_end - window_start).days < RAW_MAX_REQUEST_DAYS+ for (_, previous_end), (next_start, _) in zip(windows, windows[1:]):+ assert next_start == previous_end + timedelta(days=1)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_master_pull_never_exceeds_the_31_day_call_limit(self, mock_session):+ # The Master API rejects a range wider than 31 days, so the backfill has to be windowed.+ mock_session.return_value.get.side_effect = _serve()+ today = datetime.now(UTC).date()++ list(get_rows("token", "id123", "master_report", mock.MagicMock()))++ windows = _requested_windows(mock_session)+ assert windows[0][0] == today - timedelta(days=MASTER_MAX_LOOKBACK_DAYS)+ assert windows[-1][1] == today+ for window_start, window_end in windows:+ assert 0 <= (window_end - window_start).days < MASTER_MAX_REQUEST_DAYS++ @pytest.mark.parametrize("endpoint", ["installs", "in_app_events", "ad_revenue"])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_raw_incremental_repulls_a_whole_window_before_the_watermark(self, mock_session, endpoint):+ # A worker shutdown can interrupt a window part-way through, and AppsFlyer documents no row+ # order within one, so the next run has to start far enough back to redo the whole window.+ mock_session.return_value.get.side_effect = _serve()+ watermark = datetime.now(UTC).date() - timedelta(days=10)++ list(+ get_rows(+ "token",+ "id123",+ endpoint,+ mock.MagicMock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )++ windows = _requested_windows(mock_session)+ assert windows[0][0] == watermark - timedelta(days=RAW_LOOKBACK_DAYS)+ assert RAW_LOOKBACK_DAYS >= RAW_MAX_REQUEST_DAYS++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_raw_pull_asks_for_the_larger_row_cap(self, mock_session):+ # Without maximum_rows AppsFlyer truncates at 200k rows per window.+ mock_session.return_value.get.side_effect = _serve()++ list(get_rows("token", "id123", "installs", mock.MagicMock()))++ query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)+ assert query["maximum_rows"] == [str(RAW_MAX_ROWS)]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_ad_revenue_pull_requests_its_monetization_dimensions(self, mock_session):+ # monetization_network / ad_unit / placement are additional fields, and they make up the+ # row key — without them every revenue row for a user collapses onto one key.+ mock_session.return_value.get.side_effect = _serve()++ list(get_rows("token", "id123", "ad_revenue", mock.MagicMock()))++ query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)+ requested = set(query["additional_fields"][0].split(","))+ assert {"monetization_network", "ad_unit", "placement"} <= requested+ assert set(APPSFLYER_ENDPOINTS["ad_revenue"].primary_keys) - {"appsflyer_id", "event_time"} <= requested++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_master_pull_sends_groupings_and_kpis(self, mock_session):+ # The Master API rejects a request that omits either one.+ mock_session.return_value.get.side_effect = _serve()++ list(get_rows("token", "id123", "master_report", mock.MagicMock()))++ query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)+ assert "install_time" in query["groupings"][0].split(",")+ assert "installs" in query["kpis"][0].split(",")++ @mock.patch(f"{_MODULE}.RAW_MAX_ROWS", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_warns_when_a_raw_window_fills_the_row_cap(self, mock_session):+ # AppsFlyer drops the rest of the window silently, so the sync has to say so.+ mock_session.return_value.get.side_effect = _serve()+ logger = mock.MagicMock()++ list(get_rows("token", "id123", "installs", logger))++ assert logger.warning.called++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_value_with_an_embedded_newline_survives_streaming(self, mock_session):+ # Raw event values carry newlines; splitting the body into lines would tear the row apart.+ csv_body = 'AppsFlyer ID,Event Time,Event Value\naf-1,2024-01-01 00:00:00,"line one\nline two"\n'+ mock_session.return_value.get.side_effect = _serve(csv_body)++ rows = [row for batch in get_rows("token", "id123", "installs", mock.MagicMock()) for row in batch]++ assert rows[0] == {+ "appsflyer_id": "af-1",+ "event_time": "2024-01-01 00:00:00",+ "event_value": "line one\nline two",+ }++class TestAppsFlyerSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):@@ -229,7 +378,8 @@ class TestAppsFlyerSourceResponse:assert response.primary_keys == config.primary_keysassert response.sort_mode == "asc"assert response.partition_mode == "datetime"- assert response.partition_keys == ["date"]+ assert response.partition_keys == [config.partition_key]+ assert response.partition_format == config.partition_format# Dimension keys can collide (blank campaigns etc), but that's expected for report data# and must not block incremental syncing - regression test for the schema-wide incremental# sync outage this caused when has_duplicate_primary_keys was set unconditionally.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.pyindex 3edd4eb7b95d..caaea40901eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py@@ -31,6 +31,7 @@ class TestAppsFlyerSource:"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/daily_report/v5","416 Client Error: Requested Range Not Satisfiable for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/geo_by_date_report/v5?from=2024-01-01&to=2024-01-05",+ "400 Client Error: Bad Request for url: https://hq1.appsflyer.com/api/raw-data/export/app/id123/installs_report/v5?from=2024-01-01&to=2024-01-07",],)def test_non_retryable_errors_match_auth_failures(self, observed_error):