:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add adjust retention, skad and event tables (#116125)
Tom Owersfd11338ea974
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 51d10920ee85..be55b6fc78e9 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -214,7 +214,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/active_campaign.py1 products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py1 products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/adroll/adroll.pydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 08dda1f1d43f..dd66d236aad1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -143,14 +143,14 @@ Note: deal_groups/deal_stages already cover the pipelines and stages lookups. Th## Adjust — gaps-Today (6): `campaign_report`, `country_report`, `creative_report`, `daily_report`, `os_report`, `partner_report`+Today (10): `campaign_report`, `country_report`, `creative_report`, `daily_report`, `event_report`, `events`, `os_report`, `partner_report`, `retention_report`, `skad_report`Diffed against: <https://dev.adjust.com/en/api/rs-api/reports/>-- [ ] `Cohort retention reports (GET /reports-service/report, retention metrics)` — measure retention after install and compare acquisition cohorts beyond daily active users (high)-- [ ] `Event reports (GET /reports-service/report, event metrics)` — measure purchases and other app conversions by acquisition source instead of only installs and sessions (high)-- [ ] `SKAdNetwork reports (GET /reports-service/report, SKAdNetwork metrics)` — analyze iOS campaign attribution through SKAdNetwork installs and conversion values (high)-- [ ] `Events catalog (GET /reports-service/events)` — map readable event names and app tokens to the metric slugs needed for conversion reports (medium)+- [x] `Cohort retention reports (GET /reports-service/report, retention metrics)` — measure retention after install and compare acquisition cohorts beyond daily active users (high)+- [x] `Event reports (GET /reports-service/report, event metrics)` — measure purchases and other app conversions by acquisition source instead of only installs and sessions (high)+- [x] `SKAdNetwork reports (GET /reports-service/report, SKAdNetwork metrics)` — analyze iOS campaign attribution through SKAdNetwork installs and conversion values (high)+- [x] `Events catalog (GET /reports-service/events)` — map readable event names and app tokens to the metric slugs needed for conversion reports (medium)- [ ] `Device type reports (GET /reports-service/report, dimensions=day,app,app_token,device_type)` — compare acquisition cost, engagement, and revenue across device types (medium)Note: Read the official Report Service operations, event catalog, and filter catalog. All six tables use one endpoint with fixed metrics and dimensions. Missing reports need new query shapes; event metrics require discovery through GET /reports-service/events. Excluded CSV, Parquet, and pivot duplicates, plus write and test APIs.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.pyindex 1f467becb7fa..07b7fc174444 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/adjust.py@@ -8,7 +8,11 @@ from urllib.parse import urlencode, urlsplitimport requestsfrom 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.adjust.settings import (+ ADJUST_REPORTS,+ DEFAULT_LOOKBACK_DAYS,+ EVENTS_CATALOG,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -16,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typADJUST_API_HOST = "automate.adjust.com"BASE_URL = f"https://{ADJUST_API_HOST}/reports-service"REPORT_URL = f"{BASE_URL}/report"+EVENTS_URL = f"{BASE_URL}/events"# 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.@@ -23,14 +28,14 @@ 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 = 3REQUEST_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+# Event reports request one metric per event slug; batching keeps the query string short for+# accounts with large event catalogs.+MAX_EVENT_METRICS_PER_REQUEST = 50# 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]+")@@ -93,11 +98,12 @@ def build_report_params(start: date,end: date,app_tokens: list[str],+ metrics: list[str] | None = None,) -> dict[str, str]:config = ADJUST_REPORTS[report]params = {"dimensions": ",".join(config.dimensions),- "metrics": ",".join(config.metrics),+ "metrics": ",".join(config.metrics if metrics is None else 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.@@ -125,7 +131,7 @@ def _error_message(response: requests.Response) -> str:return f" — {detail}" if isinstance(detail, str) and detail else ""-def _request(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+def _get_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)if response.status_code == 429 or response.status_code >= 500:@@ -140,12 +146,76 @@ def _request(session: requests.Session, url: str, logger: FilteringBoundLogger)response=response,)- body = response.json()+ if response.status_code == 204:+ return None+ return response.json()+++def _request(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ body = _get_json(session, url, logger)+ if body is None:+ return {}if not isinstance(body, dict):raise ValueError(f"Adjust returned an unexpected report payload of type {type(body).__name__}")return body+def fetch_events(+ session: requests.Session, app_tokens: list[str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ params = {"tokens_mapping": "true"}+ if app_tokens:+ params["app_token__in"] = ",".join(app_tokens)+ body = _get_json(session, f"{EVENTS_URL}?{urlencode(params)}", logger)+ if body is None:+ return []+ if not isinstance(body, list):+ raise ValueError(f"Adjust returned an unexpected events payload of type {type(body).__name__}")+ return [event for event in body if isinstance(event, dict)]+++def report_event_names(events: list[dict[str, Any]]) -> dict[str, str | None]:+ """Map each event slug that can be requested as a `{slug}_events` metric to its readable name.++ SKAdNetwork events are reported through the SKAN conversion metrics, not as event counts.+ """+ names: dict[str, str | None] = {}+ for event in events:+ slug = event.get("id")+ if isinstance(slug, str) and slug and not event.get("is_skad_event"):+ name = event.get("name")+ names[slug] = name if isinstance(name, str) else None+ return names+++def _is_zero(value: Any) -> bool:+ try:+ return float(value) == 0+ except (TypeError, ValueError):+ return False+++def unpivot_event_rows(+ rows: list[dict[str, Any]],+ dimensions: list[str],+ event_names: dict[str, str | None],+) -> list[dict[str, Any]]:+ """Turn one column per event into one row per (dimensions, event).++ Zero counts are dropped: Adjust returns a value for every requested event on every row, and+ most events don't fire for most partners on most days.+ """+ unpivoted: list[dict[str, Any]] = []+ for row in rows:+ base = {dimension: row.get(dimension) for dimension in dimensions}+ for slug, name in event_names.items():+ value = row.get(f"{slug}_events")+ if value is None or _is_zero(value):+ continue+ unpivoted.append({**base, "event_slug": slug, "event_name": name, "events": value})+ return unpivoted++def extract_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:"""Pull the report rows out of a Report Service response.@@ -203,12 +273,13 @@ def resolve_start_date(should_use_incremental_field: bool,db_incremental_field_last_value: Any,today: date,+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,) -> 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 min(max(watermark - timedelta(days=lookback_days), earliest), today)return earliest@@ -270,6 +341,41 @@ def validate_credentials(api_token: str, app_tokens: str | None = None) -> bool:)+def _iter_report_pages(+ session: requests.Session,+ params: dict[str, str],+ report: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{REPORT_URL}?{urlencode(params)}"+ for page in range(MAX_PAGES_PER_WINDOW):+ payload = _request(session, url, logger)+ yield extract_rows(payload)++ next_url = next_page_url(payload)+ if next_url is None:+ return+ if page + 1 == MAX_PAGES_PER_WINDOW:+ logger.warning(+ "Adjust page cap reached; truncating window",+ report=report,+ date_period=params["date_period"],+ pages=MAX_PAGES_PER_WINDOW,+ )+ return+ url = next_url+++def get_event_catalog(+ api_token: str,+ app_tokens: str | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ events = fetch_events(_get_session(api_token), parse_app_tokens(app_tokens), logger)+ if events:+ yield events++def get_rows(api_token: str,app_tokens: str | None,@@ -282,10 +388,27 @@ def get_rows(if report not in ADJUST_REPORTS:raise ValueError(f"Unknown Adjust report: {report}")+ config = ADJUST_REPORTS[report]tokens = parse_app_tokens(app_tokens)session = _get_session(api_token)++ event_names: dict[str, str | None] = {}+ metric_batches = [config.metrics]+ if config.event_metrics:+ event_names = report_event_names(fetch_events(session, tokens, logger))+ slugs = list(event_names)+ metric_batches = [+ [f"{slug}_events" for slug in slugs[i : i + MAX_EVENT_METRICS_PER_REQUEST]]+ for i in range(0, len(slugs), MAX_EVENT_METRICS_PER_REQUEST)+ ]+ if not metric_batches:+ logger.info("Adjust: no events in the events catalog, skipping event report", report=report)+ return+today = _today()- start = resolve_start_date(should_use_incremental_field, db_incremental_field_last_value, today)+ start = resolve_start_date(+ should_use_incremental_field, db_incremental_field_last_value, today, config.lookback_days+ )windows = date_windows(start, today)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None@@ -297,25 +420,22 @@ def get_rows(# 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+ if config.event_metrics:+ # Each metric batch walks the whole window by day, so the batches are merged and+ # re-sorted to keep rows ascending across the window, as `sort_mode="asc"` promises.+ window_rows: list[dict[str, Any]] = []+ for metrics in metric_batches:+ params = build_report_params(report, window_start, window_end, tokens, metrics)+ for rows in _iter_report_pages(session, params, report, logger):+ window_rows.extend(unpivot_event_rows(rows, config.dimensions, event_names))+ if window_rows:+ window_rows.sort(key=lambda row: str(row.get("day") or ""))+ yield window_rows+ else:+ params = build_report_params(report, window_start, window_end, tokens)+ for rows in _iter_report_pages(session, params, report, logger):+ if rows:+ yield rows# Save AFTER yielding the window so a crash re-yields it rather than skipping it (merge# dedupes on the dimension key).@@ -332,6 +452,13 @@ def adjust_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> SourceResponse:+ if report == EVENTS_CATALOG:+ return SourceResponse(+ name=report,+ items=lambda: get_event_catalog(api_token=api_token, app_tokens=app_tokens, logger=logger),+ primary_keys=["id"],+ )+config = ADJUST_REPORTS[report]return SourceResponse(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.pyindex 2e4a356dfc8f..6bdb3e276acd 100644--- 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@@ -2,7 +2,7 @@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+Keyed by the report names in `settings.py` `ADJUST_REPORTS` (plus the events catalog), which match the`ExternalDataSchema.name` of a synced Adjust table. Column names are the dimension and metricnames Adjust returns verbatim; columns absent here fall back to LLM enrichment."""@@ -98,4 +98,72 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {{"os_name": "Operating system of the device (for example ios or android)."},),},+ "retention_report": {+ "description": "Day 1, 7, and 30 retention per daily install cohort, broken down by attribution partner.",+ "docs_url": _DOCS_URL,+ "columns": {+ "day": "Calendar day (UTC) of the install cohort.",+ "app": _BASE_COLUMNS["app"],+ "app_token": _BASE_COLUMNS["app_token"],+ **_PARTNER_COLUMN,+ "installs": _BASE_COLUMNS["installs"],+ **{+ f"cohort_size_{cohort}": f"Users who installed or were reattributed on the day and kept the app installed for the {cohort} cohort period."+ for cohort in ("d1", "d7", "d30")+ },+ **{+ f"retained_users_{cohort}": f"Users from the cohort who were still active in the {cohort} cohort period."+ for cohort in ("d1", "d7", "d30")+ },+ **{+ f"retention_rate_{cohort}": f"Retained users divided by cohort size for the {cohort} cohort period."+ for cohort in ("d1", "d7", "d30")+ },+ },+ },+ "skad_report": {+ "description": "Daily SKAdNetwork (iOS) installs, reinstalls, and conversion value counts per network campaign.",+ "docs_url": _DOCS_URL,+ "columns": {+ "day": _BASE_COLUMNS["day"],+ "app": _BASE_COLUMNS["app"],+ "app_token": _BASE_COLUMNS["app_token"],+ **_PARTNER_COLUMN,+ "campaign_network": "Campaign name as reported by the ad network.",+ "campaign_id_network": "Campaign identifier as reported by the ad network.",+ "skad_installs": "SKAdNetwork postbacks representing a new install.",+ "skad_reinstalls": "SKAdNetwork postbacks representing a reinstall.",+ "skad_total_installs": "Total SKAdNetwork conversions (installs plus reinstalls).",+ "valid_conversions": "SKAdNetwork postbacks with a non-null conversion value attached.",+ "skad_conversion_value_null": "SKAdNetwork postbacks received with a null conversion value.",+ },+ },+ "event_report": {+ "description": "Daily in-app event counts per app and attribution partner, with one row per event.",+ "docs_url": _DOCS_URL,+ "columns": {+ "day": _BASE_COLUMNS["day"],+ "app": _BASE_COLUMNS["app"],+ "app_token": _BASE_COLUMNS["app_token"],+ **_PARTNER_COLUMN,+ "event_slug": "Adjust event slug, matching the id column of the events table.",+ "event_name": "Readable name of the event.",+ "events": "Number of times the event was triggered on the day.",+ },+ },+ "events": {+ "description": "Catalog of in-app events configured in Adjust, with the slugs used to request event metrics in reports.",+ "docs_url": "https://dev.adjust.com/en/api/rs-api/events/",+ "columns": {+ "id": "Event slug, used to build report metric names such as `{slug}_events`.",+ "name": "Readable name of the event.",+ "short_name": "Shortened name of the event.",+ "section": "Report section the event belongs to.",+ "formatting": "Format the event's data is stored in (for example money).",+ "app_token": "App tokens the event is associated with.",+ "tokens": "Event token or tokens.",+ "is_skad_event": "Whether the event is a SKAdNetwork event.",+ "app_token_x_event_tokens_mapping": "Mapping of app tokens to the event's tokens in each app.",+ },+ },}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.pyindex 0ab012b71886..1515d9d6a482 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/settings.py@@ -33,8 +33,35 @@ _CORE_METRICS = [# creative, or country breakdowns, so they stay on the app-level reports._USER_METRICS = ["daus", "waus", "maus"]+_RETENTION_COHORTS = ["d1", "d7", "d30"]+_RETENTION_METRICS = [+ "installs",+ *(+ f"{metric}_{cohort}"+ for cohort in _RETENTION_COHORTS+ for metric in ("cohort_size", "retained_users", "retention_rate")+ ),+]++_SKAD_METRICS = [+ "skad_installs",+ "skad_reinstalls",+ "skad_total_installs",+ "valid_conversions",+ "skad_conversion_value_null",+]++# Adjust keeps revising recent days (late attributions, re-attributions), so an incremental run+# re-reads a trailing window; merge dedupes on the dimension key.+DEFAULT_LOOKBACK_DAYS = 3+# A day's cohort metrics keep changing until its longest cohort period (d30) has elapsed.+_RETENTION_LOOKBACK_DAYS = 31+# SKAdNetwork postbacks arrive with privacy delays of up to about five weeks (SKAN 4's last+# postback window).+_SKAD_LOOKBACK_DAYS = 35+-@dataclass+@dataclass(frozen=True)class AdjustReportConfig:name: str# `dimensions` / `metrics` are sent verbatim as the Report Service API's comma-separated@@ -47,6 +74,10 @@ class AdjustReportConfig: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+ lookback_days: int = DEFAULT_LOOKBACK_DAYS+ # Event metrics are named after each account's own event slugs, so they're discovered from the+ # events catalog at sync time and unpivoted into one row per event instead of one column each.+ event_metrics: bool = False# One entry per report shape we expose. Adjust's Report Service API is a single endpoint whose@@ -90,14 +121,42 @@ ADJUST_REPORTS: dict[str, AdjustReportConfig] = {primary_keys=["day", "app_token", "os_name"],description="Daily performance per app broken down by operating system.",),+ "retention_report": AdjustReportConfig(+ name="retention_report",+ dimensions=["day", "app", "app_token", "partner_name"],+ metrics=_RETENTION_METRICS,+ primary_keys=["day", "app_token", "partner_name"],+ lookback_days=_RETENTION_LOOKBACK_DAYS,+ description="Day 1, 7, and 30 retention per install cohort, broken down by attribution partner.",+ ),+ "skad_report": AdjustReportConfig(+ name="skad_report",+ dimensions=["day", "app", "app_token", "partner_name", "campaign_network", "campaign_id_network"],+ metrics=_SKAD_METRICS,+ primary_keys=["day", "app_token", "partner_name", "campaign_id_network"],+ lookback_days=_SKAD_LOOKBACK_DAYS,+ description="Daily SKAdNetwork installs, reinstalls, and conversion values per network campaign (iOS).",+ ),+ "event_report": AdjustReportConfig(+ name="event_report",+ dimensions=["day", "app", "app_token", "partner_name"],+ metrics=[],+ primary_keys=["day", "app_token", "partner_name", "event_slug"],+ event_metrics=True,+ description="Daily in-app event counts per app and attribution partner, one row per event.",+ ),}-ENDPOINTS = tuple(ADJUST_REPORTS.keys())+# The events catalog maps readable event names and tokens to the slugs used in report metrics.+EVENTS_CATALOG = "events"++ENDPOINTS = (*ADJUST_REPORTS.keys(), EVENTS_CATALOG)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+ **{name: config.description for name, config in ADJUST_REPORTS.items() if config.description},+ EVENTS_CATALOG: "Catalog of in-app events with their report slugs, names, event tokens, and apps.",}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.pyindex 92425bab5474..bfccfc4723a7 100644--- 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@@ -90,8 +90,8 @@ def _scripted_page(rows: list[dict[str, Any]], next_url: str | None = None) -> Sreturn ScriptedResponse(json={"rows": rows, "totals": {}, "pagination": pagination})-def _driver() -> SourceDriver:- return SourceDriver(AdjustSource(), AdjustSourceConfig(api_token="token"))+def _driver(app_tokens: str | None = None) -> SourceDriver:+ return SourceDriver(AdjustSource(), AdjustSourceConfig(api_token="token", app_tokens=app_tokens))def _run_get_rows(@@ -156,7 +156,8 @@ class TestBuildReportParams:# 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)+ unpivoted_keys = {"event_slug"} if config.event_metrics else set()+ assert set(config.primary_keys) <= set(config.dimensions) | unpivoted_keysclass TestRequest:@@ -341,6 +342,74 @@ class TestGetRows:"2024-06-27:2024-06-30",]+ @parameterized.expand(+ [+ ("daily_report", "2024-06-27"),+ ("retention_report", "2024-05-30"),+ ("skad_report", "2024-05-26"),+ ]+ )+ def test_incremental_lookback_covers_the_report_revision_window(self, report: str, expected_start: str) -> None:+ # Cohort and SKAN figures keep changing for weeks, so a short lookback would freeze them+ # at their first, immature value.+ with mock.patch.object(adjust, "_today", return_value=TODAY):+ result = _driver().run(+ report,+ always(_scripted_page([])),+ incremental_field="day",+ db_incremental_field_last_value="2024-06-30",+ )++ assert result.raised is None+ assert (result.params("date_period")[0] or "").startswith(f"{expected_start}:")++ def test_event_report_unpivots_event_metrics_in_day_order(self) -> None:+ catalog = [+ {"id": "purchase", "name": "Purchase", "is_skad_event": False},+ {"id": "signup", "name": "Sign up", "is_skad_event": False},+ {"id": "skad_purchase", "name": "SKAN purchase", "is_skad_event": True},+ ]+ dims = {"app": "App", "app_token": "abc123", "partner_name": "Organic"}+ with (+ mock.patch.object(adjust, "_today", return_value=TODAY),+ mock.patch.object(adjust, "MAX_EVENT_METRICS_PER_REQUEST", 1),+ ):+ result = _driver(app_tokens="abc123").run(+ "event_report",+ [+ ScriptedResponse(json=catalog),+ _scripted_page(+ [+ {"day": "2024-06-29", **dims, "purchase_events": "2"},+ {"day": "2024-06-30", **dims, "purchase_events": "0"},+ ]+ ),+ _scripted_page([{"day": "2024-06-29", **dims, "signup_events": "5"}]),+ ],+ incremental_field="day",+ db_incremental_field_last_value="2024-06-30",+ )++ assert result.raised is None+ assert result.requests[0].path == "/reports-service/events"+ assert result.requests[0].param("app_token__in") == "abc123"+ assert result.params("metrics") == [None, "purchase_events", "signup_events"]+ assert result.items == [+ [+ {**dims, "day": "2024-06-29", "event_slug": "purchase", "event_name": "Purchase", "events": "2"},+ {**dims, "day": "2024-06-29", "event_slug": "signup", "event_name": "Sign up", "events": "5"},+ ]+ ]++ @parameterized.expand([("no_content", ScriptedResponse(status=204)), ("empty_list", ScriptedResponse(json=[]))])+ def test_event_report_with_empty_catalog_requests_no_report(self, _name: str, catalog: ScriptedResponse) -> None:+ with mock.patch.object(adjust, "_today", return_value=TODAY):+ result = _driver().run("event_report", [catalog], incremental_field="day")++ assert result.raised is None+ assert len(result.requests) == 1+ assert result.items == []+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@@ -404,10 +473,11 @@ class TestValidateCredentials:class TestAdjustSource:@parameterized.expand([(name,) for name in ADJUST_REPORTS])def test_source_response_shape(self, name: str) -> None:+ script = [ScriptedResponse(json=[])] if ADJUST_REPORTS[name].event_metrics else always(_scripted_page([]))with mock.patch.object(adjust, "_today", return_value=TODAY):result = _driver().run(name,- [_scripted_page([])],+ script,incremental_field="day",db_incremental_field_last_value="2024-06-30",)