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(warehouse-sources): App Store Connect analytics report streams (#80189)

jake sciottoa2e405427f7c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py
index e952896113ab..e00953f172f7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py
@@ -3,10 +3,12 @@ import re
import csv
import gzip
import time
+import hashlib
+import tempfile
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
-from typing import Any, Optional
+from typing import IO, Any, Optional
from urllib.parse import urlsplit
import jwt
@@ -14,6 +16,8 @@ import requests
from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (
+ ANALYTICS_GRANULARITY,
+ ANALYTICS_MAX_INSTANCES_PER_RUN,
APP_STORE_CONNECT_ENDPOINTS,
MAX_PAGE_SIZE,
SALES_REPORT_END_OFFSET_DAYS,
@@ -46,6 +50,18 @@ REPORT_ACCEPT = "application/a-gzip"
# forever. At 200 rows a page that is 400k rows.
MAX_PAGES_PER_RESOURCE = 2000
+# Analytics segment downloads are presigned object-store URLs on Apple's storage, not the API origin,
+# and they expire about five minutes after the segments call. The Apple bearer token must never be
+# sent to them, and the host allowlist keeps a tampered URL from pointing the download at an
+# arbitrary or internal host.
+ANALYTICS_SEGMENT_HOST_SUFFIXES = (".amazonaws.com", ".apple.com", ".mzstatic.com")
+
+# In-memory cap while downloading one analytics segment; larger segments spool to disk so the
+# checksum can be verified before any row is parsed, without holding whole files in memory.
+ANALYTICS_SEGMENT_SPOOL_BYTES = 32 * 1024 * 1024
+
+ANALYTICS_ROWS_PER_BATCH = 2000
+
_PEM_HEADER = "-----BEGIN PRIVATE KEY-----"
_PEM_FOOTER = "-----END PRIVATE KEY-----"
_NON_ALNUM = re.compile(r"[^0-9a-z]+")
@@ -86,6 +102,10 @@ class AppStoreConnectResumeConfig:
next_url: str | None = None
# Report streams bookmark: the next report date to fetch, as `YYYY-MM-DD`.
report_date: str | None = None
+ # Analytics streams bookmark: the next instance processing date to fetch, as
+ # `YYYY-MM-DD`. Dates are walked ascending across every app, so no app bookmark is
+ # needed. Optional so states saved before this field existed still parse.
+ processing_date: str | None = None
def _normalize_private_key(private_key: str) -> str:
@@ -138,11 +158,23 @@ class AppStoreConnectTokenProvider:
) from e
-def _make_session(private_key: str) -> requests.Session:
+def _make_session(private_key: str, capture: bool = True) -> requests.Session:
# The private key itself is never sent — only the signature it produces — but redact it so a future
# change can't leak it into a captured sample. Redirects stay off so a 3xx can't quietly forward a
# bearer-token-bearing request to another host; `_get` treats any redirect as a failure.
- return make_tracked_session(redact_values=(private_key,), allow_redirects=False)
+ # `capture=False` keeps a session's responses out of HTTP sample capture, for calls whose bodies
+ # carry values the name-based scrubbers can't recognise (the presigned analytics segment URLs).
+ return make_tracked_session(redact_values=(private_key,), allow_redirects=False, capture=capture)
+
+
+def _make_segment_download_session(presigned_query: str) -> requests.Session:
+ # The presigned query string is a short-lived credential: redact it so the request log
+ # line can't carry a usable signature, and keep the bulk report body out of sample capture.
+ return make_tracked_session(
+ redact_values=(presigned_query,) if presigned_query else (),
+ allow_redirects=False,
+ capture=False,
+ )
def _get(
@@ -517,6 +549,374 @@ def _get_sales_report(
)
+def _require_segment_url(url: str) -> str:
+ """Allow only https URLs on Apple's storage hosts for analytics segment downloads."""
+ try:
+ parts = urlsplit(url)
+ except Exception as e:
+ raise AppStoreConnectUrlError(f"Unparseable analytics segment URL: {url!r}") from e
+
+ hostname = parts.hostname or ""
+ if parts.scheme != "https" or not hostname.endswith(ANALYTICS_SEGMENT_HOST_SUFFIXES):
+ raise AppStoreConnectUrlError(f"Refusing to download an analytics segment from: {url!r}")
+ return url
+
+
+def _post_json(
+ session: requests.Session,
+ url: str,
+ *,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ payload: dict[str, Any],
+ tolerate: tuple[int, ...] = (),
+) -> requests.Response:
+ _require_api_url(url)
+
+ def _send(token: str) -> requests.Response:
+ return session.post(
+ url,
+ json=payload,
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ response = _send(token_provider.token())
+ if response.status_code == 401:
+ response = _send(token_provider.token(force_refresh=True))
+
+ if 300 <= response.status_code < 400:
+ logger.error(f"App Store Connect unexpected redirect: status={response.status_code}, url={url}")
+ raise AppStoreConnectUrlError(f"Unexpected redirect from App Store Connect: {url!r}")
+
+ if response.status_code in tolerate:
+ return response
+
+ if not response.ok:
+ logger.error(
+ f"App Store Connect API error: status={response.status_code}, body={response.text[:500]}, url={url}"
+ )
+ response.raise_for_status()
+
+ return response
+
+
+def _ensure_report_request(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ app_id: str,
+) -> tuple[str | None, bool]:
+ """Reuse the app's active ONGOING analytics report request, creating one only if none exists.
+
+ Returns ``(request_id, created_now)``. Creating a request is the only call in this source that
+ mutates the customer's App Store Connect account, so it has to be idempotent: an existing active
+ request is always reused, and a request Apple stopped due to inactivity no longer generates
+ reports, so it doesn't count as active. Apple rejects a duplicate create with a 409, which
+ resolves by re-reading the list.
+ """
+ list_url = f"{BASE_URL}/v1/apps/{app_id}/analyticsReportRequests"
+
+ def _active_request_id() -> str | None:
+ body = _get(
+ session,
+ list_url,
+ token_provider=token_provider,
+ logger=logger,
+ params={"filter[accessType]": "ONGOING", "limit": MAX_PAGE_SIZE},
+ ).json()
+ data = body.get("data") if isinstance(body, dict) else None
+ for resource in data or []:
+ if not isinstance(resource, dict) or not resource.get("id"):
+ continue
+ attributes = resource.get("attributes")
+ if isinstance(attributes, dict) and attributes.get("stoppedDueToInactivity"):
+ continue
+ return str(resource["id"])
+ return None
+
+ existing = _active_request_id()
+ if existing:
+ return existing, False
+
+ payload = {
+ "data": {
+ "type": "analyticsReportRequests",
+ "attributes": {"accessType": "ONGOING"},
+ "relationships": {"app": {"data": {"type": "apps", "id": app_id}}},
+ }
+ }
+ response = _post_json(
+ session,
+ f"{BASE_URL}/v1/analyticsReportRequests",
+ token_provider=token_provider,
+ logger=logger,
+ payload=payload,
+ tolerate=(409,),
+ )
+ if response.status_code == 409:
+ # A concurrent sync (or a request the accessType filter hid) beat us to it.
+ return _active_request_id(), False
+
+ body = response.json()
+ data = body.get("data") if isinstance(body, dict) else None
+ request_id = data.get("id") if isinstance(data, dict) else None
+ return (str(request_id) if request_id else None), True
+
+
+def _find_analytics_report(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ config: AppStoreConnectEndpointConfig,
+ request_id: str,
+) -> str | None:
+ url = f"{BASE_URL}/v1/analyticsReportRequests/{request_id}/reports"
+ report_ids: dict[str, str] = {}
+ for page in _iter_pages(
+ session, token_provider, logger, url, {"filter[category]": config.analytics_report_category}
+ ):
+ for resource in page.resources:
+ row = _flatten_resource(resource)
+ if row.get("name") and row.get("id"):
+ report_ids[str(row["name"])] = str(row["id"])
+
+ for name in config.analytics_report_names:
+ if name in report_ids:
+ return report_ids[name]
+
+ logger.warning(
+ f"App Store Connect: no report named {config.analytics_report_names} under this request "
+ f"(endpoint={config.name}, available={sorted(report_ids)}). The account may not be entitled "
+ f"to this report, Apple may have renamed it, or the first reports may still be generating."
+ )
+ return None
+
+
+def _analytics_instances(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ report_id: str,
+ lower_bound: date | None,
+) -> list[tuple[str, date]]:
+ url = f"{BASE_URL}/v1/analyticsReports/{report_id}/instances"
+ instances: list[tuple[str, date]] = []
+ for page in _iter_pages(session, token_provider, logger, url, {"filter[granularity]": ANALYTICS_GRANULARITY}):
+ for resource in page.resources:
+ row = _flatten_resource(resource)
+ processing_date = _to_date(row.get("processingDate"))
+ if not row.get("id") or processing_date is None:
+ continue
+ # The lower bound is inclusive: an instance's rows can restate earlier data
+ # dates, and re-reading the boundary merges idempotently on the primary key.
+ if lower_bound is not None and processing_date < lower_bound:
+ continue
+ instances.append((str(row["id"]), processing_date))
+ instances.sort(key=lambda instance: instance[1])
+ return instances
+
+
+def _analytics_segments(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ instance_id: str,
+) -> list[dict[str, Any]]:
+ url = f"{BASE_URL}/v1/analyticsReportInstances/{instance_id}/segments"
+ segments: list[dict[str, Any]] = []
+ for page in _iter_pages(session, token_provider, logger, url, {}):
+ segments.extend(row for row in (_flatten_resource(resource) for resource in page.resources) if row.get("url"))
+ # Row keys carry the line's position within the instance, so segment order has to be
+ # deterministic across re-reads or the same key would name a different row each time.
+ segments.sort(key=lambda segment: str(segment.get("id")))
+ return segments
+
+
+def _download_segment(logger: FilteringBoundLogger, segment: dict[str, Any]) -> IO[bytes]:
+ """Download one segment to a spooled file, hashing as it streams.
+
+ The URL is presigned, so no Authorization header is attached: sending the Apple bearer token to
+ the storage host would hand it to a third party. The checksum's algorithm is undocumented (the
+ value is shaped like an MD5), so a mismatch is logged rather than fatal; failing hard on a wrong
+ algorithm guess would brick the table, and gzip's own CRC still rejects corrupted payloads at
+ decompression time.
+ """
+ url = _require_segment_url(str(segment["url"]))
+ spool = tempfile.SpooledTemporaryFile(max_size=ANALYTICS_SEGMENT_SPOOL_BYTES)
+ # Download-integrity check against Apple's checksum, not a cryptographic use; corrupted
+ # payloads are also rejected by the gzip CRC.
+ digest = hashlib.md5(usedforsecurity=False) # nosemgrep
+
+ session = _make_segment_download_session(urlsplit(url).query)
+ response = session.get(url, stream=True, timeout=REPORT_TIMEOUT_SECONDS)
+ try:
+ if not response.ok:
+ logger.error(f"App Store Connect analytics segment download failed: status={response.status_code}")
+ response.raise_for_status()
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
+ digest.update(chunk)
+ spool.write(chunk)
+ finally:
+ response.close()
+
+ expected = segment.get("checksum")
+ if expected and digest.hexdigest() != expected:
+ logger.warning(
+ f"App Store Connect: analytics segment checksum mismatch "
+ f"(expected={expected}, got={digest.hexdigest()}, sizeInBytes={segment.get('sizeInBytes')}). "
+ f"Continuing; the gzip CRC rejects genuinely corrupt payloads."
+ )
+
+ spool.seek(0)
+ return spool
+
+
+def _open_segment_text(spool: IO[bytes]) -> IO[str]:
+ # The transport can hand the payload over decompressed (a `Content-Encoding: gzip` body is
+ # unwrapped by urllib3), so sniff the magic bytes instead of assuming.
+ magic = spool.read(2)
+ spool.seek(0)
+ if magic == b"\x1f\x8b":
+ return io.TextIOWrapper(gzip.GzipFile(fileobj=spool, mode="rb"), encoding="utf-8-sig", errors="replace")
+ return io.TextIOWrapper(spool, encoding="utf-8-sig", errors="replace")
+
+
+def _iter_segment_rows(text: IO[str], processing_date: date, line_start: int) -> Iterator[dict[str, Any]]:
+ header_line = text.readline()
+ if not header_line.strip():
+ return
+
+ # Apple's segment objects are named `.csv.gz` but its docs describe the files only as
+ # delimited text, so sniff the delimiter from the header instead of assuming one.
+ delimiter = "\t" if "\t" in header_line else ","
+ columns = [_normalize_report_column(column) for column in next(csv.reader([header_line], delimiter=delimiter))]
+ processing_date_str = processing_date.isoformat()
+ line = line_start
+
+ for values in csv.reader(text, delimiter=delimiter):
+ if not any(value.strip() for value in values):
+ continue
+ row: dict[str, Any] = {
+ column: (values[index] if index < len(values) else None) for index, column in enumerate(columns)
+ }
+ row["processing_date"] = processing_date_str
+ # 1-based position within the instance, continuing across its segments. A published
+ # instance is immutable, so (app_id, processing_date, _line) stays a stable unique key
+ # and re-reading an instance merges instead of duplicating.
+ line += 1
+ row["_line"] = line
+ yield row
+
+
+def _get_analytics_report(
+ session: requests.Session,
+ segments_session: requests.Session,
+ config: AppStoreConnectEndpointConfig,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppStoreConnectResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ app_ids = _list_app_ids(session, token_provider, logger)
+ resume = _load_resume(manager)
+ resumed_date = _to_date(resume.processing_date) if resume is not None else None
+ watermark = _to_date(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ lower_bound: date | None = None
+ for candidate in (watermark, resumed_date):
+ if candidate is not None and (lower_bound is None or candidate > lower_bound):
+ lower_bound = candidate
+
+ # Discover every app's report and instances up front, then walk processing dates in
+ # ascending order ACROSS apps. Yields are then globally date-ordered, so the pipeline's
+ # per-batch watermark checkpoint can never advance past an app whose older instances are
+ # still unfetched, and the walk can stop cleanly at the first gap or at the per-run cap:
+ # the watermark stands at the last date reached, and because the lower bound is inclusive
+ # the next run re-reads that boundary date in full and the merge dedupes it. Resume state
+ # is job-scoped (it survives retries of the same job, never the next scheduled run), so
+ # the watermark has to carry cross-run progress by itself.
+ instances_by_date: dict[date, list[tuple[str, str]]] = {}
+ for app_id in app_ids:
+ request_id, created_now = _ensure_report_request(session, token_provider, logger, app_id)
+ if created_now:
+ logger.info(
+ f"App Store Connect: created an ONGOING analytics report request for app {app_id}; "
+ f"Apple generates the first reports in 1-2 days. endpoint={config.name}"
+ )
+ continue
+ if request_id is None:
+ continue
+
+ report_id = _find_analytics_report(session, token_provider, logger, config, request_id)
+ if report_id is None:
+ # An unavailable report degrades this table for this app; other apps and tables
+ # are unaffected.
+ continue
+
+ for instance_id, processing_date in _analytics_instances(
+ session, token_provider, logger, report_id, lower_bound
+ ):
+ instances_by_date.setdefault(processing_date, []).append((app_id, instance_id))
+
+ instances_fetched = 0
+ for processing_date in sorted(instances_by_date):
+ for app_id, instance_id in instances_by_date[processing_date]:
+ if instances_fetched >= ANALYTICS_MAX_INSTANCES_PER_RUN:
+ # An incremental sync continues from the watermark next run. A full refresh
+ # has no watermark to continue from, so a cap-hit there means a truncated
+ # table until the backlog fits in one run.
+ logger.warning(
+ f"App Store Connect: hit the per-run analytics instance cap at "
+ f"{processing_date.isoformat()}; later dates are left for the next "
+ f"incremental run. endpoint={config.name}"
+ )
+ manager.save_state(AppStoreConnectResumeConfig(processing_date=processing_date.isoformat()))
+ return
+
+ segments = _analytics_segments(segments_session, token_provider, logger, instance_id)
+ if not segments:
+ # The instance is listed but its files aren't ready. Stop the whole walk at
+ # this date so no newer date is emitted past the gap: the watermark then
+ # stays at or below this date, and the next run re-reads it once the files
+ # exist.
+ logger.info(
+ f"App Store Connect: analytics instance has no segments yet, stopping the "
+ f"walk at this date. endpoint={config.name}, app_id={app_id}, "
+ f"processing_date={processing_date.isoformat()}"
+ )
+ manager.save_state(AppStoreConnectResumeConfig(processing_date=processing_date.isoformat()))
+ return
+
+ line = 0
+ batch: list[dict[str, Any]] = []
+ for segment in segments:
+ spool = _download_segment(logger, segment)
+ try:
+ with _open_segment_text(spool) as text:
+ for row in _iter_segment_rows(text, processing_date, line):
+ row["app_id"] = app_id
+ line = row["_line"]
+ batch.append(row)
+ if len(batch) >= ANALYTICS_ROWS_PER_BATCH:
+ yield batch
+ batch = []
+ finally:
+ spool.close()
+ if batch:
+ yield batch
+
+ instances_fetched += 1
+
+ # The date is complete for every app, so a retried attempt of this job can start at
+ # the next one. Saved AFTER the date's rows are yielded, so a crash re-reads the
+ # date rather than skipping it; the merge dedupes the re-read.
+ manager.save_state(
+ AppStoreConnectResumeConfig(processing_date=(processing_date + timedelta(days=1)).isoformat())
+ )
+
+
def check_credentials(issuer_id: str, key_id: str, private_key: str) -> tuple[int | None, str | None]:
"""Probe ``/v1/apps`` with a minted token.
@@ -560,6 +960,20 @@ def get_rows(
yield from _get_collection(session, config, token_provider, logger, resumable_source_manager)
elif config.kind == "app_fanout":
yield from _get_app_fanout(session, config, token_provider, logger, resumable_source_manager)
+ elif config.kind == "analytics_report":
+ yield from _get_analytics_report(
+ session,
+ # Segment listings ride a capture-disabled session: their bodies carry presigned
+ # URLs whose query strings are short-lived credentials the name-based scrubbers
+ # can't recognise.
+ _make_session(private_key, capture=False),
+ config,
+ token_provider,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
else: # "sales_report"
yield from _get_sales_report(
session,
@@ -609,7 +1023,8 @@ def app_store_connect_source(
partition_mode="datetime" if config.partition_key else None,
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- # Report streams walk dates oldest-first. Collections are full refreshes merged on a unique key,
- # so their page order doesn't affect the result either way.
+ # Report streams walk dates oldest-first (analytics streams date-major across apps, so
+ # per-batch watermark checkpoints stay safe despite the fan-out), and collections are
+ # full refreshes merged on a unique key, so asc fits everything.
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py
index 31ee81ab502c..70bb9cb09dc7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py
@@ -10,6 +10,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
+# Columns every analytics report stream shares: the sync's own key columns plus the
+# fields Apple includes in every report.
+_ANALYTICS_SHARED_COLUMNS: dict[str, str] = {
+ "app_id": "Identifier of the app the report belongs to.",
+ "processing_date": (
+ "Date Apple processed the report instance the row came from. Rows in an instance can carry earlier data dates."
+ ),
+ "_line": "Position of the row within the report instance's files, unique per app and processing date.",
+ "date": "Date the events in the row occurred. The first day of the period for weekly or monthly data.",
+ "app_name": "Name of the app as set up in App Store Connect.",
+ "app_apple_identifier": "Apple ID of the app.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"apps": {
"description": "An app on the App Store, and the parent of the per-app version, review, purchase and subscription tables.",
@@ -236,4 +249,132 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"country": "App Store territory the events are counted in.",
},
},
+ "analytics_app_sessions": {
+ "description": (
+ "How often people open the app and for how long, from Apple's App Sessions analytics "
+ "report. One row per instance line; an instance's rows can restate earlier data dates."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-sessions",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "app_version": "Version of the app in the session.",
+ "device": "Device model the sessions occurred on.",
+ "platform_version": "OS version of the device.",
+ "source_type": "Where the user discovered the app.",
+ "page_type": "App Store page associated with the discovery.",
+ "app_download_date": "Date the app was downloaded onto the device.",
+ "territory": "App Store country or region of the sessions.",
+ "sessions": "Total number of sessions.",
+ "total_session_duration": "Total duration of the sessions, in seconds.",
+ "unique_devices": "Number of unique devices with sessions.",
+ },
+ },
+ "analytics_app_store_downloads": {
+ "description": (
+ "How many times people download the app on the App Store, including redownloads and "
+ "updates, from Apple's App Store Downloads analytics report."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-download",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "download_type": "Kind of download: first-time download, redownload, update, or restore.",
+ "app_version": "Version of the app downloaded.",
+ "device": "Device model the download occurred on.",
+ "platform_version": "OS version of the downloading device.",
+ "source_type": "Where the user discovered the app.",
+ "page_type": "App Store page the download came from.",
+ "pre_order": "Whether the download came from a pre-order.",
+ "territory": "App Store country or region of the download.",
+ "counts": "Total number of downloads.",
+ },
+ },
+ "analytics_installations_deletions": {
+ "description": (
+ "How many times users install and delete the app, from Apple's App Store Installations "
+ "and Deletions analytics report. Covers users who opted in to sharing data."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-installs",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "event": "Type of event, Install or Delete.",
+ "download_type": "How the install originally occurred.",
+ "app_version": "Version of the app installed or deleted.",
+ "device": "Device model the event occurred on.",
+ "platform_version": "OS version of the device.",
+ "source_type": "Where the user discovered the app.",
+ "page_type": "App Store page that led to the discovery.",
+ "app_download_date": "Date the app was downloaded onto the device.",
+ "territory": "App Store country or region of the event.",
+ "counts": "Total number of events.",
+ "unique_devices": "Number of unique devices generating events.",
+ },
+ },
+ "analytics_discovery_engagement": {
+ "description": (
+ "How users find and interact with the app on the App Store (impressions, page views, "
+ "taps), from Apple's App Store Discovery and Engagement analytics report."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-store-discovery-and-engagement",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "event": "Event type: impression, page view, or tap.",
+ "page_type": "App Store page associated with the event.",
+ "source_type": "Where the user discovered the app.",
+ "engagement_type": "Action the user took on the impression or page.",
+ "device": "Device model the event occurred on.",
+ "platform_version": "OS version of the device.",
+ "territory": "App Store country or region of the event.",
+ "counts": "Total number of events.",
+ "unique_counts": "Number of unique users performing the event.",
+ },
+ },
+ "analytics_app_crashes": {
+ "description": (
+ "Crash counts by app version and device, from Apple's App Crashes analytics report. "
+ "Covers users who opted in to sharing data, with low-volume rows suppressed."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-crashes",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "app_version": "Version of the app that crashed.",
+ "device": "Device model the crashes occurred on.",
+ "platform_version": "OS version of the device.",
+ "crashes": "Total number of crashes.",
+ "unique_devices": "Number of unique devices on which the app crashed.",
+ },
+ },
+ "analytics_app_store_preorders": {
+ "description": (
+ "Pre-orders placed and canceled for the app, from Apple's App Store Pre-orders analytics report."
+ ),
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-store-pre-order",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "device": "Device model the pre-order was placed on.",
+ "platform_version": "OS version of the device.",
+ "source_type": "Where the user discovered the app.",
+ "page_type": "App Store page the pre-order was placed from.",
+ "territory": "App Store country or region of the pre-order.",
+ "pre_order_start_date": "Date the app became available for pre-order.",
+ "pre_order_end_date": "Last date the app is available for pre-order.",
+ "pre_orders_placed": "Total pre-orders placed.",
+ "pre_orders_canceled": "Total pre-orders canceled.",
+ },
+ },
+ "analytics_app_clip_usage": {
+ "description": "How users engage with the app's App Clips, from Apple's App Clip Usage analytics report.",
+ "docs_url": "https://developer.apple.com/documentation/analytics-reports/app-clip-usage",
+ "columns": {
+ **_ANALYTICS_SHARED_COLUMNS,
+ "app_clip_event_type": "Type of App Clip event: views, installations, sessions, or crashes.",
+ "source_type": "Where the user discovered the App Clip.",
+ "app_version": "Version of the App Clip on the device.",
+ "device": "Device model the event occurred on.",
+ "platform_version": "OS version of the device.",
+ "territory": "App Store country or region of the event.",
+ "counts": "Total number of App Clip events.",
+ "total_session_duration": "Total duration of the reported sessions, in seconds.",
+ "unique_devices": "Number of unique devices with events.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py
index 5110e64ea21b..de09093fc264 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py
@@ -4,14 +4,19 @@ from typing import Literal, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-# App Store Connect splits into two very different transports, so the catalog carries three kinds:
+# App Store Connect splits into very different transports, so the catalog carries four kinds:
#
-# - "collection": a top-level JSON:API list (`/v1/apps`, `/v1/builds`, ...) walked via `links.next`.
-# - "app_fanout": a per-app JSON:API list (`/v1/apps/{app_id}/customerReviews`, ...). Apps are
-# discovered from `/v1/apps` first, then each app's collection is walked.
-# - "sales_report": `/v1/salesReports`, which is not a collection at all — one request per report date
-# returns a gzipped TSV file. Walked forward a day at a time from the watermark.
-EndpointKind = Literal["collection", "app_fanout", "sales_report"]
+# - "collection": a top-level JSON:API list (`/v1/apps`, `/v1/builds`, ...) walked via `links.next`.
+# - "app_fanout": a per-app JSON:API list (`/v1/apps/{app_id}/customerReviews`, ...). Apps are
+# discovered from `/v1/apps` first, then each app's collection is walked.
+# - "sales_report": `/v1/salesReports`, which is not a collection at all — one request per report date
+# returns a gzipped TSV file. Walked forward a day at a time from the watermark.
+# - "analytics_report": Apple's Analytics Reports API, an asynchronous request/poll/download flow.
+# Per app: ensure an ONGOING report request exists (the one account mutation this
+# source makes), find the named report under it, list its DAILY instances, then
+# download and parse each instance's file segments. Walked forward by instance
+# processing date from the watermark.
+EndpointKind = Literal["collection", "app_fanout", "sales_report", "analytics_report"]
# Apple caps most collection pages at 200 resources.
MAX_PAGE_SIZE = 200
@@ -28,6 +33,17 @@ SALES_REPORT_MAX_DAYS_PER_RUN = 400
# yesterday (UTC). Asking for today reliably 404s.
SALES_REPORT_END_OFFSET_DAYS = 1
+# Analytics reports generate one instance per day per granularity; only DAILY is synced. Weekly and
+# monthly instances aggregate the same rows, so syncing them too would double-count.
+ANALYTICS_GRANULARITY = "DAILY"
+
+# Analytics instances downloaded in a single run, across all apps. Ongoing requests accumulate at
+# most ~35 daily instances (Apple's retention) per report per app, so this cap only bites on a
+# cold start with many apps. The walk is date-ascending, so an incremental sync that hits the cap
+# continues from its watermark next run; a full-refresh sync has no watermark and stays truncated
+# until its backlog fits in one run.
+ANALYTICS_MAX_INSTANCES_PER_RUN = 400
+
@dataclass
class AppStoreConnectEndpointConfig:
@@ -51,6 +67,15 @@ class AppStoreConnectEndpointConfig:
# Column that carries the id of the `data` resource referencing each included row, so
# the table joins back to its parent without a per-row request.
included_parent_column: str = "parent_id"
+ # Analytics Reports API selectors, only meaningful for the "analytics_report" kind.
+ # Acceptable report names in preference order: Apple exposes most reports as separate
+ # "<name> Standard" / "<name> Detailed" resources, but a few (App Crashes, App Clip
+ # Usage) carry no suffix on their standard variant. Standard is preferred: it covers
+ # the full population, while Detailed is limited to opted-in users.
+ analytics_report_names: tuple[str, ...] = ()
+ # Category the report lives under, sent as filter[category] so the per-request report
+ # list stays one page.
+ analytics_report_category: str = ""
# `/v1/salesReports` filters, only meaningful for the "sales_report" kind.
report_type: str = ""
report_sub_type: str = ""
@@ -67,6 +92,26 @@ class AppStoreConnectEndpointConfig:
_REPORT_DATE_FIELD: IncrementalField = incremental_field("report_date", IncrementalFieldType.Date)
+_PROCESSING_DATE_FIELD: IncrementalField = incremental_field("processing_date", IncrementalFieldType.Date)
+
+
+def _analytics_endpoint(name: str, report_names: tuple[str, ...], category: str) -> AppStoreConnectEndpointConfig:
+ # All analytics report streams share their shape: keyed on (app, instance processing
+ # date, line in the instance's files), because an instance's rows may restate earlier
+ # data dates and each instance is immutable once its files publish. Off by default:
+ # enabling the first stream creates a report request on the customer's account, and
+ # the row volume is substantial.
+ return AppStoreConnectEndpointConfig(
+ name=name,
+ kind="analytics_report",
+ primary_keys=["app_id", "processing_date", "_line"],
+ analytics_report_names=report_names,
+ analytics_report_category=category,
+ incremental_fields=[_PROCESSING_DATE_FIELD],
+ partition_key="processing_date",
+ should_sync_default=False,
+ )
+
APP_STORE_CONNECT_ENDPOINTS: dict[str, AppStoreConnectEndpointConfig] = {
# The app inventory, and the parent every fan-out endpoint iterates. App attributes carry no
@@ -183,6 +228,45 @@ APP_STORE_CONNECT_ENDPOINTS: dict[str, AppStoreConnectEndpointConfig] = {
should_sync_default=False,
missing_report_status_codes=(404, 400),
),
+ # Analytics Reports API streams: the behavioural data (sessions, downloads, installs
+ # and deletions, discovery, crashes, pre-orders, App Clips) that has no sales-report
+ # equivalent. The suffix-less fallbacks cover Apple renaming a variant; the crashes
+ # and App Clip reports carry no "Standard" suffix today, so their plain name leads.
+ "analytics_app_sessions": _analytics_endpoint(
+ "analytics_app_sessions",
+ ("App Sessions Standard", "App Sessions"),
+ "APP_USAGE",
+ ),
+ "analytics_app_store_downloads": _analytics_endpoint(
+ "analytics_app_store_downloads",
+ ("App Store Downloads Standard", "App Store Downloads"),
+ "COMMERCE",
+ ),
+ "analytics_installations_deletions": _analytics_endpoint(
+ "analytics_installations_deletions",
+ ("App Store Installations and Deletions Standard", "App Store Installations and Deletions"),
+ "APP_USAGE",
+ ),
+ "analytics_discovery_engagement": _analytics_endpoint(
+ "analytics_discovery_engagement",
+ ("App Store Discovery and Engagement Standard", "App Store Discovery and Engagement"),
+ "APP_STORE_ENGAGEMENT",
+ ),
+ "analytics_app_crashes": _analytics_endpoint(
+ "analytics_app_crashes",
+ ("App Crashes", "App Crashes Standard"),
+ "APP_USAGE",
+ ),
+ "analytics_app_store_preorders": _analytics_endpoint(
+ "analytics_app_store_preorders",
+ ("App Store Pre-orders Standard", "App Store Pre-orders"),
+ "COMMERCE",
+ ),
+ "analytics_app_clip_usage": _analytics_endpoint(
+ "analytics_app_clip_usage",
+ ("App Clip Usage", "App Clip Usage Standard"),
+ "APP_USAGE",
+ ),
}
ENDPOINTS = tuple(APP_STORE_CONNECT_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
index d23d5be7165e..a51f1db641e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
@@ -1,4 +1,5 @@
import gzip
+import hashlib
from datetime import date, timedelta
from typing import Any
@@ -511,6 +512,355 @@ class TestReviewResponses:
assert response.partition_keys is None
+APPS_URL = f"{BASE_URL}/v1/apps"
+REQUESTS_URL = f"{BASE_URL}/v1/apps/A1/analyticsReportRequests"
+CREATE_REQUEST_URL = f"{BASE_URL}/v1/analyticsReportRequests"
+REPORTS_URL = f"{BASE_URL}/v1/analyticsReportRequests/REQ1/reports"
+INSTANCES_URL = f"{BASE_URL}/v1/analyticsReports/REP1/instances"
+
+
+def _segments_url(instance_id: str) -> str:
+ return f"{BASE_URL}/v1/analyticsReportInstances/{instance_id}/segments"
+
+
+def _gzip_csv(text: str) -> bytes:
+ return gzip.compress(text.encode())
+
+
+def _segment_response(content: bytes) -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.iter_content.side_effect = lambda chunk_size: iter([content])
+ return response
+
+
+def _instance(instance_id: str, processing_date: str) -> dict[str, Any]:
+ return _resource("analyticsReportInstances", instance_id, granularity="DAILY", processingDate=processing_date)
+
+
+def _segment(segment_id: str, url: str, payload: bytes) -> dict[str, Any]:
+ return _resource(
+ "analyticsReportSegments",
+ segment_id,
+ checksum=hashlib.md5(payload).hexdigest(),
+ sizeInBytes=len(payload),
+ url=url,
+ )
+
+
+class _FakeAnalyticsApi(_FakeApi):
+ """Extends _FakeApi with POST recording and presigned segment downloads served by URL."""
+
+ def __init__(
+ self,
+ bodies: dict[str, dict[str, Any]],
+ segment_payloads: dict[str, bytes] | None = None,
+ ) -> None:
+ super().__init__(bodies)
+ self.segment_payloads = segment_payloads or {}
+ self.posts: list[tuple[str, Any]] = []
+
+ def get(self, url: str, **kwargs: Any) -> MagicMock:
+ if url in self.segment_payloads:
+ self.calls.append((url, None))
+ return _segment_response(self.segment_payloads[url])
+ return super().get(url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> MagicMock:
+ self.posts.append((url, kwargs.get("json")))
+ body = {"data": {"type": "analyticsReportRequests", "id": "REQ-NEW", "attributes": {"accessType": "ONGOING"}}}
+ return _json_response(body, status_code=201)
+
+
+def _analytics_api(
+ *,
+ requests_page: list[dict[str, Any]] | None = None,
+ reports: list[dict[str, Any]] | None = None,
+ instances: list[dict[str, Any]] | None = None,
+ segments_by_instance: dict[str, list[dict[str, Any]]] | None = None,
+ segment_payloads: dict[str, bytes] | None = None,
+) -> _FakeAnalyticsApi:
+ bodies = {
+ APPS_URL: _page([_resource("apps", "A1")]),
+ REQUESTS_URL: _page(
+ requests_page
+ if requests_page is not None
+ else [_resource("analyticsReportRequests", "REQ1", accessType="ONGOING", stoppedDueToInactivity=False)]
+ ),
+ REPORTS_URL: _page(
+ reports
+ if reports is not None
+ else [_resource("analyticsReports", "REP1", name="App Sessions Standard", category="APP_USAGE")]
+ ),
+ INSTANCES_URL: _page(instances if instances is not None else []),
+ }
+ for instance_id, segment_resources in (segments_by_instance or {}).items():
+ bodies[_segments_url(instance_id)] = _page(segment_resources)
+ return _FakeAnalyticsApi(bodies, segment_payloads=segment_payloads)
+
+
+def _collect_analytics(api: _FakeAnalyticsApi, manager: _FakeManager, **kwargs: Any) -> list[dict[str, Any]]:
+ session = MagicMock()
+ session.get.side_effect = api.get
+ session.post.side_effect = api.post
+ rows: list[dict[str, Any]] = []
+ with (
+ patch(f"{MODULE}._make_session", return_value=session),
+ patch(f"{MODULE}._make_segment_download_session", return_value=session),
+ ):
+ for batch in get_rows(
+ issuer_id="issuer",
+ key_id="KEY123",
+ private_key=PRIVATE_KEY_PEM,
+ vendor_number=None,
+ endpoint="analytics_app_sessions",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestAnalyticsReportStreams:
+ def test_full_chain_parses_daily_instances_into_keyed_rows(self) -> None:
+ segment_1 = _gzip_csv("Date,App Name,App Apple Identifier,Sessions\n2026-07-31,Example,123,5\n")
+ segment_2 = _gzip_csv("Date,App Name,App Apple Identifier,Sessions\n2026-08-01,Example,123,7\n")
+ segment_3 = _gzip_csv("Date,App Name,App Apple Identifier,Sessions\n2026-08-02,Example,123,2\n")
+ api = _analytics_api(
+ # Listed newest-first on purpose: the walk must process oldest-first anyway.
+ instances=[_instance("I2", "2026-08-02"), _instance("I1", "2026-08-01")],
+ segments_by_instance={
+ "I1": [
+ _segment("S1a", "https://reports.example.s3.amazonaws.com/1a", segment_1),
+ _segment("S1b", "https://reports.example.s3.amazonaws.com/1b", segment_2),
+ ],
+ "I2": [_segment("S2", "https://reports.example.s3.amazonaws.com/2", segment_3)],
+ },
+ segment_payloads={
+ "https://reports.example.s3.amazonaws.com/1a": segment_1,
+ "https://reports.example.s3.amazonaws.com/1b": segment_2,
+ "https://reports.example.s3.amazonaws.com/2": segment_3,
+ },
+ )
+ manager = _FakeManager()
+
+ rows = _collect_analytics(api, manager)
+
+ # _line continues across an instance's segments; a restart per segment would give two
+ # rows the same merge key and lose one of them.
+ assert [(row["app_id"], row["processing_date"], row["_line"], row["sessions"]) for row in rows] == [
+ ("A1", "2026-08-01", 1, "5"),
+ ("A1", "2026-08-01", 2, "7"),
+ ("A1", "2026-08-02", 1, "2"),
+ ]
+ assert rows[0]["app_apple_identifier"] == "123"
+ assert api.posts == []
+
+ params_by_url = dict(api.calls)
+ assert params_by_url[REQUESTS_URL]["filter[accessType]"] == "ONGOING"
+ assert params_by_url[REPORTS_URL]["filter[category]"] == "APP_USAGE"
+ assert params_by_url[INSTANCES_URL]["filter[granularity]"] == "DAILY"
+
+ assert [(state.app_id, state.processing_date) for state in manager.saved] == [
+ (None, "2026-08-02"),
+ (None, "2026-08-03"),
+ ]
+
+ def test_missing_request_is_created_once_and_the_app_skipped_this_run(self) -> None:
+ api = _analytics_api(requests_page=[])
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ assert rows == []
+ assert [url for url, _ in api.posts] == [CREATE_REQUEST_URL]
+ _, payload = api.posts[0]
+ assert payload["data"]["attributes"]["accessType"] == "ONGOING"
+ assert payload["data"]["relationships"]["app"]["data"] == {"type": "apps", "id": "A1"}
+ # First reports generate in 1-2 days, so nothing further is polled for this app.
+ assert REPORTS_URL not in [url for url, _ in api.calls]
+
+ def test_request_stopped_due_to_inactivity_does_not_count_as_active(self) -> None:
+ api = _analytics_api(
+ requests_page=[
+ _resource("analyticsReportRequests", "REQ1", accessType="ONGOING", stoppedDueToInactivity=True)
+ ]
+ )
+
+ _collect_analytics(api, _FakeManager())
+
+ assert [url for url, _ in api.posts] == [CREATE_REQUEST_URL]
+
+ def test_incremental_walk_reads_from_the_watermark_day_inclusive(self) -> None:
+ payload = _gzip_csv("Date,Sessions\n2026-08-02,5\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ segments_by_instance={"I2": [_segment("S2", "https://r.s3.amazonaws.com/2", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/2": payload},
+ )
+
+ rows = _collect_analytics(
+ api,
+ _FakeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 8, 2),
+ )
+
+ assert [row["processing_date"] for row in rows] == ["2026-08-02"]
+ assert _segments_url("I1") not in [url for url, _ in api.calls]
+
+ def test_resume_bookmark_floors_the_walk(self) -> None:
+ payload = _gzip_csv("Date,Sessions\n2026-08-02,5\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ segments_by_instance={"I2": [_segment("S2", "https://r.s3.amazonaws.com/2", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/2": payload},
+ )
+ manager = _FakeManager(AppStoreConnectResumeConfig(processing_date="2026-08-02"))
+
+ rows = _collect_analytics(api, manager)
+
+ assert [row["processing_date"] for row in rows] == ["2026-08-02"]
+ assert _segments_url("I1") not in [url for url, _ in api.calls]
+
+ def test_unavailable_report_degrades_the_table_without_failing(self) -> None:
+ api = _analytics_api(
+ reports=[_resource("analyticsReports", "REPX", name="Some Other Report", category="APP_USAGE")]
+ )
+
+ assert _collect_analytics(api, _FakeManager()) == []
+
+ def test_instance_without_segments_stops_the_walk_at_that_date(self) -> None:
+ # Emitting a later date past a not-ready gap would let the table watermark advance
+ # beyond data that never landed.
+ payload = _gzip_csv("Date,Sessions\n2026-08-02,5\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ segments_by_instance={"I1": [], "I2": [_segment("S2", "https://r.s3.amazonaws.com/2", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/2": payload},
+ )
+ manager = _FakeManager()
+
+ rows = _collect_analytics(api, manager)
+
+ assert rows == []
+ assert _segments_url("I2") not in [url for url, _ in api.calls]
+ assert manager.saved[-1].processing_date == "2026-08-01"
+
+ def test_checksum_mismatch_is_not_fatal(self) -> None:
+ # The checksum algorithm is undocumented; a wrong guess must degrade to a warning,
+ # not brick the table on every segment forever.
+ payload = _gzip_csv("Date,Sessions\n2026-08-01,5\n")
+ segment = _resource(
+ "analyticsReportSegments",
+ "S1",
+ checksum="0000",
+ sizeInBytes=len(payload),
+ url="https://r.s3.amazonaws.com/1",
+ )
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ segments_by_instance={"I1": [segment]},
+ segment_payloads={"https://r.s3.amazonaws.com/1": payload},
+ )
+
+ assert len(_collect_analytics(api, _FakeManager())) == 1
+
+ def test_off_host_segment_url_is_refused(self) -> None:
+ payload = _gzip_csv("Date,Sessions\n2026-08-01,5\n")
+ segment = _segment("S1", "https://attacker.example/steal", payload)
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ segments_by_instance={"I1": [segment]},
+ segment_payloads={"https://attacker.example/steal": payload},
+ )
+
+ with pytest.raises(AppStoreConnectUrlError):
+ _collect_analytics(api, _FakeManager())
+
+ def test_tab_delimited_segments_parse_too(self) -> None:
+ # Apple names the objects .csv.gz but its docs never state the delimiter, so both
+ # must parse.
+ payload = _gzip_csv("Date\tSessions\n2026-08-01\t5\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/1": payload},
+ )
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ assert [(row["date"], row["sessions"]) for row in rows] == [("2026-08-01", "5")]
+
+ def test_per_run_instance_cap_saves_a_resumable_bookmark(self) -> None:
+ payload = _gzip_csv("Date,Sessions\n2026-08-01,5\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/1": payload},
+ )
+ manager = _FakeManager()
+
+ with patch(f"{MODULE}.ANALYTICS_MAX_INSTANCES_PER_RUN", 1):
+ rows = _collect_analytics(api, manager)
+
+ assert [row["processing_date"] for row in rows] == ["2026-08-01"]
+ assert manager.saved[-1].processing_date == "2026-08-02"
+
+ def test_dates_walk_in_order_across_apps(self) -> None:
+ # App-major order would yield app A1's newest dates before app A2's older ones, and
+ # the per-batch ascending watermark checkpoint would then skip A2's backlog after a
+ # crash. Date-major order is what makes the checkpoint safe.
+ seg_1 = _gzip_csv("Date,Sessions\n2026-08-01,1\n")
+ seg_2 = _gzip_csv("Date,Sessions\n2026-08-02,2\n")
+ seg_3 = _gzip_csv("Date,Sessions\n2026-08-03,3\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I3", "2026-08-03")],
+ segments_by_instance={
+ "I1": [_segment("S1", "https://r.s3.amazonaws.com/1", seg_1)],
+ "I2": [_segment("S2", "https://r.s3.amazonaws.com/2", seg_2)],
+ "I3": [_segment("S3", "https://r.s3.amazonaws.com/3", seg_3)],
+ },
+ segment_payloads={
+ "https://r.s3.amazonaws.com/1": seg_1,
+ "https://r.s3.amazonaws.com/2": seg_2,
+ "https://r.s3.amazonaws.com/3": seg_3,
+ },
+ )
+ api.bodies[APPS_URL] = _page([_resource("apps", "A1"), _resource("apps", "A2")])
+ api.bodies[f"{BASE_URL}/v1/apps/A2/analyticsReportRequests"] = _page(
+ [_resource("analyticsReportRequests", "REQ2", accessType="ONGOING", stoppedDueToInactivity=False)]
+ )
+ api.bodies[f"{BASE_URL}/v1/analyticsReportRequests/REQ2/reports"] = _page(
+ [_resource("analyticsReports", "REP2", name="App Sessions Standard", category="APP_USAGE")]
+ )
+ api.bodies[f"{BASE_URL}/v1/analyticsReports/REP2/instances"] = _page([_instance("I2", "2026-08-02")])
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ assert [(row["app_id"], row["processing_date"]) for row in rows] == [
+ ("A1", "2026-08-01"),
+ ("A2", "2026-08-02"),
+ ("A1", "2026-08-03"),
+ ]
+
+ def test_analytics_source_response_checkpoints_ascending(self) -> None:
+ response = app_store_connect_source(
+ issuer_id="issuer",
+ key_id="KEY123",
+ private_key=PRIVATE_KEY_PEM,
+ vendor_number=None,
+ endpoint="analytics_app_sessions",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeManager(),
+ )
+ assert response.primary_keys == ["app_id", "processing_date", "_line"]
+ assert response.partition_keys == ["processing_date"]
+ # The walk is date-major across apps, so ascending per-batch checkpoints are safe.
+ assert response.sort_mode == "asc"
+
+
class TestReportColumnNames:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py
index b4e7f9bc7a91..1469d1cc7c38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py
@@ -93,13 +93,16 @@ class TestAppStoreConnectSource:
schemas = {schema.name: schema for schema in AppStoreConnectSource().get_schemas(_config(), team_id=1)}
for name, schema in schemas.items():
- is_report = name in REPORT_ENDPOINTS
+ kind = APP_STORE_CONNECT_ENDPOINTS[name].kind
+ is_report_stream = kind in ("sales_report", "analytics_report")
# Apple exposes no server-side timestamp filter on the JSON:API collections, so only the
- # report streams (filtered by reportDate) can sync incrementally.
- assert schema.supports_incremental is is_report
- assert schema.should_sync_default is not is_report
- if is_report:
+ # report streams (walked by report date or instance processing date) sync incrementally.
+ assert schema.supports_incremental is is_report_stream
+ assert schema.should_sync_default is not is_report_stream
+ if kind == "sales_report":
assert [field["field"] for field in schema.incremental_fields] == ["report_date"]
+ if kind == "analytics_report":
+ assert [field["field"] for field in schema.incremental_fields] == ["processing_date"]
def test_canonical_descriptions_cover_the_catalog(self) -> None:
descriptions = AppStoreConnectSource().get_canonical_descriptions()