: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): implement applovin source (#73759)
Tom Owers27dba0b69754
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 66fb5aa0eb52..77207edb5269 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -75,6 +75,7 @@ the row lists both.| appdynamics | HTTP | requests | ✅ || appfigures | HTTP | requests | ✅ || appfollow | HTTP | requests | ✅ |+| applovin | HTTP | requests | ✅ || appsflyer | HTTP (CSV reports) | requests | ✅ || appsignal | HTTP (REST + GraphQL) | requests | ✅ || appstack | HTTP | requests + `rest_source.RESTClient` | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/applovin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/applovin.pynew file mode 100644index 000000000000..efeef5683459--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/applovin.py@@ -0,0 +1,292 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import (+ APPLOVIN_API_BASE_URL,+ APPLOVIN_ENDPOINTS,+ MAX_REQUEST_WINDOW_DAYS,+ REPORT_LOOKBACK_DAYS,+ REPORT_PAGE_SIZE,+ REPORT_WINDOW_DAYS,+ AppLovinEndpointConfig,+)+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.http.url_utils import redact_literal_values+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++REQUEST_TIMEOUT_SECONDS = 120+VALIDATION_TIMEOUT_SECONDS = 30++# Matched by `AppLovinSource.get_non_retryable_errors`, so keep these stable.+AUTH_ERROR_PREFIX = "AppLovin denied the request"+BAD_REQUEST_ERROR_PREFIX = "AppLovin rejected the report request"+# Deliberately NOT registered as non-retryable: the tracked session already retried the request,+# and an upstream outage must not permanently disable the source.+TRANSIENT_ERROR_PREFIX = "AppLovin API error (retryable)"++_AUTH_STATUS_CODES = (401, 403)+++class AppLovinAPIError(Exception):+ pass+++def _utc_today() -> date:+ return datetime.now(tz=UTC).date()+++def _redacted(message: str, api_key: str) -> str:+ """Strip the Report Key out of a message before it can reach a user-visible error.++ A transport error quotes the request URL, where the key is URL-encoded, so redact the+ raw, percent-encoded, and plus-encoded forms via the shared value-based masker.+ """+ return redact_literal_values(message, (api_key,)) if api_key else message+++def _to_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _body_code(body: Any) -> Optional[int]:+ """AppLovin echoes its own status in the JSON body's `code` key; 200 means success."""+ if not isinstance(body, dict):+ return None+ try:+ return int(body["code"])+ except (KeyError, TypeError, ValueError):+ return None+++def _is_transient_status(status_code: int) -> bool:+ """Throttling and upstream failures, which the source must keep retrying."""+ return status_code == 429 or status_code >= 500+++def _prefix_for_code(code: int) -> str:+ if code in _AUTH_STATUS_CODES:+ return AUTH_ERROR_PREFIX+ if _is_transient_status(code):+ return TRANSIENT_ERROR_PREFIX+ return BAD_REQUEST_ERROR_PREFIX+++def _build_url(config: AppLovinEndpointConfig, api_key: str, start: date, end: date, offset: int) -> str:+ params: dict[str, Any] = {+ "api_key": api_key,+ "columns": ",".join(config.columns),+ "start": start.isoformat(),+ "end": end.isoformat(),+ "format": "json",+ "limit": REPORT_PAGE_SIZE,+ "offset": offset,+ # Pin the order so limit/offset paging can't reshuffle rows between pages, and so rows+ # arrive oldest-first (`sort_mode="asc"` on the response).+ "sort_day": "ASC",+ **config.extra_params,+ }+ return f"{APPLOVIN_API_BASE_URL}{config.path}?{urlencode(params)}"+++def _fetch_page(+ session: requests.Session,+ config: AppLovinEndpointConfig,+ api_key: str,+ start: date,+ end: date,+ offset: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ url = _build_url(config, api_key, start, end, offset)++ try:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)+ except requests.RequestException as e:+ # `requests`/`urllib3` transport errors quote the full request URL, which carries the+ # Report Key as a query param. Re-raise redacted, and drop the cause so the original+ # (unredacted) message can't be surfaced through the exception chain.+ raise AppLovinAPIError(f"AppLovin request failed: {_redacted(str(e), api_key)}") from None++ if response.status_code in _AUTH_STATUS_CODES:+ raise AppLovinAPIError(f"{AUTH_ERROR_PREFIX}: status={response.status_code}, endpoint={config.path}")++ if _is_transient_status(response.status_code):+ raise AppLovinAPIError(f"{TRANSIENT_ERROR_PREFIX}: status={response.status_code}, endpoint={config.path}")++ if not response.ok:+ raise AppLovinAPIError(+ f"{BAD_REQUEST_ERROR_PREFIX}: status={response.status_code}, endpoint={config.path}, "+ f"body={_redacted(response.text, api_key)[:500]}"+ )++ try:+ body = response.json()+ except ValueError:+ raise AppLovinAPIError(+ f"{BAD_REQUEST_ERROR_PREFIX}: endpoint={config.path} returned a non-JSON body: "+ f"{_redacted(response.text, api_key)[:500]}"+ ) from None++ code = _body_code(body)+ if code is not None and code != 200:+ raise AppLovinAPIError(f"{_prefix_for_code(code)}: body code={code}, endpoint={config.path}")++ results = body.get("results") if isinstance(body, dict) else None+ if not isinstance(results, list):+ logger.debug(f"AppLovin: {config.name} returned no results list for {start.isoformat()}..{end.isoformat()}")+ return []++ return [row for row in results if isinstance(row, dict)]+++class AppLovinResumeConfig:+ # First day (YYYY-MM-DD) of the report window still being fetched.+ next_window_start: Optional[str] = None+ # `offset` of the next unfetched page within that window.+ next_offset: int = 0+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: "ResumableSourceManager[AppLovinResumeConfig]",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = APPLOVIN_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_key,))++ today = _utc_today()+ # The API refuses dates older than the request window, so clamp every start to it rather+ # than letting a stale watermark produce a guaranteed error.+ earliest = today - timedelta(days=MAX_REQUEST_WINDOW_DAYS - 1)++ start = earliest+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ start = max(earliest, watermark - timedelta(days=REPORT_LOOKBACK_DAYS))++ offset = 0+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.next_window_start:+ resumed = _to_date(resume_config.next_window_start)+ if resumed is not None and earliest <= resumed <= today and resumed >= start:+ start = resumed+ offset = resume_config.next_offset+ logger.debug(f"AppLovin: resuming {endpoint} from {start.isoformat()} offset {offset}")++ while start <= today:+ window_end = min(start + timedelta(days=REPORT_WINDOW_DAYS - 1), today)++ while True:+ rows = _fetch_page(session, config, api_key, start, window_end, offset, logger)+ if rows:+ yield rows++ # A short page means the window is exhausted: AppLovin returns an empty set once+ # `offset` passes the total row count.+ if len(rows) < REPORT_PAGE_SIZE:+ break++ offset += REPORT_PAGE_SIZE+ # Saved after yielding so a crash re-yields the in-flight page instead of skipping+ # it (the merge dedupes on the dimension primary key).+ resumable_source_manager.save_state(+ AppLovinResumeConfig(next_window_start=start.isoformat(), next_offset=offset)+ )++ start = window_end + timedelta(days=1)+ offset = 0+ if start <= today:+ resumable_source_manager.save_state(+ AppLovinResumeConfig(next_window_start=start.isoformat(), next_offset=0)+ )++ # The whole window is walked, so drop the checkpoint rather than leaving a later attempt to+ # resume from the final report window.+ resumable_source_manager.clear_state()+++def validate_credentials(api_key: str) -> bool:+ """Confirm the Report Key is accepted by at least one reporting endpoint.++ A key belonging to a publisher-only account and one belonging to an advertiser-only account+ both authenticate against `/maxReport` and `/report`, so a single probe would reject a valid+ key for the other account shape. Probe both and accept the first success.+ """+ session = make_tracked_session(redact_values=(api_key,))+ today = _utc_today()++ for path, extra_params in (("/maxReport", {}), ("/report", {"report_type": "publisher"})):+ params: dict[str, Any] = {+ "api_key": api_key,+ "columns": "day,impressions",+ "start": today.isoformat(),+ "end": today.isoformat(),+ "format": "json",+ "limit": 1,+ **extra_params,+ }+ try:+ response = session.get(+ f"{APPLOVIN_API_BASE_URL}{path}?{urlencode(params)}", timeout=VALIDATION_TIMEOUT_SECONDS+ )+ if not response.ok:+ continue+ code = _body_code(response.json())+ except Exception: # noqa: BLE001 — a credential probe must never raise out of source create+ continue++ if code is None or code == 200:+ return True++ return False+++def applovin_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: "ResumableSourceManager[AppLovinResumeConfig]",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = APPLOVIN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ # Windows are walked oldest-first and each request pins `sort_day=ASC`, so `day` only+ # ever moves forward; the restatement re-pull happens below the saved watermark and+ # merges on the dimension primary key.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/canonical_descriptions.pynew file mode 100644index 000000000000..5446162a10e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/canonical_descriptions.py@@ -0,0 +1,153 @@+"""Canonical, documentation-sourced descriptions for AppLovin report endpoints and columns.++Sourced from the AppLovin support centre API references linked per entry below. Keyed by the+endpoint names in `settings.py` `APPLOVIN_ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced AppLovin table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import COHORT_DAY_OFFSETS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_MAX_REPORT_DOCS_URL = "https://support.applovin.com/en/max/reporting-apis/revenue-reporting-api"+_REPORT_DOCS_URL = "https://support.applovin.com/en/growth/promoting-your-apps/api/reporting-api"+_COHORT_DOCS_URL = "https://support.applovin.com/en/max/reporting-apis/cohort-api"+++def _horizon_columns(prefix: str, template: str) -> dict[str, str]:+ """Expand a per-horizon cohort metric into one description per requested day offset."""+ return {f"{prefix}_{offset}": template.format(days=offset) for offset in COHORT_DAY_OFFSETS}+++_APP_DIMENSIONS = {+ "day": "Day of the data, in YYYY-MM-DD format (UTC).",+ "application": "Name of the application.",+ "package_name": "Package name (Android) or bundle ID (iOS) of the application.",+ "store_id": "Numeric part of the iTunes ID on iOS, or the package name on Android. Falls back to the bundle ID when AppLovin doesn't know the iTunes ID.",+ "platform": "Platform of the application: android, fireos or ios.",+ "country": "Two-letter ISO country code of the user.",+ "device_type": "The user's device type: phone, tablet or other.",+}++_COHORT_DIMENSION_DESCRIPTIONS = {+ "day": _APP_DIMENSIONS["day"],+ "application": _APP_DIMENSIONS["application"],+ "package_name": _APP_DIMENSIONS["package_name"],+ "platform": _APP_DIMENSIONS["platform"],+ "country": _APP_DIMENSIONS["country"],+ "installs": "Number of new installers on this day.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "max_ad_revenue": {+ "description": "Estimated MAX mediation revenue and delivery, broken down by day, app, ad unit and the ad network that filled the impression.",+ "docs_url": _MAX_REPORT_DOCS_URL,+ "columns": {+ **_APP_DIMENSIONS,+ "ad_format": "Ad unit ad type: INTER, BANNER or REWARD.",+ "max_ad_unit": "MAX Ad Unit name.",+ "max_ad_unit_id": "MAX Ad Unit ID.",+ "network": "Ad network name that served the impression.",+ "impressions": "Number of impressions shown.",+ "attempts": "Number of attempts made to the ad network.",+ "responses": "Number of responses received from the ad network.",+ "fill_rate": "Responses divided by attempts.",+ "ecpm": "Estimated eCPM generated, in USD.",+ "estimated_revenue": "Estimated revenue generated, in USD.",+ },+ },+ "max_ad_unit_revenue": {+ "description": "Estimated MAX mediation revenue and delivery per ad unit, without the network breakdown. This is the only grain at which AppLovin reports ad requests.",+ "docs_url": _MAX_REPORT_DOCS_URL,+ "columns": {+ **_APP_DIMENSIONS,+ "ad_format": "Ad unit ad type: INTER, BANNER or REWARD.",+ "max_ad_unit": "MAX Ad Unit name.",+ "max_ad_unit_id": "MAX Ad Unit ID.",+ "impressions": "Number of impressions shown.",+ "requests": "Number of ad requests made by the SDK.",+ "ecpm": "Estimated eCPM generated, in USD.",+ "estimated_revenue": "Estimated revenue generated, in USD.",+ },+ },+ "publisher_report": {+ "description": "Publisher-side AppLovin monetization: revenue, impressions and clicks earned by your apps, broken down by day, app, placement and geography.",+ "docs_url": _REPORT_DOCS_URL,+ "columns": {+ **_APP_DIMENSIONS,+ "ad_type": "Ad type served: APPOPEN, GRAPHIC, MRAID, PLAY, REWARD or VIDEO.",+ "placement_type": "Placement type: APP_OPEN, BANNER, INTER, LEADER, MREC, NATIVE or REWARDED_INTER.",+ "size": "Ad size: BANNER, INTER, LEADER, MREC or NATIVE.",+ "bidding_integration": "The mediation provider AppLovin bids through: MAX for MAX mediation, Google for AdMob Open Bidding or Google Ad Manager, None for non-bidding integrations.",+ "impressions": "Number of impressions.",+ "clicks": "Number of clicks.",+ "ctr": "Clicks divided by impressions.",+ "ecpm": "Money earned per 1000 impressions.",+ "revenue": "Money earned.",+ },+ },+ "advertiser_report": {+ "description": "Advertiser-side AppLovin campaign performance: spend, installs and attributed sales by day, campaign, traffic source app and geography.",+ "docs_url": _REPORT_DOCS_URL,+ "columns": {+ "day": _APP_DIMENSIONS["day"],+ "campaign": "Campaign name.",+ "campaign_id_external": "Unique reference to a campaign. Does not change when the campaign is renamed.",+ "campaign_type": "The campaign optimization type: CPP, CPE, ad ROAS, IAP ROAS or ROAS.",+ "campaign_ad_type": "ua for user acquisition, or rt for retargeting.",+ "campaign_package_name": "Package name or bundle ID of the promoted app.",+ "application": "Name of the source application the ad ran in.",+ "app_id_external": "Hashed application ID of the source app, commonly called the site ID.",+ "platform": "Platform of the source application: android, fireos, ios or tvos.",+ "country": _APP_DIMENSIONS["country"],+ "device_type": _APP_DIMENSIONS["device_type"],+ "ad_type": "Ad type served: APPOPEN, GRAPHIC, PLAY, REWARD or VIDEO.",+ "size": "Ad size: BANNER, INTER, LEADER, MREC, NATIVE or PRELOAD.",+ "cost": "Advertiser spend.",+ "impressions": "Number of impressions.",+ "clicks": "Number of clicks.",+ "ctr": "Clicks divided by impressions.",+ "conversions": "Number of conversions (installs).",+ "conversion_rate": "Conversions divided by impressions.",+ "average_cpa": "Average cost per conversion.",+ "average_cpc": "Average cost per click.",+ "sales": "Count of attributed sales events. Requires revenue postbacks.",+ },+ },+ "max_cohort_ad_revenue": {+ "description": "MAX cohort revenue: how much revenue users generate in the days after they install, keyed on the install day.",+ "docs_url": _COHORT_DOCS_URL,+ "columns": {+ **_COHORT_DIMENSION_DESCRIPTIONS,+ **_horizon_columns("pub_revenue", "Revenue generated in {days} days since the install."),+ **_horizon_columns("rpi", "Revenue per install generated in {days} days since the install."),+ **_horizon_columns("ads_pub_revenue", "Revenue generated from ads in {days} days since the install."),+ **_horizon_columns(+ "iap_pub_revenue", "Revenue generated from in-app purchases in {days} days since the install."+ ),+ },+ },+ "max_cohort_impressions": {+ "description": "MAX cohort ad impressions: how many impressions users see in the days after they install, keyed on the install day.",+ "docs_url": _COHORT_DOCS_URL,+ "columns": {+ **_COHORT_DIMENSION_DESCRIPTIONS,+ **_horizon_columns("imp", "Number of impressions from users {days} days after the install."),+ **_horizon_columns("imp_per_user", "Impressions per user {days} days after the install."),+ **_horizon_columns("user_count", "Number of users active {days} days after the install."),+ },+ },+ "max_cohort_sessions": {+ "description": "MAX cohort engagement: retention, session counts and time spent in the days after users install, keyed on the install day.",+ "docs_url": _COHORT_DOCS_URL,+ "columns": {+ **_COHORT_DIMENSION_DESCRIPTIONS,+ **_horizon_columns("user_count", "Number of users active {days} days after the install."),+ **_horizon_columns("retention", "Active users {days} days after the install divided by installs."),+ **_horizon_columns("session_count", "Total number of user sessions {days} days after the install."),+ **_horizon_columns("daily_usage", "Average time spent by users {days} days after the install, in seconds."),+ **_horizon_columns("session_length", "Daily usage divided by session count {days} days after the install."),+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/settings.pynew file mode 100644index 000000000000..adc763f9ff0a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/settings.py@@ -0,0 +1,222 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++APPLOVIN_API_BASE_URL = "https://r.applovin.com"++# Every reporting endpoint rejects dates outside a rolling 45-day window, so 45 days is the+# deepest history the API can serve — older data is not retrievable through the API at all.+MAX_REQUEST_WINDOW_DAYS = 45+# Report rows for recent days restate as attribution and cohort metrics settle, so incremental+# runs re-pull a trailing window and merge on the dimension tuple.+REPORT_LOOKBACK_DAYS = 7+# Request in bounded date chunks so a single response doesn't carry the whole window. Kept equal+# to the lookback so one window is always fully re-read after a mid-window failure.+REPORT_WINDOW_DAYS = 7+# `limit`/`offset` page size. AppLovin documents no maximum; 1000 is the value used in its own+# pagination example.+REPORT_PAGE_SIZE = 1000++# The cohort endpoints expose one metric per (metric, days-since-install) pair. AppLovin accepts+# 0, 1, 2, 3, 4, 5, 6, 7, 10, 14, 18, 21, 24, 27, 30 and 45; we request a useful subset because+# every extra horizon multiplies the column count.+COHORT_DAY_OFFSETS = (0, 1, 3, 7, 14, 30)++COHORT_DIMENSIONS = ["day", "application", "package_name", "platform", "country"]+COHORT_PRIMARY_KEYS = ["day", "package_name", "platform", "country"]+++def cohort_metrics(prefixes: tuple[str, ...]) -> list[str]:+ """Expand per-horizon cohort metric prefixes into concrete column names."""+ return [f"{prefix}_{offset}" for prefix in prefixes for offset in COHORT_DAY_OFFSETS]+++@dataclass+class AppLovinEndpointConfig:+ name: str+ # Path under `https://r.applovin.com`.+ path: str+ # Grouping columns. AppLovin has no fixed schema: the requested `columns` decide both the+ # grain of the aggregate and the shape of each row.+ dimensions: list[str]+ metrics: list[str]+ # Subset of `dimensions` that identifies a row. Excludes columns that are functionally+ # determined by another key column (an app's display name, a campaign's name) so a rename+ # upstream doesn't fork a row into two.+ primary_keys: list[str]+ extra_params: dict[str, str] = field(default_factory=dict)++ @property+ def columns(self) -> list[str]:+ return [*self.dimensions, *self.metrics]+++APPLOVIN_ENDPOINTS: dict[str, AppLovinEndpointConfig] = {+ # MAX mediation revenue at network grain. `requests` is unavailable whenever `network` or+ # `network_placement` is requested, which is why the ad-unit table below exists separately.+ "max_ad_revenue": AppLovinEndpointConfig(+ name="max_ad_revenue",+ path="/maxReport",+ dimensions=[+ "day",+ "application",+ "package_name",+ "store_id",+ "platform",+ "country",+ "device_type",+ "ad_format",+ "max_ad_unit",+ "max_ad_unit_id",+ "network",+ ],+ metrics=["impressions", "attempts", "responses", "fill_rate", "ecpm", "estimated_revenue"],+ primary_keys=[+ "day",+ "package_name",+ "platform",+ "country",+ "device_type",+ "ad_format",+ "max_ad_unit_id",+ "network",+ ],+ ),+ # Same report without the network dimension, which is the only way to get `requests`.+ "max_ad_unit_revenue": AppLovinEndpointConfig(+ name="max_ad_unit_revenue",+ path="/maxReport",+ dimensions=[+ "day",+ "application",+ "package_name",+ "store_id",+ "platform",+ "country",+ "device_type",+ "ad_format",+ "max_ad_unit",+ "max_ad_unit_id",+ ],+ metrics=["impressions", "requests", "ecpm", "estimated_revenue"],+ primary_keys=[+ "day",+ "package_name",+ "platform",+ "country",+ "device_type",+ "ad_format",+ "max_ad_unit_id",+ ],+ ),+ "publisher_report": AppLovinEndpointConfig(+ name="publisher_report",+ path="/report",+ dimensions=[+ "day",+ "application",+ "package_name",+ "store_id",+ "platform",+ "country",+ "device_type",+ "ad_type",+ "placement_type",+ "size",+ "bidding_integration",+ ],+ metrics=["impressions", "clicks", "ctr", "ecpm", "revenue"],+ primary_keys=[+ "day",+ "package_name",+ "platform",+ "country",+ "device_type",+ "ad_type",+ "placement_type",+ "size",+ "bidding_integration",+ ],+ extra_params={"report_type": "publisher"},+ ),+ "advertiser_report": AppLovinEndpointConfig(+ name="advertiser_report",+ path="/report",+ dimensions=[+ "day",+ "campaign",+ "campaign_id_external",+ "campaign_type",+ "campaign_ad_type",+ "campaign_package_name",+ "application",+ "app_id_external",+ "platform",+ "country",+ "device_type",+ "ad_type",+ "size",+ ],+ metrics=[+ "cost",+ "impressions",+ "clicks",+ "ctr",+ "conversions",+ "conversion_rate",+ "average_cpa",+ "average_cpc",+ "sales",+ ],+ primary_keys=[+ "day",+ "campaign_id_external",+ "app_id_external",+ "platform",+ "country",+ "device_type",+ "ad_type",+ "size",+ ],+ extra_params={"report_type": "advertiser"},+ ),+ "max_cohort_ad_revenue": AppLovinEndpointConfig(+ name="max_cohort_ad_revenue",+ path="/maxCohort",+ dimensions=list(COHORT_DIMENSIONS),+ metrics=[+ "installs",+ *cohort_metrics(("pub_revenue", "rpi", "ads_pub_revenue", "iap_pub_revenue")),+ ],+ primary_keys=list(COHORT_PRIMARY_KEYS),+ ),+ "max_cohort_impressions": AppLovinEndpointConfig(+ name="max_cohort_impressions",+ path="/maxCohort/imp",+ dimensions=list(COHORT_DIMENSIONS),+ metrics=["installs", *cohort_metrics(("imp", "imp_per_user", "user_count"))],+ primary_keys=list(COHORT_PRIMARY_KEYS),+ ),+ "max_cohort_sessions": AppLovinEndpointConfig(+ name="max_cohort_sessions",+ path="/maxCohort/session",+ dimensions=list(COHORT_DIMENSIONS),+ metrics=[+ "installs",+ *cohort_metrics(("user_count", "retention", "session_count", "daily_usage", "session_length")),+ ],+ primary_keys=list(COHORT_PRIMARY_KEYS),+ ),+}++ENDPOINTS = tuple(APPLOVIN_ENDPOINTS.keys())++# Every endpoint is a date-partitioned report filtered server-side by `start`/`end` on `day`.+DAY_INCREMENTAL_FIELD: IncrementalField = {+ "label": "day",+ "type": IncrementalFieldType.DateTime,+ "field": "day",+ "field_type": IncrementalFieldType.DateTime,+}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [DAY_INCREMENTAL_FIELD] for name in ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/source.pyindex 2a55e2789217..a5492454c900 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/source.py@@ -1,13 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.applovin import (+ AUTH_ERROR_PREFIX,+ BAD_REQUEST_ERROR_PREFIX,+ AppLovinResumeConfig,+ applovin_source,+ validate_credentials as validate_applovin_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import (+ APPLOVIN_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applovin import (AppLovinSourceConfig,)@@ -15,18 +39,101 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AppLovinSource(SimpleSource[AppLovinSourceConfig]):+class AppLovinSource(ResumableSource[AppLovinSourceConfig, AppLovinResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ # The reporting endpoints under r.applovin.com carry no version token of any kind.+ api_docs_url = "https://support.applovin.com/en/max/reporting-apis/revenue-reporting-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPLOVIN+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ AUTH_ERROR_PREFIX: "AppLovin rejected your Report Key. Generate a new one under your account menu > Keys in the AppLovin dashboard, then reconnect.",+ BAD_REQUEST_ERROR_PREFIX: "AppLovin rejected the report request. This usually means your account can't access the requested report.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.APP_LOVIN,category=DataWarehouseSourceCategory.ADVERTISING,label="AppLovin",+ caption="""Connect your AppLovin account to pull MAX mediation revenue, campaign spend, and cohort reporting into the PostHog Data warehouse.++Find your **Report Key** in the AppLovin dashboard: click your account in the top right, then **Keys**.++AppLovin only serves the last 45 days of report data, so anything older than that can't be backfilled.""",iconPath="/static/services/applovin.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/applovin",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["max", "appdiscovery", "axon", "mobile ads"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Report Key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: AppLovinSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Rows are aggregates that restate for a few days, so append would duplicate them.+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)+ for schema in schemas:+ schema.detected_primary_keys = list(APPLOVIN_ENDPOINTS[schema.name].primary_keys)+ return schemas++ def validate_credentials(+ self,+ config: AppLovinSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_applovin_credentials(config.api_key):+ return True, None++ return False, "Invalid AppLovin Report Key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppLovinResumeConfig]:+ return ResumableSourceManager[AppLovinResumeConfig](inputs, AppLovinResumeConfig)++ def source_for_pipeline(+ self,+ config: AppLovinSourceConfig,+ resumable_source_manager: ResumableSourceManager[AppLovinResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return applovin_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.pynew file mode 100644index 000000000000..c605f931e9c8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py@@ -0,0 +1,538 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, cast+from urllib.parse import parse_qs, quote, quote_plus, urlparse++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.applovin import (+ AUTH_ERROR_PREFIX,+ BAD_REQUEST_ERROR_PREFIX,+ TRANSIENT_ERROR_PREFIX,+ AppLovinAPIError,+ AppLovinResumeConfig,+ _body_code,+ _to_date,+ applovin_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import (+ APPLOVIN_ENDPOINTS,+ ENDPOINTS,+ MAX_REQUEST_WINDOW_DAYS,+ REPORT_LOOKBACK_DAYS,+ REPORT_PAGE_SIZE,+ REPORT_WINDOW_DAYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.applovin.applovin"+++class FakeResumeManager(ResumableSourceManager[AppLovinResumeConfig]):+ """In-memory stand-in for the Redis-backed manager."""++ def __init__(self, state: Optional[AppLovinResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[AppLovinResumeConfig] = []+ self.clear_count = 0++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AppLovinResumeConfig]:+ return self.state++ def save_state(self, data: AppLovinResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.clear_count += 1+++def _response(body: Any = None, status_code: int = 200, text: str = "", json_error: bool = False) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.text = text+ if json_error:+ resp.json.side_effect = ValueError("not json")+ else:+ resp.json.return_value = body+ return resp+++def _rows(count: int) -> list[dict[str, str]]:+ return [{"day": "2026-07-01", "package_name": f"com.app.{index}"} for index in range(count)]+++def _query(url: str) -> dict[str, list[str]]:+ return parse_qs(urlparse(url).query)+++def _urls(session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in session.return_value.get.call_args_list]+++def _today() -> date:+ return datetime.now(tz=UTC).date()+++def _earliest() -> date:+ return _today() - timedelta(days=MAX_REQUEST_WINDOW_DAYS - 1)+++class TestHelpers:+ @pytest.mark.parametrize(+ "value, expected_iso",+ [+ (datetime(2026, 7, 2, 3, 4, 5, tzinfo=UTC), "2026-07-02"),+ (date(2026, 7, 2), "2026-07-02"),+ ("2026-07-02", "2026-07-02"),+ ("2026-07-02T03:04:05Z", "2026-07-02"),+ ("junk", None),+ (None, None),+ (12345, None),+ ],+ )+ def test_to_date(self, value: Any, expected_iso: Optional[str]) -> None:+ result = _to_date(value)+ assert (result.isoformat() if result else None) == expected_iso++ @pytest.mark.parametrize(+ "body, expected",+ [+ ({"code": 200}, 200),+ ({"code": "200"}, 200),+ ({"code": 403}, 403),+ ({"results": []}, None),+ ({"code": None}, None),+ ({"code": "nope"}, None),+ ("Authentication Failed", None),+ ],+ )+ def test_body_code(self, body: Any, expected: Optional[int]) -> None:+ assert _body_code(body) == expected+++class TestRequestShape:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_report_key_is_registered_for_redaction(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})++ list(get_rows("secret-key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_every_endpoint_requests_its_declared_columns(self, mock_session: mock.MagicMock, endpoint: str) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})+ config = APPLOVIN_ENDPOINTS[endpoint]++ list(get_rows("key", endpoint, mock.MagicMock(), FakeResumeManager()))++ url = _urls(mock_session)[0]+ assert urlparse(url).path == config.path+ params = _query(url)+ assert params["columns"] == [",".join(config.columns)]+ assert params["format"] == ["json"]+ assert params["api_key"] == ["key"]+ assert params["limit"] == [str(REPORT_PAGE_SIZE)]+ assert params["offset"] == ["0"]+ # Pinned so limit/offset paging can't reshuffle rows and `sort_mode="asc"` holds.+ assert params["sort_day"] == ["ASC"]+ for name, value in config.extra_params.items():+ assert params[name] == [value]+++class TestWindowWalking:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_covers_the_whole_request_window_oldest_first(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": _rows(2)})+ manager = FakeResumeManager()++ batches = list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))++ starts = [_query(url)["start"][0] for url in _urls(mock_session)]+ ends = [_query(url)["end"][0] for url in _urls(mock_session)]+ assert starts == sorted(starts)+ assert starts[0] == _earliest().isoformat()+ assert ends[-1] == _today().isoformat()+ # Windows tile the range with no gaps.+ for previous_end, next_start in zip(ends, starts[1:]):+ assert date.fromisoformat(next_start) == date.fromisoformat(previous_end) + timedelta(days=1)+ assert len(batches) == len(starts)+ assert [saved.next_window_start for saved in manager.saved] == starts[1:]+ # A completed walk leaves no checkpoint behind.+ assert manager.clear_count == 1++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_checkpoint_survives_a_failed_walk(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = [+ _response({"code": 200, "results": _rows(2)}),+ _response(status_code=500, text="boom"),+ ]+ manager = FakeResumeManager()++ with pytest.raises(AppLovinAPIError):+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))++ assert manager.saved+ assert manager.clear_count == 0++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_starts_a_lookback_before_the_watermark(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})+ watermark = _today() - timedelta(days=3)++ list(+ get_rows(+ "key",+ "publisher_report",+ mock.MagicMock(),+ FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark.isoformat(),+ )+ )++ expected = (watermark - timedelta(days=REPORT_LOOKBACK_DAYS)).isoformat()+ assert _query(_urls(mock_session)[0])["start"] == [expected]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_watermark_older_than_the_request_window_is_clamped(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})++ list(+ get_rows(+ "key",+ "publisher_report",+ mock.MagicMock(),+ FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=(_today() - timedelta(days=400)).isoformat(),+ )+ )++ # AppLovin errors on dates outside the window, so the stale watermark must not be sent.+ assert _query(_urls(mock_session)[0])["start"] == [_earliest().isoformat()]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_unparseable_watermark_falls_back_to_full_window(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})++ list(+ get_rows(+ "key",+ "publisher_report",+ mock.MagicMock(),+ FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="not-a-date",+ )+ )++ assert _query(_urls(mock_session)[0])["start"] == [_earliest().isoformat()]+++class TestPagination:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_page_advances_offset_and_short_page_ends_the_window(self, mock_session: mock.MagicMock) -> None:+ first_window = [+ _response({"code": 200, "results": _rows(REPORT_PAGE_SIZE)}),+ _response({"code": 200, "results": _rows(REPORT_PAGE_SIZE)}),+ _response({"code": 200, "results": _rows(3)}),+ ]+ # Every later window returns a single short page.+ mock_session.return_value.get.side_effect = [+ *first_window,+ *[_response({"code": 200, "results": []}) for _ in range(50)],+ ]+ manager = FakeResumeManager()++ batches = list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))++ offsets = [_query(url)["offset"][0] for url in _urls(mock_session)[:4]]+ assert offsets == ["0", str(REPORT_PAGE_SIZE), str(REPORT_PAGE_SIZE * 2), "0"]+ # The empty later windows yield nothing, so only the three real pages come through.+ assert [len(batch) for batch in batches] == [REPORT_PAGE_SIZE, REPORT_PAGE_SIZE, 3]+ # Mid-window checkpoints carry the offset; the window rollover resets it.+ assert (manager.saved[0].next_window_start, manager.saved[0].next_offset) == (+ _earliest().isoformat(),+ REPORT_PAGE_SIZE,+ )+ assert manager.saved[2].next_offset == 0++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_window_and_offset(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})+ resume_start = _today() - timedelta(days=1)+ manager = FakeResumeManager(+ AppLovinResumeConfig(next_window_start=resume_start.isoformat(), next_offset=REPORT_PAGE_SIZE)+ )++ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))++ params = _query(_urls(mock_session)[0])+ assert params["start"] == [resume_start.isoformat()]+ assert params["offset"] == [str(REPORT_PAGE_SIZE)]+ # A single window remains, so nothing older gets re-walked.+ assert len(_urls(mock_session)) == 1++ @pytest.mark.parametrize(+ "resume_start_offset_days, description",+ [+ (400, "older than the request window"),+ (-5, "in the future"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_out_of_range_resume_state_is_ignored(+ self, mock_session: mock.MagicMock, resume_start_offset_days: int, description: str+ ) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})+ resume_start = _today() - timedelta(days=resume_start_offset_days)+ manager = FakeResumeManager(AppLovinResumeConfig(next_window_start=resume_start.isoformat()))++ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))++ assert _query(_urls(mock_session)[0])["start"] == [_earliest().isoformat()]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_state_behind_the_incremental_start_is_ignored(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})+ watermark = _today()+ expected_start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)+ manager = FakeResumeManager(+ AppLovinResumeConfig(next_window_start=(expected_start - timedelta(days=10)).isoformat())+ )++ list(+ get_rows(+ "key",+ "max_ad_revenue",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark.isoformat(),+ )+ )++ assert _query(_urls(mock_session)[0])["start"] == [expected_start.isoformat()]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_non_dict_results_are_dropped(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = [+ _response({"code": 200, "results": [{"day": "2026-07-01"}, "junk", None]}),+ *[_response({"code": 200, "results": None}) for _ in range(50)],+ ]++ batches = list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert batches == [[{"day": "2026-07-01"}]]+++class TestErrorClassification:+ @pytest.mark.parametrize("status_code", [401, 403])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_auth_statuses_raise_the_auth_prefix(self, mock_session: mock.MagicMock, status_code: int) -> None:+ mock_session.return_value.get.return_value = _response(status_code=status_code, text="Authentication Failed")++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert str(exc_info.value).startswith(AUTH_ERROR_PREFIX)++ @pytest.mark.parametrize("status_code", [400, 404, 422])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_other_client_errors_raise_the_bad_request_prefix(+ self, mock_session: mock.MagicMock, status_code: int+ ) -> None:+ mock_session.return_value.get.return_value = _response(status_code=status_code, text="Invalid column")++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert str(exc_info.value).startswith(BAD_REQUEST_ERROR_PREFIX)+ assert "Invalid column" in str(exc_info.value)++ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_throttling_and_upstream_failures_stay_retryable(+ self, mock_session: mock.MagicMock, status_code: int+ ) -> None:+ mock_session.return_value.get.return_value = _response(status_code=status_code, text="try later")++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ # Must not be classified as a permanent rejection, or an outage disables the source.+ assert str(exc_info.value).startswith(TRANSIENT_ERROR_PREFIX)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_non_json_body_on_a_200_is_a_bad_request(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response(text="<html>oops</html>", json_error=True)++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert str(exc_info.value).startswith(BAD_REQUEST_ERROR_PREFIX)++ @pytest.mark.parametrize(+ "body_code, expected_prefix",+ [+ (401, AUTH_ERROR_PREFIX),+ (403, AUTH_ERROR_PREFIX),+ (400, BAD_REQUEST_ERROR_PREFIX),+ (429, TRANSIENT_ERROR_PREFIX),+ (500, TRANSIENT_ERROR_PREFIX),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_body_level_error_code_on_a_200_is_classified(+ self, mock_session: mock.MagicMock, body_code: int, expected_prefix: str+ ) -> None:+ mock_session.return_value.get.return_value = _response({"code": body_code, "results": []})++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert str(exc_info.value).startswith(expected_prefix)++ # A Report Key with reserved characters is percent-/plus-encoded in the request URL, so a+ # transport error that quotes the URL never carries the raw key — redaction must cover the+ # encoded forms too.+ @pytest.mark.parametrize("api_key", ["super-secret", "ab/c+d=="])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_transport_error_never_leaks_the_report_key(self, mock_session: mock.MagicMock, api_key: str) -> None:+ # `requests`/`urllib3` quote the built URL, where the key is URL-encoded.+ leaked_url = f"/maxReport?api_key={quote_plus(api_key)}&columns=day"+ mock_session.return_value.get.side_effect = requests.ConnectionError(+ f"Max retries exceeded with url: {leaked_url}"+ )++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows(api_key, "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ message = str(exc_info.value)+ assert api_key not in message+ assert quote_plus(api_key) not in message+ assert quote(api_key, safe="") not in message+ assert "REDACTED" in message+ # The original exception carries the unredacted URL, so it must not be chained.+ assert exc_info.value.__cause__ is None++ @pytest.mark.parametrize("api_key", ["super-secret", "ab/c+d=="])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_error_body_echoing_the_report_key_is_redacted(self, mock_session: mock.MagicMock, api_key: str) -> None:+ mock_session.return_value.get.return_value = _response(+ status_code=400, text=f"bad request for api_key={api_key}"+ )++ with pytest.raises(AppLovinAPIError) as exc_info:+ list(get_rows(api_key, "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))++ assert api_key not in str(exc_info.value)+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_key_accepted_on_the_first_probe(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _response({"code": 200, "results": []})++ assert validate_credentials("key") is True+ assert len(_urls(mock_session)) == 1+ assert urlparse(_urls(mock_session)[0]).path == "/maxReport"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_advertiser_only_key_accepted_on_the_report_probe(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = [+ _response(status_code=403, text="Authentication Failed"),+ _response({"code": 200, "results": []}),+ ]++ assert validate_credentials("key") is True+ assert [urlparse(url).path for url in _urls(mock_session)] == ["/maxReport", "/report"]++ @pytest.mark.parametrize(+ "responses",+ [+ [_response(status_code=403, text="Authentication Failed")] * 2,+ [_response({"code": 403, "results": []})] * 2,+ [_response(text="Authentication Failed", json_error=True)] * 2,+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rejected_key_is_invalid(self, mock_session: mock.MagicMock, responses: list[mock.MagicMock]) -> None:+ mock_session.return_value.get.side_effect = responses++ assert validate_credentials("bad") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_transport_failure_is_not_validated_and_does_not_raise(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ assert validate_credentials("key") is False+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:+ response = applovin_source("key", endpoint, mock.MagicMock(), FakeResumeManager())++ assert response.name == endpoint+ assert response.primary_keys == APPLOVIN_ENDPOINTS[endpoint].primary_keys+ assert response.sort_mode == "asc"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_items_yields_rows_as_returned_by_the_api(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = [+ _response({"code": 200, "results": [{"day": "2026-07-01", "estimated_revenue": "1.23"}]}),+ *[_response({"code": 200, "results": []}) for _ in range(50)],+ ]+ response = applovin_source("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager())++ batches = list(cast("Iterable[Any]", response.items()))++ assert batches == [[{"day": "2026-07-01", "estimated_revenue": "1.23"}]]+++class TestEndpointCatalogInvariants:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_primary_keys_are_requested_dimensions(self, endpoint: str) -> None:+ config = APPLOVIN_ENDPOINTS[endpoint]+ # A key column absent from `columns` would never appear in a row, so every merge+ # would multi-match and duplicate.+ assert set(config.primary_keys) <= set(config.dimensions)+ assert config.primary_keys++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_day_is_always_requested_and_keyed(self, endpoint: str) -> None:+ config = APPLOVIN_ENDPOINTS[endpoint]+ assert "day" in config.dimensions+ assert "day" in config.primary_keys++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_columns_have_no_duplicates(self, endpoint: str) -> None:+ columns = APPLOVIN_ENDPOINTS[endpoint].columns+ assert len(columns) == len(set(columns))++ @pytest.mark.parametrize("endpoint", ["max_ad_revenue", "max_ad_unit_revenue"])+ def test_max_report_network_and_request_metrics_are_mutually_exclusive(self, endpoint: str) -> None:+ config = APPLOVIN_ENDPOINTS[endpoint]+ # AppLovin refuses `requests` whenever `network`/`network_placement` is requested, and+ # only reports `attempts`/`responses`/`fill_rate` when one of them is.+ network_grain = "network" in config.dimensions+ assert ("requests" in config.metrics) is not network_grain+ for metric in ("attempts", "responses", "fill_rate"):+ assert (metric in config.metrics) is network_grain++ def test_lookback_covers_a_whole_window(self) -> None:+ # A mid-window crash is only self-healing when the next run re-reads the full window.+ assert REPORT_LOOKBACK_DAYS >= REPORT_WINDOW_DAYS+ assert REPORT_WINDOW_DAYS < MAX_REQUEST_WINDOW_DAYSdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.pynew file mode 100644index 000000000000..a68a232690b9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py@@ -0,0 +1,193 @@+from typing import Optional++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.applovin import (+ AUTH_ERROR_PREFIX,+ BAD_REQUEST_ERROR_PREFIX,+ TRANSIENT_ERROR_PREFIX,+ AppLovinResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import (+ APPLOVIN_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.source import AppLovinSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applovin import (+ AppLovinSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.applovin.source"+++class TestAppLovinSource:+ def setup_method(self) -> None:+ self.source = AppLovinSource()+ self.team_id = 123+ self.config = AppLovinSourceConfig(api_key="report-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.APPLOVIN++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "AppLovin"+ assert config.label == "AppLovin"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/applovin.png"+ assert [field.name for field in config.fields] == ["api_key"]++ def test_report_key_field_is_a_secret_password(self) -> None:+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"+ )++ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_lists_tables_without_credentials(self) -> None:+ # `get_schemas` is a static catalog, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ assert self.source.api_docs_url is not None+ assert self.source.api_docs_url.startswith("https://")++ def test_get_schemas(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name, schema in schemas.items():+ # Every endpoint filters server-side on `day` via start/end.+ assert schema.supports_incremental is True+ assert schema.incremental_fields == INCREMENTAL_FIELDS[name]+ # Aggregate rows restate for a few days, so append would duplicate them.+ assert schema.supports_append is False+ assert schema.detected_primary_keys == APPLOVIN_ENDPOINTS[name].primary_keys++ @pytest.mark.parametrize(+ "names, expected",+ [+ (["max_ad_revenue"], ["max_ad_revenue"]),+ (["max_cohort_sessions", "publisher_report"], ["publisher_report", "max_cohort_sessions"]),+ (["nope"], []),+ ],+ )+ def test_get_schemas_filtered_by_names(self, names: list[str], expected: list[str]) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)++ assert sorted(schema.name for schema in schemas) == sorted(expected)++ @pytest.mark.parametrize(+ "probe_result, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid AppLovin Report Key"),+ ],+ )+ @mock.patch(f"{_SOURCE_MODULE}.validate_applovin_credentials")+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ probe_result: bool,+ expected_valid: bool,+ expected_message: Optional[str],+ ) -> None:+ mock_validate.return_value = probe_result++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("report-key")++ @pytest.mark.parametrize(+ "observed_error",+ [+ f"{AUTH_ERROR_PREFIX}: status=403, endpoint=/maxReport",+ f"{BAD_REQUEST_ERROR_PREFIX}: status=400, endpoint=/report, body=Invalid column",+ f"{AUTH_ERROR_PREFIX}: body code=401, endpoint=/maxCohort",+ ],+ )+ def test_non_retryable_errors_match_the_raised_messages(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ "AppLovin request failed: HTTPSConnectionPool(host='r.applovin.com', port=443): timed out",+ f"{TRANSIENT_ERROR_PREFIX}: status=503, endpoint=/maxReport",+ f"{TRANSIENT_ERROR_PREFIX}: status=429, endpoint=/report",+ "500 Server Error for url: https://r.applovin.com/maxReport",+ ],+ )+ def test_transient_errors_stay_retryable(self, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AppLovinResumeConfig++ @mock.patch(f"{_SOURCE_MODULE}.applovin_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_applovin_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "max_ad_revenue"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_applovin_source.call_args.kwargs+ assert kwargs["api_key"] == "report-key"+ assert kwargs["endpoint"] == "max_ad_revenue"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01"++ @mock.patch(f"{_SOURCE_MODULE}.applovin_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_applovin_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "publisher_report"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-07-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_applovin_source.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestAppLovinCanonicalDescriptions:+ def setup_method(self) -> None:+ self.source = AppLovinSource()++ def test_every_endpoint_is_documented(self) -> None:+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_documented_columns_are_columns_the_source_requests(self, endpoint: str) -> None:+ # A typo here would ship a description for a column that never lands in the table.+ documented = set(CANONICAL_DESCRIPTIONS[endpoint].get("columns", {}))+ assert documented <= set(APPLOVIN_ENDPOINTS[endpoint].columns)+ assert documented == set(APPLOVIN_ENDPOINTS[endpoint].columns)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_each_entry_has_a_description_and_docs_url(self, endpoint: str) -> None:+ entry = CANONICAL_DESCRIPTIONS[endpoint]++ assert entry["description"]+ assert str(entry["docs_url"]).startswith("https://")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applovin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applovin.pyindex d30ae6d32abf..2cf74108b513 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applovin.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applovin.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AppLovinSourceConfig(config.Config):- pass+ api_key: str