Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement adjust source (#73760)

Tom Owers1552cf4a594b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 5816a3735c03..bc7ae10879f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -49,6 +49,7 @@ the row lists both.
| Source | Comm method | Primary library | Tracked transport |
| -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
| ably | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| adjust | HTTP | requests | ✅ |
| adobe_analytics | HTTP | requests | ✅ |
| adobe_commerce | HTTP | requests | ✅ |
| adroll | HTTP | requests | ✅ |
@@ -708,8 +709,6 @@ doesn't conflict with concurrent PRs.
- active_campaign
- acuity_scheduling
- adapty
-- adjust
-- adobe_analytics
- adobe_commerce
- adp_workforce_now
- aftership
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py
new file mode 100644
index 000000000000..7222ba6643f6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py
@@ -0,0 +1,358 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+from urllib.parse import urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.settings import ADJUST_REPORTS
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+ADJUST_API_HOST = "automate.adjust.com"
+BASE_URL = f"https://{ADJUST_API_HOST}/reports-service"
+REPORT_URL = f"{BASE_URL}/report"
+
+# Reports are pulled one date window at a time so a long backfill streams instead of asking Adjust
+# for years of rows in a single response. The window is also the resume unit.
+WINDOW_DAYS = 30
+# First sync backfill depth. Adjust does not retain report data indefinitely, so anything older
+# than this is unlikely to be available anyway.
+MAX_HISTORY_DAYS = 730
+# Adjust keeps revising recent days (late attributions, re-attributions), so an incremental run
+# re-reads a trailing window; merge dedupes on the dimension key.
+LOOKBACK_DAYS = 3
+REQUEST_TIMEOUT_SECONDS = 300
+# The Report Service API documents a `pagination` field but not its mechanism, so the page loop is
+# driven purely by a next link when one is present. The cap stops a malformed/looping link from
+# scanning forever.
+MAX_PAGES_PER_WINDOW = 200
+# Adjust app tokens are short alphanumeric identifiers; reject anything else before it reaches a
+# query string.
+_APP_TOKEN_RE = re.compile(r"[A-Za-z0-9]+")
+
+
+class AdjustRetryableError(Exception):
+ """Transient upstream failure (429 / 5xx) that survived the tracked session's own retries."""
+
+ pass
+
+
+class AdjustCredentialsError(Exception):
+ """A credential check failed for a reason we can explain to the user (bad token, bad app token)."""
+
+ pass
+
+
+class AdjustResumeConfig:
+ # ISO date (YYYY-MM-DD) of the next date window to request. Lets a multi-window backfill pick up
+ # where it stopped after a heartbeat timeout instead of re-walking the whole history.
+ next_start_date: str | None = None
+
+
+def _today() -> date:
+ return datetime.now(UTC).date()
+
+
+def _get_session(api_token: str) -> requests.Session:
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
+ redact_values=(api_token,),
+ # The Bearer token rides in every request's default headers, so pin the session off
+ # redirects — an upstream redirect must not carry the credential to another host.
+ allow_redirects=False,
+ )
+
+
+def parse_app_tokens(app_tokens: str | None) -> list[str]:
+ """Split the optional comma-separated app token filter, rejecting anything malformed.
+
+ Raises ``AdjustCredentialsError`` rather than silently dropping a bad entry — a typo'd token
+ would otherwise quietly narrow (or widen) the report to the wrong set of apps.
+ """
+ if not app_tokens:
+ return []
+ tokens = [token.strip() for token in app_tokens.split(",")]
+ tokens = [token for token in tokens if token]
+ for token in tokens:
+ if not _APP_TOKEN_RE.fullmatch(token):
+ raise AdjustCredentialsError(
+ f"'{token}' does not look like an Adjust app token. App tokens are the short "
+ "alphanumeric identifiers shown under your app's settings in the Adjust dashboard."
+ )
+ return tokens
+
+
+def build_report_params(
+ report: str,
+ start: date,
+ end: date,
+ app_tokens: list[str],
+) -> dict[str, str]:
+ config = ADJUST_REPORTS[report]
+ params = {
+ "dimensions": ",".join(config.dimensions),
+ "metrics": ",".join(config.metrics),
+ "date_period": f"{start.isoformat()}:{end.isoformat()}",
+ # Ascending by day so the rows arrive in the order `sort_mode="asc"` promises and the
+ # incremental watermark only ever moves forward.
+ "sort": "day",
+ }
+ if app_tokens:
+ params["app_token__in"] = ",".join(app_tokens)
+ return params
+
+
+def _error_message(response: requests.Response) -> str:
+ """Best-effort human-readable detail from an Adjust error body."""
+ try:
+ body = response.json()
+ except ValueError:
+ return ""
+ if not isinstance(body, dict):
+ return ""
+ error = body.get("error")
+ if isinstance(error, dict):
+ detail = error.get("message") or error.get("detail")
+ else:
+ detail = error
+ detail = detail or body.get("message") or body.get("detail")
+ return f" — {detail}" if isinstance(detail, str) and detail else ""
+
+
+def _request(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AdjustRetryableError(f"Adjust API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Adjust API error: status={response.status_code}, body={response.text[:500]}, url={url}")
+ # The API token rides in the Authorization header, so the URL is safe to embed — it lets
+ # `get_non_retryable_errors()` match on the stable host prefix.
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {url}{_error_message(response)}",
+ response=response,
+ )
+
+ body = response.json()
+ if not isinstance(body, dict):
+ raise ValueError(f"Adjust returned an unexpected report payload of type {type(body).__name__}")
+ return body
+
+
+def extract_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """Pull the report rows out of a Report Service response.
+
+ Adjust returns them under `rows`; tolerate a `data` list too, since the CSV/pivot variants of
+ the same endpoint have historically wrapped rows differently.
+ """
+ for key in ("rows", "data"):
+ rows = payload.get(key)
+ if isinstance(rows, list):
+ return [row for row in rows if isinstance(row, dict)]
+ return []
+
+
+def next_page_url(payload: dict[str, Any]) -> str | None:
+ """Return the absolute next-page URL, if the response advertises one.
+
+ The `pagination` field is present but undocumented, so only an explicit link is followed —
+ anything else terminates the page loop rather than guessing an offset scheme. The link is
+ pinned to HTTPS on the Adjust API host: `_request` fetches it with the session whose default
+ headers carry the customer's Bearer token, so a tampered upstream `next` must not be able to
+ point the credentialed request at an attacker-controlled or internal host.
+ """
+ pagination = payload.get("pagination")
+ if not isinstance(pagination, dict):
+ return None
+ candidate = pagination.get("next") or pagination.get("next_url")
+ if not isinstance(candidate, str) or not candidate:
+ return None
+ try:
+ parts = urlsplit(candidate)
+ except ValueError:
+ return None
+ if parts.scheme != "https" or parts.hostname != ADJUST_API_HOST:
+ return None
+ return candidate
+
+
+def _to_date(value: Any) -> date | None:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return (value if value.tzinfo else value.replace(tzinfo=UTC)).astimezone(UTC).date()
+ if isinstance(value, date):
+ return value
+ try:
+ return datetime.fromisoformat(str(value)[:19].replace("Z", "")).date()
+ except ValueError:
+ try:
+ return date.fromisoformat(str(value)[:10])
+ except ValueError:
+ return None
+
+
+def resolve_start_date(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ today: date,
+) -> date:
+ earliest = today - timedelta(days=MAX_HISTORY_DAYS)
+ if should_use_incremental_field:
+ watermark = _to_date(db_incremental_field_last_value)
+ if watermark is not None:
+ return min(max(watermark - timedelta(days=LOOKBACK_DAYS), earliest), today)
+ return earliest
+
+
+def date_windows(start: date, end: date, window_days: int = WINDOW_DAYS) -> list[tuple[date, date]]:
+ """Split [start, end] into consecutive inclusive windows of at most `window_days` days."""
+ if start > end:
+ return []
+ windows: list[tuple[date, date]] = []
+ cursor = start
+ while cursor <= end:
+ window_end = min(cursor + timedelta(days=window_days - 1), end)
+ windows.append((cursor, window_end))
+ cursor = window_end + timedelta(days=1)
+ return windows
+
+
+def validate_credentials(api_token: str, app_tokens: str | None = None) -> bool:
+ """Confirm the API token (and any app token filter) works with a one-day report probe.
+
+ Returns ``True`` on success. Raises ``AdjustCredentialsError`` with a user-facing message when
+ Adjust rejects the token, the app tokens, or the request, ``AdjustRetryableError`` on
+ rate-limit / 5xx responses, and lets transport errors propagate so a transient failure isn't
+ mislabelled as a bad credential. Never returns ``False``.
+ """
+ tokens = parse_app_tokens(app_tokens)
+ today = _today()
+ params = {
+ "dimensions": "day",
+ "metrics": "installs",
+ "date_period": f"{today.isoformat()}:{today.isoformat()}",
+ }
+ if tokens:
+ params["app_token__in"] = ",".join(tokens)
+
+ response = _get_session(api_token).get(f"{REPORT_URL}?{urlencode(params)}", timeout=30)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AdjustRetryableError(f"Adjust API error (retryable): status={response.status_code}")
+ if response.status_code == 200:
+ return True
+ if response.status_code == 401:
+ raise AdjustCredentialsError(
+ "Adjust rejected the API token. Check that you pasted a valid Adjust API token from "
+ "your account settings in the Adjust dashboard."
+ )
+ if response.status_code == 403:
+ raise AdjustCredentialsError(
+ "Adjust denied access. Check that your user has reporting access to the apps you want "
+ "to import and that your account includes the Report Service API."
+ )
+ if response.status_code in (400, 404, 422):
+ raise AdjustCredentialsError(
+ f"Adjust rejected the report request (HTTP {response.status_code})"
+ f"{_error_message(response)}. If you set app tokens, check they belong to this account."
+ )
+ raise AdjustCredentialsError(
+ f"Adjust returned an unexpected response (HTTP {response.status_code}) while validating "
+ "credentials. If your API token looks correct, please try again shortly."
+ )
+
+
+def get_rows(
+ api_token: str,
+ app_tokens: str | None,
+ report: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AdjustResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ if report not in ADJUST_REPORTS:
+ raise ValueError(f"Unknown Adjust report: {report}")
+
+ tokens = parse_app_tokens(app_tokens)
+ session = _get_session(api_token)
+ today = _today()
+ start = resolve_start_date(should_use_incremental_field, db_incremental_field_last_value, today)
+ windows = date_windows(start, today)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_start_date:
+ windows = [window for window in windows if window[0].isoformat() >= resume.next_start_date]
+ logger.debug(f"Adjust: resuming {report} from {resume.next_start_date}")
+
+ # The tracked session already retries 429 + transient 5xx honoring `Retry-After`, so there is
+ # deliberately no second retry layer here — anything that reaches us has already been retried,
+ # and the Temporal activity retries the job.
+ for index, (window_start, window_end) in enumerate(windows):
+ url = f"{REPORT_URL}?{urlencode(build_report_params(report, window_start, window_end, tokens))}"
+ for page in range(MAX_PAGES_PER_WINDOW):
+ payload = _request(session, url, logger)
+ rows = extract_rows(payload)
+ if rows:
+ yield rows
+
+ next_url = next_page_url(payload)
+ if next_url is None:
+ break
+ if page + 1 == MAX_PAGES_PER_WINDOW:
+ logger.warning(
+ "Adjust page cap reached; truncating window",
+ report=report,
+ date_period=f"{window_start.isoformat()}:{window_end.isoformat()}",
+ pages=MAX_PAGES_PER_WINDOW,
+ )
+ break
+ url = next_url
+
+ # Save AFTER yielding the window so a crash re-yields it rather than skipping it (merge
+ # dedupes on the dimension key).
+ if index + 1 < len(windows):
+ resumable_source_manager.save_state(AdjustResumeConfig(next_start_date=windows[index + 1][0].isoformat()))
+
+
+def adjust_source(
+ api_token: str,
+ app_tokens: str | None,
+ report: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AdjustResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ config = ADJUST_REPORTS[report]
+
+ return SourceResponse(
+ name=report,
+ items=lambda: get_rows(
+ api_token=api_token,
+ app_tokens=app_tokens,
+ report=report,
+ 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=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["day"],
+ sort_mode="asc",
+ # Aggregated dimension keys can collide when a dimension value comes back blank
+ # (e.g. organic traffic with no campaign).
+ has_duplicate_primary_keys=True,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/canonical_descriptions.py
new file mode 100644
index 000000000000..2e4a356dfc8f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/canonical_descriptions.py
@@ -0,0 +1,101 @@
+"""Canonical, documentation-sourced descriptions for the Adjust Report Service API reports.
+
+Sourced from the official Adjust Report Service API reference
+(https://dev.adjust.com/en/api/rs-api/), including its dimensions and metrics glossaries.
+Keyed by the report names in `settings.py` `ADJUST_REPORTS`, which match the
+`ExternalDataSchema.name` of a synced Adjust table. Column names are the dimension and metric
+names Adjust returns verbatim; columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://dev.adjust.com/en/api/rs-api/"
+
+# Dimensions and metrics requested on every report.
+_BASE_COLUMNS = {
+ "day": "Calendar day (UTC) the aggregated metrics are reported for.",
+ "app": "Name of the app in the Adjust dashboard.",
+ "app_token": "Adjust app token identifying the app the metrics belong to.",
+ "impressions": "Ad impressions recorded by the network in the period.",
+ "clicks": "Ad clicks recorded by the network in the period.",
+ "installs": "App installs attributed in the period.",
+ "sessions": "App sessions recorded in the period.",
+ "reattributions": "Reattributed users (previously installed users re-engaged by a campaign) in the period.",
+ "click_conversion_rate": "Installs divided by clicks.",
+ "impression_conversion_rate": "Installs divided by impressions.",
+ "cost": "Ad spend in the period, from the connected ad-spend integrations.",
+ "ecpi": "Effective cost per install (cost divided by installs).",
+ "revenue": "Revenue attributed in the period, from tracked revenue events.",
+}
+
+_USER_COLUMNS = {
+ "daus": "Daily active users.",
+ "waus": "Weekly active users.",
+ "maus": "Monthly active users.",
+}
+
+_PARTNER_COLUMN = {"partner_name": "Name of the attribution partner (ad network) the activity is attributed to."}
+
+
+def _columns(*extra: dict[str, str]) -> dict[str, str]:
+ merged = dict(_BASE_COLUMNS)
+ for block in extra:
+ merged.update(block)
+ return merged
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "daily_report": {
+ "description": "Daily aggregated performance per app — installs, sessions, clicks, impressions, cost, revenue, and active users.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(_USER_COLUMNS),
+ },
+ "partner_report": {
+ "description": "Daily aggregated performance per app broken down by attribution partner (ad network).",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(_PARTNER_COLUMN),
+ },
+ "campaign_report": {
+ "description": "Daily aggregated performance per campaign, broken down by attribution partner.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ _PARTNER_COLUMN,
+ {
+ "campaign": "Campaign name as recorded by Adjust.",
+ "campaign_id_network": "Campaign identifier as reported by the ad network.",
+ },
+ ),
+ },
+ "creative_report": {
+ "description": "Daily aggregated performance per creative, broken down by ad group, campaign, and attribution partner.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ _PARTNER_COLUMN,
+ {
+ "campaign": "Campaign name as recorded by Adjust.",
+ "adgroup": "Ad group name within the campaign.",
+ "creative": "Creative name within the ad group.",
+ },
+ ),
+ },
+ "country_report": {
+ "description": "Daily aggregated performance per app broken down by country.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ {
+ "country": "Country name the metrics are reported for.",
+ "country_code": "ISO country code the metrics are reported for.",
+ }
+ ),
+ },
+ "os_report": {
+ "description": "Daily aggregated performance per app broken down by operating system.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ _USER_COLUMNS,
+ {"os_name": "Operating system of the device (for example ios or android)."},
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py
new file mode 100644
index 000000000000..40d7aceab947
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Every report is grouped by `day`, which is the only stable cursor the Report Service API
+# exposes (it filters server-side via `date_period`).
+_DAY_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "day",
+ "type": IncrementalFieldType.Date,
+ "field": "day",
+ "field_type": IncrementalFieldType.Date,
+ },
+]
+
+# Delivery + engagement metrics available on every Adjust account. Cost and revenue metrics
+# return 0 until the account has ad-spend / revenue integrations configured, which is a
+# reporting setup concern rather than a request error.
+_CORE_METRICS = [
+ "impressions",
+ "clicks",
+ "installs",
+ "sessions",
+ "reattributions",
+ "click_conversion_rate",
+ "impression_conversion_rate",
+ "cost",
+ "ecpi",
+ "revenue",
+]
+
+# Active-user metrics only make sense at app grain — they are not additive across campaign,
+# creative, or country breakdowns, so they stay on the app-level reports.
+_USER_METRICS = ["daus", "waus", "maus"]
+
+
+@dataclass
+class AdjustReportConfig:
+ name: str
+ # `dimensions` / `metrics` are sent verbatim as the Report Service API's comma-separated
+ # `dimensions` and `metrics` params, and they define the report's column set.
+ dimensions: list[str]
+ metrics: list[str] = field(default_factory=lambda: list(_CORE_METRICS))
+ # Aggregated reports have no row ids — the requested dimensions are the natural key. Blank
+ # dimension values (e.g. an unattributed campaign) can collide, so rows are merged with
+ # `has_duplicate_primary_keys=True`.
+ primary_keys: list[str] = field(default_factory=lambda: ["day", "app_token"])
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DAY_INCREMENTAL_FIELDS))
+ description: str | None = None
+
+
+# One entry per report shape we expose. Adjust's Report Service API is a single endpoint whose
+# response schema is defined entirely by the requested dimensions and metrics, so each "table"
+# here is a fixed dimension/metric selection rather than a distinct URL.
+ADJUST_REPORTS: dict[str, AdjustReportConfig] = {
+ "daily_report": AdjustReportConfig(
+ name="daily_report",
+ dimensions=["day", "app", "app_token"],
+ metrics=[*_CORE_METRICS, *_USER_METRICS],
+ description="Daily performance per app — installs, sessions, clicks, impressions, cost, revenue, and active users.",
+ ),
+ "partner_report": AdjustReportConfig(
+ name="partner_report",
+ dimensions=["day", "app", "app_token", "partner_name"],
+ primary_keys=["day", "app_token", "partner_name"],
+ description="Daily performance per app broken down by attribution partner (network).",
+ ),
+ "campaign_report": AdjustReportConfig(
+ name="campaign_report",
+ dimensions=["day", "app", "app_token", "partner_name", "campaign", "campaign_id_network"],
+ primary_keys=["day", "app_token", "partner_name", "campaign", "campaign_id_network"],
+ description="Daily performance per campaign, broken down by attribution partner.",
+ ),
+ "creative_report": AdjustReportConfig(
+ name="creative_report",
+ dimensions=["day", "app", "app_token", "partner_name", "campaign", "adgroup", "creative"],
+ primary_keys=["day", "app_token", "partner_name", "campaign", "adgroup", "creative"],
+ description="Daily performance per creative, broken down by ad group, campaign, and attribution partner.",
+ ),
+ "country_report": AdjustReportConfig(
+ name="country_report",
+ dimensions=["day", "app", "app_token", "country", "country_code"],
+ primary_keys=["day", "app_token", "country_code"],
+ description="Daily performance per app broken down by country.",
+ ),
+ "os_report": AdjustReportConfig(
+ name="os_report",
+ dimensions=["day", "app", "app_token", "os_name"],
+ metrics=[*_CORE_METRICS, *_USER_METRICS],
+ primary_keys=["day", "app_token", "os_name"],
+ description="Daily performance per app broken down by operating system.",
+ ),
+}
+
+ENDPOINTS = tuple(ADJUST_REPORTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ADJUST_REPORTS.items() if config.incremental_fields
+}
+
+DESCRIPTIONS: dict[str, str] = {
+ name: config.description for name, config in ADJUST_REPORTS.items() if config.description
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/source.py
index e1e4da44ee82..01e311833f5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/source.py
@@ -1,30 +1,160 @@
-from typing import cast
+from typing import Optional, cast
+
+import requests
from 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.adjust.adjust import (
+ AdjustCredentialsError,
+ AdjustResumeConfig,
+ AdjustRetryableError,
+ adjust_source,
+ validate_credentials as validate_adjust_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.settings import (
+ DESCRIPTIONS,
+ 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, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adjust import AdjustSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AdjustSource(SimpleSource[AdjustSourceConfig]):
+class AdjustSource(ResumableSource[AdjustSourceConfig, AdjustResumeConfig]):
+ # The Report Service API carries no version token in its path, headers, or params, so there is
+ # no vendor version to pin.
+ api_docs_url = "https://dev.adjust.com/en/api/rs-api/"
+
+ lists_tables_without_credentials = True # static report catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ADJUST
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://automate.adjust.com": "Adjust rejected your API token. Generate a new token in the Adjust dashboard and reconnect.",
+ "403 Client Error: Forbidden for url: https://automate.adjust.com": "Adjust denied access. Check that your user has reporting access to these apps and that your account includes the Report Service API.",
+ # A 400 means the report request itself is invalid (unknown dimension or metric, or an
+ # app token that isn't in this account). The request shape is fixed per table, so
+ # retrying it identically can never succeed.
+ "400 Client Error: Bad Request for url: https://automate.adjust.com": "Adjust rejected the report request. Check that the app tokens belong to this account and that your account has access to the requested metrics.",
+ "404 Client Error: Not Found for url: https://automate.adjust.com": "Adjust could not find the requested report data. Check the app tokens on this source.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ADJUST,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Adjust",
+ caption="""Enter your Adjust API token to pull aggregated attribution and performance reports into the PostHog Data warehouse.
+
+Find your API token in the Adjust dashboard under your account menu > Account settings. The token needs reporting access to the apps you want to import. Leave app tokens blank to import every app the token can read, or enter a comma-separated list to narrow it down.
+
+Adjust's Report Service API returns metrics aggregated per day, so these tables are daily time series rather than user-level events. Raw user-level data needs server callbacks or a cloud storage upload, which can't be set up through the API.""",
iconPath="/static/services/adjust.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/adjust",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["mobile attribution", "mmp"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="app_tokens",
+ label="App tokens (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="abc123def456,ghi789jkl012",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AdjustSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AdjustSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ try:
+ # validate_credentials returns True or raises — it never returns False — so an
+ # unexpected status surfaces its real cause instead of a conflated credential error.
+ validate_adjust_credentials(config.api_token, config.app_tokens)
+ return True, None
+ except AdjustCredentialsError as e:
+ return False, str(e)
+ except (AdjustRetryableError, requests.RequestException):
+ # A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.
+ return (
+ False,
+ "Could not reach Adjust to validate credentials. This may be a temporary rate-limit or network issue — please try again.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AdjustResumeConfig]:
+ return ResumableSourceManager[AdjustResumeConfig](inputs, AdjustResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AdjustSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AdjustResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return adjust_source(
+ api_token=config.api_token,
+ app_tokens=config.app_tokens,
+ report=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/adjust/tests/test_adjust.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
new file mode 100644
index 000000000000..f8e3f967c744
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
@@ -0,0 +1,517 @@
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust import adjust
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.adjust import (
+ LOOKBACK_DAYS,
+ MAX_HISTORY_DAYS,
+ MAX_PAGES_PER_WINDOW,
+ REPORT_URL,
+ AdjustCredentialsError,
+ AdjustResumeConfig,
+ AdjustRetryableError,
+ adjust_source,
+ build_report_params,
+ date_windows,
+ extract_rows,
+ get_rows,
+ next_page_url,
+ parse_app_tokens,
+ resolve_start_date,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.settings import ADJUST_REPORTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+TODAY = date(2024, 6, 30)
+
+
+class _FakeResponse:
+ def __init__(
+ self, status_code: int = 200, json_data: Any = None, text: str = "", reason: str = "Bad Request"
+ ) -> None:
+ self.status_code = status_code
+ self._json_data = json_data
+ self.text = text
+ self.reason = reason
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> Any:
+ if isinstance(self._json_data, Exception):
+ raise self._json_data
+ return self._json_data
+
+
+class _FakeSession:
+ """Returns queued responses in order and records every URL requested."""
+
+ def __init__(self, responses: list[_FakeResponse]) -> None:
+ self._responses = list(responses)
+ self.requested_urls: list[str] = []
+
+ def get(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.requested_urls.append(url)
+ return self._responses.pop(0)
+
+
+class _FakeResumeManager(ResumableSourceManager[AdjustResumeConfig]):
+ def __init__(self, state: AdjustResumeConfig | None = None) -> None:
+ self.state = state
+ self.saved: list[AdjustResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> AdjustResumeConfig | None:
+ return self.state
+
+ def save_state(self, data: AdjustResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _params(url: str) -> dict[str, str]:
+ return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}
+
+
+def _page(rows: list[dict[str, Any]], next_url: str | None = None) -> _FakeResponse:
+ pagination = {"next": next_url} if next_url else None
+ return _FakeResponse(json_data={"rows": rows, "totals": {}, "pagination": pagination})
+
+
+def _run_get_rows(
+ session: _FakeSession,
+ report: str = "daily_report",
+ manager: _FakeResumeManager | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ app_tokens: str | None = None,
+) -> list[list[dict[str, Any]]]:
+ resume_manager = manager if manager is not None else _FakeResumeManager()
+ with (
+ mock.patch.object(adjust, "make_tracked_session", return_value=session),
+ mock.patch.object(adjust, "_today", return_value=TODAY),
+ ):
+ return list(
+ get_rows(
+ api_token="token",
+ app_tokens=app_tokens,
+ report=report,
+ logger=mock.MagicMock(),
+ resumable_source_manager=resume_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+
+
+class TestParseAppTokens:
+ @parameterized.expand(
+ [
+ ("blank", None, []),
+ ("empty_string", "", []),
+ ("single", "abc123", ["abc123"]),
+ ("whitespace_and_trailing_comma", " abc123 , def456 ,", ["abc123", "def456"]),
+ ]
+ )
+ def test_parses(self, _name: str, raw: str | None, expected: list[str]) -> None:
+ assert parse_app_tokens(raw) == expected
+
+ @parameterized.expand([("space", "abc 123"), ("query_injection", "abc&metrics=cost"), ("path", "abc/def")])
+ def test_rejects_malformed_tokens(self, _name: str, raw: str) -> None:
+ # A malformed token must fail loudly rather than silently narrowing the report or leaking
+ # extra query params into the request.
+ with pytest.raises(AdjustCredentialsError):
+ parse_app_tokens(raw)
+
+
+class TestBuildReportParams:
+ def test_sends_report_dimensions_metrics_and_date_period(self) -> None:
+ params = build_report_params("campaign_report", date(2024, 1, 1), date(2024, 1, 31), [])
+ config = ADJUST_REPORTS["campaign_report"]
+
+ assert params["dimensions"] == ",".join(config.dimensions)
+ assert params["metrics"] == ",".join(config.metrics)
+ assert params["date_period"] == "2024-01-01:2024-01-31"
+ # sort_mode="asc" only holds if we ask Adjust for ascending days.
+ assert params["sort"] == "day"
+ assert "app_token__in" not in params
+
+ def test_app_token_filter_included_when_configured(self) -> None:
+ params = build_report_params("daily_report", date(2024, 1, 1), date(2024, 1, 2), ["abc123", "def456"])
+ assert params["app_token__in"] == "abc123,def456"
+
+ @parameterized.expand([(name,) for name in ADJUST_REPORTS])
+ def test_every_report_groups_by_day(self, name: str) -> None:
+ # `day` is the incremental cursor and partition key, so every report must return it.
+ assert "day" in ADJUST_REPORTS[name].dimensions
+ assert "day" in build_report_params(name, date(2024, 1, 1), date(2024, 1, 2), [])["dimensions"]
+
+ @parameterized.expand([(name,) for name in ADJUST_REPORTS])
+ def test_primary_keys_are_requested_dimensions(self, name: str) -> None:
+ # A primary key that isn't a requested dimension would be absent from every row, so merges
+ # would collapse the whole table onto null keys.
+ config = ADJUST_REPORTS[name]
+ assert set(config.primary_keys) <= set(config.dimensions)
+
+
+class TestRequest:
+ @parameterized.expand([(429,), (500,), (502,), (503,)])
+ def test_throttle_and_5xx_are_retryable(self, status: int) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status)])
+ with pytest.raises(AdjustRetryableError):
+ adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+
+ @parameterized.expand([(400,), (401,), (403,), (404,), (422,)])
+ def test_client_errors_raise_http_error_with_url(self, status: int) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status, text="nope")])
+ with pytest.raises(requests.HTTPError) as exc:
+ adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ # get_non_retryable_errors matches on the status text plus the host, so both must be present.
+ assert str(status) in str(exc.value)
+ assert "https://automate.adjust.com" in str(exc.value)
+
+ @parameterized.expand(
+ [
+ ("nested_error", {"error": {"message": "Unknown metric: bogus"}}, "Unknown metric: bogus"),
+ ("flat_error", {"error": "Invalid app_token"}, "Invalid app_token"),
+ ("message_key", {"message": "Access denied"}, "Access denied"),
+ ]
+ )
+ def test_error_body_detail_is_surfaced(self, _name: str, body: dict[str, Any], expected: str) -> None:
+ session = _FakeSession([_FakeResponse(status_code=400, json_data=body)])
+ with pytest.raises(requests.HTTPError) as exc:
+ adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ assert expected in str(exc.value)
+
+ def test_non_json_error_body_does_not_break_error_construction(self) -> None:
+ session = _FakeSession([_FakeResponse(status_code=400, json_data=ValueError("no json"), text="<html>")])
+ with pytest.raises(requests.HTTPError):
+ adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+
+ def test_success_returns_parsed_body(self) -> None:
+ body = {"rows": [{"day": "2024-01-01"}]}
+ session = _FakeSession([_FakeResponse(json_data=body)])
+ assert adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock()) == body
+
+ def test_non_dict_payload_raises(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data=[{"day": "2024-01-01"}])])
+ with pytest.raises(ValueError):
+ adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+
+
+class TestExtractRows:
+ @parameterized.expand(
+ [
+ ("rows_key", {"rows": [{"day": "2024-01-01"}]}, 1),
+ ("data_key", {"data": [{"day": "2024-01-01"}]}, 1),
+ ("empty_rows", {"rows": []}, 0),
+ ("missing", {"totals": {}}, 0),
+ ("rows_not_a_list", {"rows": {"day": "2024-01-01"}}, 0),
+ ]
+ )
+ def test_extracts(self, _name: str, payload: dict[str, Any], expected: int) -> None:
+ assert len(extract_rows(payload)) == expected
+
+ def test_non_dict_entries_are_dropped(self) -> None:
+ assert extract_rows({"rows": [{"day": "2024-01-01"}, "junk", None]}) == [{"day": "2024-01-01"}]
+
+
+class TestNextPageUrl:
+ @parameterized.expand(
+ [
+ ("absolute_next", {"pagination": {"next": "https://automate.adjust.com/x?page=2"}}, True),
+ ("next_url_alias", {"pagination": {"next_url": "https://automate.adjust.com/x?page=2"}}, True),
+ ("null_pagination", {"pagination": None}, False),
+ ("missing_pagination", {}, False),
+ ("empty_next", {"pagination": {"next": ""}}, False),
+ # The mechanism is undocumented, so anything that isn't a link on the Adjust API host
+ # terminates the loop instead of being guessed at.
+ ("relative_next", {"pagination": {"next": "/report?page=2"}}, False),
+ ("numeric_next", {"pagination": {"next": 2}}, False),
+ # The credentialed session follows this URL, so an off-host or non-HTTPS link — which
+ # could exfiltrate the Bearer token or hit an internal host — is rejected.
+ ("off_host_next", {"pagination": {"next": "https://evil.example.com/x?page=2"}}, False),
+ ("subdomain_spoof_next", {"pagination": {"next": "https://automate.adjust.com.evil.com/x"}}, False),
+ ("http_scheme_next", {"pagination": {"next": "http://automate.adjust.com/x?page=2"}}, False),
+ ]
+ )
+ def test_only_adjust_host_links_are_followed(self, _name: str, payload: dict[str, Any], expected: bool) -> None:
+ assert (next_page_url(payload) is not None) is expected
+
+
+class TestDateHelpers:
+ @parameterized.expand(
+ [
+ ("date", date(2024, 1, 5), date(2024, 1, 5)),
+ ("naive_datetime", datetime(2024, 1, 5, 23, 0), date(2024, 1, 5)),
+ ("aware_datetime", datetime(2024, 1, 5, 23, 0, tzinfo=UTC), date(2024, 1, 5)),
+ ("iso_date_string", "2024-01-05", date(2024, 1, 5)),
+ ("iso_datetime_string", "2024-01-05T12:34:56Z", date(2024, 1, 5)),
+ ("garbage", "not-a-date", None),
+ ("none", None, None),
+ ]
+ )
+ def test_to_date(self, _name: str, value: Any, expected: date | None) -> None:
+ assert adjust._to_date(value) == expected
+
+ @parameterized.expand(
+ [
+ ("exact_multiple", date(2024, 1, 1), date(2024, 1, 20), 10, [(1, 10), (11, 20)]),
+ ("partial_last_window", date(2024, 1, 1), date(2024, 1, 15), 10, [(1, 10), (11, 15)]),
+ ("single_day", date(2024, 1, 1), date(2024, 1, 1), 10, [(1, 1)]),
+ ]
+ )
+ def test_date_windows(
+ self, _name: str, start: date, end: date, window: int, expected: list[tuple[int, int]]
+ ) -> None:
+ assert date_windows(start, end, window) == [(date(2024, 1, a), date(2024, 1, b)) for a, b in expected]
+
+ def test_date_windows_empty_when_start_after_end(self) -> None:
+ assert date_windows(date(2024, 2, 1), date(2024, 1, 1)) == []
+
+ def test_date_windows_are_contiguous_and_cover_the_range(self) -> None:
+ windows = date_windows(date(2024, 1, 1), date(2024, 4, 15), 30)
+ assert windows[0][0] == date(2024, 1, 1)
+ assert windows[-1][1] == date(2024, 4, 15)
+ for earlier, later in zip(windows, windows[1:]):
+ assert (later[0] - earlier[1]).days == 1
+
+
+class TestResolveStartDate:
+ def test_full_refresh_starts_at_the_history_cap(self) -> None:
+ assert resolve_start_date(False, None, TODAY) == TODAY - adjust.timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_incremental_rewinds_the_watermark_by_the_lookback(self) -> None:
+ # Adjust restates recent days, so an incremental run must re-read a trailing window.
+ assert resolve_start_date(True, "2024-06-20", TODAY) == date(2024, 6, 20) - adjust.timedelta(days=LOOKBACK_DAYS)
+
+ def test_incremental_without_watermark_falls_back_to_full_history(self) -> None:
+ assert resolve_start_date(True, None, TODAY) == TODAY - adjust.timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_unparseable_watermark_falls_back_to_full_history(self) -> None:
+ assert resolve_start_date(True, "not-a-date", TODAY) == TODAY - adjust.timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_watermark_older_than_the_history_cap_is_clamped(self) -> None:
+ assert resolve_start_date(True, "2010-01-01", TODAY) == TODAY - adjust.timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_future_watermark_is_clamped_to_today(self) -> None:
+ # A watermark ahead of today would otherwise produce an inverted date_period.
+ assert resolve_start_date(True, "2030-01-01", TODAY) == TODAY
+
+
+class TestGetRows:
+ def test_unknown_report_raises(self) -> None:
+ with pytest.raises(ValueError):
+ _run_get_rows(_FakeSession([]), report="nope")
+
+ def test_incremental_window_requests_only_the_watermark_range(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-06-28"}])])
+ batches = _run_get_rows(
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-06-28",
+ )
+
+ assert batches == [[{"day": "2024-06-28"}]]
+ assert len(session.requested_urls) == 1
+ assert _params(session.requested_urls[0])["date_period"] == "2024-06-25:2024-06-30"
+
+ def test_app_token_filter_is_sent(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-06-30"}])])
+ _run_get_rows(
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-06-30",
+ app_tokens="abc123",
+ )
+ assert _params(session.requested_urls[0])["app_token__in"] == "abc123"
+
+ def test_empty_page_yields_no_batch(self) -> None:
+ session = _FakeSession([_page([])])
+ assert (
+ _run_get_rows(session, should_use_incremental_field=True, db_incremental_field_last_value="2024-06-30")
+ == []
+ )
+
+ def test_pagination_follows_next_link_then_terminates(self) -> None:
+ next_url = "https://automate.adjust.com/reports-service/report?page=2"
+ session = _FakeSession(
+ [
+ _page([{"day": "2024-06-29"}], next_url=next_url),
+ _page([{"day": "2024-06-30"}]),
+ ]
+ )
+ batches = _run_get_rows(
+ session, should_use_incremental_field=True, db_incremental_field_last_value="2024-06-30"
+ )
+
+ assert batches == [[{"day": "2024-06-29"}], [{"day": "2024-06-30"}]]
+ assert session.requested_urls[1] == next_url
+
+ def test_pagination_stops_at_the_page_cap(self) -> None:
+ # A next link that never clears would otherwise loop forever.
+ looping = "https://automate.adjust.com/reports-service/report?page=next"
+ session = _FakeSession([_page([{"day": "2024-06-30"}], next_url=looping)] * (MAX_PAGES_PER_WINDOW + 5))
+ batches = _run_get_rows(
+ session, should_use_incremental_field=True, db_incremental_field_last_value="2024-06-30"
+ )
+ assert len(batches) == MAX_PAGES_PER_WINDOW
+
+ def test_multiple_windows_are_walked_in_ascending_order(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-05-05"}]) for _ in range(3)])
+ _run_get_rows(session, should_use_incremental_field=True, db_incremental_field_last_value="2024-05-01")
+
+ periods = [_params(url)["date_period"] for url in session.requested_urls]
+ assert periods == ["2024-04-28:2024-05-27", "2024-05-28:2024-06-26", "2024-06-27:2024-06-30"]
+
+ def test_state_is_saved_after_each_window_except_the_last(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-05-05"}]) for _ in range(3)])
+ manager = _FakeResumeManager()
+ _run_get_rows(
+ session,
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-05-01",
+ )
+ # Saving only between windows means a crash re-yields the window in flight instead of
+ # skipping it, and a completed walk leaves no checkpoint mid-stream.
+ assert [state.next_start_date for state in manager.saved] == ["2024-05-28", "2024-06-27"]
+
+ def test_resume_skips_windows_already_completed(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-06-05"}]) for _ in range(2)])
+ manager = _FakeResumeManager(AdjustResumeConfig(next_start_date="2024-05-28"))
+ _run_get_rows(
+ session,
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-05-01",
+ )
+
+ assert [_params(url)["date_period"] for url in session.requested_urls] == [
+ "2024-05-28:2024-06-26",
+ "2024-06-27:2024-06-30",
+ ]
+
+ def test_exhausted_throttle_surfaces_as_retryable_without_a_second_retry_layer(self) -> None:
+ # The tracked session owns 429/5xx retries. Anything that reaches get_rows has already been
+ # retried, so it must propagate for Temporal to retry the job rather than being re-looped
+ # here (which would multiply the request count against Adjust's rate limit).
+ session = _FakeSession([_FakeResponse(status_code=429), _page([{"day": "2024-06-30"}])])
+ with pytest.raises(AdjustRetryableError):
+ _run_get_rows(session, should_use_incremental_field=True, db_incremental_field_last_value="2024-06-30")
+ assert len(session.requested_urls) == 1
+
+
+class TestValidateCredentials:
+ def _validate(self, response: _FakeResponse, app_tokens: str | None = None) -> bool:
+ session = _FakeSession([response])
+ with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ return validate_credentials("token", app_tokens)
+
+ def test_success(self) -> None:
+ assert self._validate(_FakeResponse(json_data={"rows": []})) is True
+
+ def test_probe_is_minimal_and_includes_app_token_filter(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"rows": []})])
+ with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ validate_credentials("token", "abc123")
+
+ params = _params(session.requested_urls[0])
+ assert params["dimensions"] == "day"
+ assert params["metrics"] == "installs"
+ assert params["app_token__in"] == "abc123"
+
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_throttle_and_5xx_are_retryable(self, status: int) -> None:
+ with pytest.raises(AdjustRetryableError):
+ self._validate(_FakeResponse(status_code=status))
+
+ @parameterized.expand([(401, "API token"), (403, "denied access"), (400, "app tokens"), (404, "app tokens")])
+ def test_rejections_are_credential_errors_with_specific_messages(self, status: int, expected: str) -> None:
+ with pytest.raises(AdjustCredentialsError) as exc:
+ self._validate(_FakeResponse(status_code=status))
+ assert expected in str(exc.value)
+
+ def test_unexpected_status_does_not_blame_the_token(self) -> None:
+ with pytest.raises(AdjustCredentialsError) as exc:
+ self._validate(_FakeResponse(status_code=418))
+ assert "unexpected response (HTTP 418)" in str(exc.value)
+
+ def test_malformed_app_token_fails_before_any_request(self) -> None:
+ session = _FakeSession([])
+ with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ with pytest.raises(AdjustCredentialsError):
+ validate_credentials("token", "abc 123")
+ assert session.requested_urls == []
+
+ def test_transport_errors_propagate(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ with pytest.raises(requests.ConnectionError):
+ validate_credentials("token")
+
+
+class TestAdjustSource:
+ @parameterized.expand([(name,) for name in ADJUST_REPORTS])
+ def test_source_response_shape(self, name: str) -> None:
+ response = adjust_source(
+ api_token="token",
+ app_tokens=None,
+ report=name,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+
+ assert response.name == name
+ assert response.primary_keys == ADJUST_REPORTS[name].primary_keys
+ # Windows are walked oldest-first and each report is sorted by day, so rows arrive ascending.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["day"]
+ # Blank dimension values (e.g. organic traffic with no campaign) can collide.
+ assert response.has_duplicate_primary_keys is True
+
+ def test_items_is_lazy(self) -> None:
+ # Building the SourceResponse must not issue a request; the pipeline drives iteration.
+ session = _FakeSession([])
+ with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ response = adjust_source(
+ api_token="token",
+ app_tokens=None,
+ report="daily_report",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+ assert session.requested_urls == []
+ assert callable(response.items)
+
+ def test_items_streams_rows(self) -> None:
+ session = _FakeSession([_page([{"day": "2024-06-30", "installs": "3"}])])
+ with (
+ mock.patch.object(adjust, "make_tracked_session", return_value=session),
+ mock.patch.object(adjust, "_today", return_value=TODAY),
+ ):
+ response = adjust_source(
+ api_token="token",
+ app_tokens=None,
+ report="daily_report",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-06-30",
+ )
+ batches = list(cast(Iterable[Any], response.items()))
+
+ assert batches == [[{"day": "2024-06-30", "installs": "3"}]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py
new file mode 100644
index 000000000000..99d4bb58b086
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py
@@ -0,0 +1,189 @@
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.adjust import (
+ AdjustCredentialsError,
+ AdjustResumeConfig,
+ AdjustRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.settings import ADJUST_REPORTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.source import AdjustSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adjust import AdjustSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adjust.source"
+
+
+class TestAdjustSource:
+ def setup_method(self) -> None:
+ self.source = AdjustSource()
+ self.team_id = 123
+ self.config = AdjustSourceConfig(api_token="adjust-token", app_tokens="abc123")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ADJUST
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Adjust"
+ assert config.label == "Adjust"
+ assert config.category == DataWarehouseSourceCategory.ADVERTISING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/adjust"
+ assert [field.name for field in config.fields] == ["api_token", "app_tokens"]
+
+ def test_source_is_released(self) -> None:
+ # A truthy unreleasedSource hides the connector from users entirely.
+ assert not self.source.get_source_config.unreleasedSource
+
+ def test_api_token_field_is_a_secret_password(self) -> None:
+ field = next(f for f in self.source.get_source_config.fields if f.name == "api_token")
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_app_tokens_field_is_optional_and_not_secret(self) -> None:
+ field = next(f for f in self.source.get_source_config.fields if f.name == "app_tokens")
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.required is False
+ assert field.secret is False
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas iterates a static report catalog with no I/O — safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_api_docs_url_is_https(self) -> None:
+ assert self.source.api_docs_url is not None
+ assert self.source.api_docs_url.startswith("https://")
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://automate.adjust.com/reports-service/report?dimensions=day",
+ "403 Client Error: Forbidden for url: https://automate.adjust.com/reports-service/report",
+ "400 Client Error: Bad Request for url: https://automate.adjust.com/reports-service/report — Unknown metric",
+ "404 Client Error: Not Found for url: https://automate.adjust.com/reports-service/report",
+ ],
+ )
+ def test_permanent_failures_are_non_retryable(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",
+ [
+ "429 Client Error: Too Many Requests for url: https://automate.adjust.com/reports-service/report",
+ "Adjust API error (retryable): status=503, url=https://automate.adjust.com/reports-service/report",
+ ],
+ )
+ def test_throttles_and_5xx_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_schemas_covers_every_report(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_every_report_is_incremental_on_day(self) -> None:
+ # date_period is a real server-side filter, so every report can sync incrementally on day.
+ for schema in self.source.get_schemas(self.config, self.team_id):
+ assert schema.supports_incremental is True
+ assert [field["field"] for field in schema.incremental_fields] == ["day"]
+
+ def test_get_schemas_carries_descriptions(self) -> None:
+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert all(schema.description for schema in by_name.values())
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["country_report"])
+ assert [schema.name for schema in schemas] == ["country_report"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
+ def test_validate_credentials_success(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = True
+
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("adjust-token", "abc123")
+
+ @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
+ def test_validate_credentials_surfaces_the_specific_rejection(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.side_effect = AdjustCredentialsError("Adjust rejected the API token.")
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert message == "Adjust rejected the API token."
+
+ @pytest.mark.parametrize(
+ "raised",
+ [AdjustRetryableError("status=503"), requests.ConnectionError("boom"), requests.ReadTimeout("slow")],
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
+ def test_transient_failures_are_not_reported_as_bad_credentials(
+ self, mock_validate: mock.MagicMock, raised: Exception
+ ) -> None:
+ mock_validate.side_effect = raised
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert message is not None
+ assert "temporary rate-limit or network issue" in message
+
+ def test_get_resumable_source_manager_binds_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AdjustResumeConfig
+
+ @mock.patch(f"{_SOURCE_MODULE}.adjust_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "campaign_report"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-06-01"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "adjust-token"
+ assert kwargs["app_tokens"] == "abc123"
+ assert kwargs["report"] == "campaign_report"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01"
+
+ @mock.patch(f"{_SOURCE_MODULE}.adjust_source")
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "daily_report"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-06-01"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ # A full refresh must not inherit a stale watermark and silently skip history.
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_every_report(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("report", sorted(ADJUST_REPORTS))
+ def test_canonical_descriptions_document_the_primary_key_columns(self, report: str) -> None:
+ # The key columns are what a user joins on, so they must not fall through to LLM guessing.
+ columns = self.source.get_canonical_descriptions()[report]["columns"]
+ assert set(ADJUST_REPORTS[report].primary_keys) <= set(columns)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adjust.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adjust.py
index c7b0487bccd1..333736e2bdd6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adjust.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adjust.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AdjustSourceConfig(config.Config):
- pass
+ api_token: str
+ app_tokens: str | None = None