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): backfill App Store Connect analytics history via ONE_TIME_SNAPSHOT (#82970)

jake sciotto46ce43d11c69
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 efccafa7f0ac..8828a55f772a 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
@@ -9,7 +9,7 @@ import tempfile
import dataclasses
from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
-from typing import IO, Any, Optional
+from typing import IO, Any, Literal, Optional
from urllib.parse import urlsplit
import jwt
@@ -197,7 +197,7 @@ def _require_api_url(url: str) -> str:
return url
[email protected](frozen=True, kw_only=True)
class AppStoreConnectResumeConfig:
# Fan-out bookmark: the app currently being walked. A stable Apple id rather than a positional
# index, so apps added or removed between a crash and the retry can't resume into the wrong app.
@@ -210,6 +210,15 @@ class AppStoreConnectResumeConfig:
# `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
+ # Whether this job's first attempt decided to ingest the one-time historical snapshot.
+ # Pipelines can persist the incremental watermark per batch, so a retried attempt of a first
+ # sync may arrive with a watermark even though the snapshot hasn't fully landed — the recorded
+ # decision keeps the retry from silently dropping the history. Optional so states saved before
+ # this field existed still parse.
+ include_snapshot: bool | None = None
+
+
+_ANALYTICS_SNAPSHOT_DECISION_NAMESPACE = "analytics_snapshot_decision"
def _normalize_private_key(private_key: str) -> str:
@@ -1133,52 +1142,46 @@ def _post_json(
return response
-def _ensure_report_request(
+ONGOING_ACCESS_TYPE = "ONGOING"
+SNAPSHOT_ACCESS_TYPE = "ONE_TIME_SNAPSHOT"
+
+
+def _list_report_requests(
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.
+) -> list[dict[str, Any]]:
+ """All of the app's analytics report requests, flattened, both access types.
- 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.
+ Listed unfiltered and split client-side on ``accessType``: one call serves the ongoing and
+ snapshot ensures, and a response that ignores the server-side filter can't misclassify a
+ request as the wrong kind.
"""
- list_url = f"{BASE_URL}/v1/apps/{app_id}/analyticsReportRequests"
-
- def _active_request_id() -> tuple[str | None, bool]:
- """Returns ``(active_request_id, saw_stopped)`` — the active request to reuse, and whether an
- ONGOING request stopped due to inactivity was skipped, so the create 403 can name that cause."""
- 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
- saw_stopped = False
- 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"):
- saw_stopped = True
- continue
- return str(resource["id"]), saw_stopped
- return None, saw_stopped
+ url = f"{BASE_URL}/v1/apps/{app_id}/analyticsReportRequests"
+ report_requests: list[dict[str, Any]] = []
+ for page in _iter_pages(session, token_provider, logger, url, {}):
+ report_requests.extend(_flatten_resource(resource) for resource in page.resources)
+ return [row for row in report_requests if row.get("id")]
- existing, saw_stopped = _active_request_id()
- if existing:
- return existing, False
+def _create_report_request(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ app_id: str,
+ access_type: str,
+ saw_stopped: bool = False,
+) -> str | None:
+ """POST a new analytics report request; ``None`` when Apple reports one already exists (409).
+
+ Creating a request is the only call in this source that mutates the customer's App Store
+ Connect account, so every caller has to stay idempotent around it.
+ """
payload = {
"data": {
"type": "analyticsReportRequests",
- "attributes": {"accessType": "ONGOING"},
+ "attributes": {"accessType": access_type},
"relationships": {"app": {"data": {"type": "apps", "id": app_id}}},
}
}
@@ -1210,13 +1213,60 @@ def _ensure_report_request(
)
raise AppStoreConnectPermissionError(f"{message} ({_apple_error_suffix(apple_error, 403)})")
if response.status_code == 409:
- # A concurrent sync (or a request the accessType filter hid) beat us to it.
- return _active_request_id()[0], False
+ return None
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
+ return str(request_id) if request_id else None
+
+
+def _saw_stopped_ongoing_request(report_requests: list[dict[str, Any]]) -> bool:
+ return any(
+ row.get("accessType") == ONGOING_ACCESS_TYPE and row.get("stoppedDueToInactivity") for row in report_requests
+ )
+
+
+def _active_ongoing_request_id(report_requests: list[dict[str, Any]]) -> str | None:
+ for row in report_requests:
+ if row.get("accessType") != ONGOING_ACCESS_TYPE:
+ continue
+ # A request Apple stopped due to inactivity no longer generates reports, so it doesn't
+ # count as active.
+ if row.get("stoppedDueToInactivity"):
+ continue
+ return str(row["id"])
+ return None
+
+
+def _ensure_report_request(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ app_id: str,
+ report_requests: list[dict[str, Any]],
+) -> tuple[str | None, bool]:
+ """Reuse the app's active ONGOING analytics report request, creating one only if none exists.
+
+ Returns ``(request_id, created_now)``. An existing active request is always reused. Apple
+ rejects a duplicate create with a 409, which resolves by re-reading the list.
+ """
+ existing = _active_ongoing_request_id(report_requests)
+ if existing:
+ return existing, False
+
+ created = _create_report_request(
+ session,
+ token_provider,
+ logger,
+ app_id,
+ ONGOING_ACCESS_TYPE,
+ saw_stopped=_saw_stopped_ongoing_request(report_requests),
+ )
+ if created is None:
+ # A concurrent sync beat us to it.
+ return _active_ongoing_request_id(_list_report_requests(session, token_provider, logger, app_id)), False
+ return created, True
def _normalize_report_name(name: str) -> str:
@@ -1225,13 +1275,14 @@ def _normalize_report_name(name: str) -> str:
return re.sub(r"[^a-z0-9]", "", name.casefold())
-def _find_analytics_report(
+def _list_reports(
session: requests.Session,
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
config: AppStoreConnectEndpointConfig,
request_id: str,
-) -> str | None:
+) -> dict[str, str]:
+ """Map of report name to report id under one report request, within the endpoint's category."""
url = f"{BASE_URL}/v1/analyticsReportRequests/{request_id}/reports"
report_ids: dict[str, str] = {}
for page in _iter_pages(
@@ -1241,12 +1292,29 @@ def _find_analytics_report(
row = _flatten_resource(resource)
if row.get("name") and row.get("id"):
report_ids[str(row["name"])] = str(row["id"])
+ return report_ids
+
+def _match_report(config: AppStoreConnectEndpointConfig, report_ids: dict[str, str]) -> str | None:
by_normalized = {_normalize_report_name(name): report_id for name, report_id in report_ids.items()}
for name in config.analytics_report_names:
report_id = by_normalized.get(_normalize_report_name(name))
if report_id is not None:
return report_id
+ return None
+
+
+def _find_analytics_report(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ config: AppStoreConnectEndpointConfig,
+ request_id: str,
+) -> str | None:
+ report_ids = _list_reports(session, token_provider, logger, config, request_id)
+ report_id = _match_report(config, report_ids)
+ if report_id is not None:
+ return report_id
logger.warning(
f"App Store Connect: no report named {config.analytics_report_names} under this request "
@@ -1261,8 +1329,12 @@ def _analytics_instances(
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
report_id: str,
- lower_bound: date | None,
) -> list[tuple[str, date]]:
+ """Every DAILY ``(instance_id, processing_date)`` of a report, ascending by processing date.
+
+ Unfiltered on purpose: the caller applies its watermark bound for the walk, but also needs the
+ full listing to place the snapshot's report-date cutoff at the earliest ongoing instance.
+ """
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}):
@@ -1271,15 +1343,124 @@ def _analytics_instances(
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
[email protected](frozen=True, kw_only=True)
+class _SnapshotPlan:
+ """Outcome of resolving an app's one-time historical snapshot for one report.
+
+ ``ready``: walkable instances exist. ``pending``: Apple is (or may still be) generating one.
+ ``absent``: every fulfilled snapshot request lists reports and none of them is this one, so
+ the account isn't entitled to it and there is nothing to wait for. ``forbidden``: the key's
+ role can't create the snapshot request, so there is nothing to wait for either.
+ """
+
+ state: Literal["ready", "pending", "absent", "forbidden"]
+ instances: list[tuple[str, date]] = dataclasses.field(default_factory=list)
+
+
+def _request_snapshot(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ config: AppStoreConnectEndpointConfig,
+ app_id: str,
+) -> bool:
+ """POST a ONE_TIME_SNAPSHOT request. ``False`` when the key's role can't create one.
+
+ Apple gates this create on Admin, but a Finance or Sales key reads the ongoing reports
+ fine. The backfill is an addition to that stream, so losing it must not take the stream
+ down with it: the 403 degrades this app's snapshot instead of failing the sync. A 403 on
+ the ONGOING create stays fatal, because nothing can be read without that request.
+ """
+ try:
+ _create_report_request(session, token_provider, logger, app_id, SNAPSHOT_ACCESS_TYPE)
+ except AppStoreConnectPermissionError:
+ logger.warning(
+ f"App Store Connect: this API key cannot request the one-time historical snapshot, "
+ f"which Apple allows only for an Admin key. The ongoing analytics stream keeps "
+ f"syncing without it. To backfill history, give the key the Admin role and resync "
+ f"this table. endpoint={config.name}, app_id={app_id}"
+ )
+ return False
+ return True
+
+
+def _resolve_snapshot_plan(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ config: AppStoreConnectEndpointConfig,
+ app_id: str,
+ report_requests: list[dict[str, Any]],
+) -> _SnapshotPlan:
+ """Find (or request) the app's ONE_TIME_SNAPSHOT and this report's instances under it.
+
+ A fulfilled snapshot request is always reused — a second ensure never re-creates or errors.
+ Creating is reserved for two cases: no snapshot request exists at all, or a fulfilled one's
+ instances have aged out (Apple retains them only for a limited window), where only a fresh
+ snapshot can regenerate the history. A request with no reports yet is still generating, so it
+ is waited on rather than duplicated.
+ """
+ snapshot_requests = [row for row in report_requests if row.get("accessType") == SNAPSHOT_ACCESS_TYPE]
+ if not snapshot_requests:
+ if not _request_snapshot(session, token_provider, logger, config, app_id):
+ return _SnapshotPlan(state="forbidden")
+ logger.info(
+ f"App Store Connect: requested a one-time historical snapshot for app {app_id}; "
+ f"Apple generates it in 1-2 days. endpoint={config.name}"
+ )
+ return _SnapshotPlan(state="pending")
+
+ generating = False
+ resolved_report_ids: list[str] = []
+ for row in snapshot_requests:
+ report_ids = _list_reports(session, token_provider, logger, config, str(row["id"]))
+ if not report_ids:
+ # No reports in this category yet: the snapshot is most likely still generating.
+ generating = True
+ continue
+ report_id = _match_report(config, report_ids)
+ if report_id is not None:
+ resolved_report_ids.append(report_id)
+
+ # One instance per processing date: snapshot rows are numbered from -1 within their instance,
+ # so walking two instances of one date would hand different rows the same merge key. The
+ # lowest instance id wins so re-runs pick the same one.
+ instances: dict[date, str] = {}
+ for report_id in resolved_report_ids:
+ for instance_id, processing_date in _analytics_instances(session, token_provider, logger, report_id):
+ current = instances.get(processing_date)
+ if current is None or instance_id < current:
+ instances[processing_date] = instance_id
+
+ if instances:
+ return _SnapshotPlan(
+ state="ready",
+ instances=sorted(
+ ((instance_id, processing_date) for processing_date, instance_id in instances.items()),
+ key=lambda instance: instance[1],
+ ),
+ )
+ if resolved_report_ids and not generating:
+ # Fulfilled once, but the instances aged out before they were downloaded — and no other
+ # snapshot request is mid-generation, so re-requesting won't pile requests up while a
+ # replacement is already on its way.
+ if not _request_snapshot(session, token_provider, logger, config, app_id):
+ return _SnapshotPlan(state="forbidden")
+ logger.info(
+ f"App Store Connect: the existing historical snapshot for app {app_id} has expired; "
+ f"requested a fresh one. endpoint={config.name}"
+ )
+ return _SnapshotPlan(state="pending")
+ if generating or resolved_report_ids:
+ return _SnapshotPlan(state="pending")
+ return _SnapshotPlan(state="absent")
+
+
def _analytics_segments(
session: requests.Session,
token_provider: AppStoreConnectTokenProvider,
@@ -1374,6 +1555,19 @@ def _iter_segment_rows(
yield row
[email protected](frozen=True, kw_only=True)
+class _WalkInstance:
+ """One analytics report instance scheduled into the date-ordered walk."""
+
+ app_id: str
+ instance_id: str
+ is_snapshot: bool = False
+ # Snapshot rows are kept only when their report date is strictly before this cutoff — the
+ # earliest listed ongoing instance's processing date. Report dates at or after it are the
+ # ongoing stream's to deliver, which keeps one report date from landing from both streams.
+ snapshot_cutoff: date | None = None
+
+
def _get_analytics_report(
session: requests.Session,
segments_session: requests.Session,
@@ -1390,6 +1584,8 @@ def _get_analytics_report(
# unselected app never gets an ONGOING analytics report request created on it.
app_ids = _list_app_ids(session, token_provider, logger, selected_app_ids)
resume = _load_resume(manager)
+ snapshot_decision_manager = manager.with_namespace(_ANALYTICS_SNAPSHOT_DECISION_NAMESPACE)
+ snapshot_decision = _load_resume(snapshot_decision_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
@@ -1398,6 +1594,21 @@ def _get_analytics_report(
if candidate is not None and (lower_bound is None or candidate > lower_bound):
lower_bound = candidate
+ # The one-time snapshot restates all history, so it only joins the walk when the table is
+ # known to be empty: a first sync, a resync (the reset clears the watermark before the run),
+ # or a full refresh. An established incremental table holds ongoing history the source can't
+ # enumerate, so no report-date boundary could dedupe a snapshot against it. The decision has
+ # separate state from the main resume checkpoint, because the pipeline reads that checkpoint
+ # before this generator starts and uses it to decide whether to overwrite the first batch.
+ if snapshot_decision is not None and snapshot_decision.include_snapshot is not None:
+ include_snapshot = snapshot_decision.include_snapshot
+ elif resume is not None and resume.include_snapshot is not None:
+ include_snapshot = resume.include_snapshot
+ else:
+ include_snapshot = watermark is None
+ if snapshot_decision is None or snapshot_decision.include_snapshot is None:
+ snapshot_decision_manager.save_state(AppStoreConnectResumeConfig(include_snapshot=include_snapshot))
+
# 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
@@ -1406,45 +1617,126 @@ def _get_analytics_report(
# 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]]] = {}
+ instances_by_date: dict[date, list[_WalkInstance]] = {}
+ hold_for_snapshot = False
+ snapshot_ceiling: date | None = None
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:
+ report_requests = _list_report_requests(session, token_provider, logger, app_id)
+ request_id, created_now = _ensure_report_request(session, token_provider, logger, app_id, report_requests)
+
+ snapshot_plan: _SnapshotPlan | None = None
+ if include_snapshot:
+ snapshot_plan = _resolve_snapshot_plan(session, token_provider, logger, config, app_id, report_requests)
+
+ if created_now or request_id is None:
+ 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}"
+ )
+ # The app can't be walked this run, so an available snapshot can't be emitted in
+ # order either — everything for this app has to land together on a later run.
+ if snapshot_plan is not None and snapshot_plan.state not in ("absent", "forbidden"):
+ hold_for_snapshot = True
continue
report_id = _find_analytics_report(session, token_provider, logger, config, request_id)
- if report_id is None:
+ ongoing_instances: list[tuple[str, date]] = []
+ if report_id is not None:
# An unavailable report degrades this table for this app; other apps and tables
# are unaffected.
+ ongoing_instances = _analytics_instances(session, token_provider, logger, report_id)
+
+ for instance_id, processing_date in ongoing_instances:
+ # 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_by_date.setdefault(processing_date, []).append(
+ _WalkInstance(app_id=app_id, instance_id=instance_id)
+ )
+
+ if snapshot_plan is None:
continue
+ if snapshot_plan.state == "pending" and report_id is not None:
+ # A live ongoing report is the only in-module evidence that the app is entitled to
+ # this report at all. An app that is entitled to nothing stays "pending" forever, so
+ # holding on it would keep the whole table empty forever. The accepted cost: an
+ # entitled app whose ongoing report is still generating does not hold, so a sibling
+ # app's emission can ratchet the shared watermark past it and leave that app's
+ # history to a resync.
+ hold_for_snapshot = True
+ snapshot_cutoff = min((processing_date for _, processing_date in ongoing_instances), default=None)
+ for instance_id, processing_date in snapshot_plan.instances:
+ if lower_bound is not None and processing_date < lower_bound:
+ continue
+ instances_by_date.setdefault(processing_date, []).append(
+ _WalkInstance(app_id=app_id, instance_id=instance_id, is_snapshot=True, snapshot_cutoff=snapshot_cutoff)
+ )
+ if snapshot_ceiling is None or processing_date > snapshot_ceiling:
+ snapshot_ceiling = processing_date
+
+ if hold_for_snapshot and should_use_incremental_field:
+ # An incremental table's first emission ratchets the watermark past the snapshot's
+ # report dates for good, so nothing is emitted until the snapshot can be emitted with
+ # it. A full refresh never holds: it rebuilds the whole table every run, so the next
+ # rebuild picks the history up on its own.
+ logger.info(
+ f"App Store Connect: waiting for Apple to generate the one-time historical snapshot "
+ f"(typically 1-2 days) before the first ingest, so history lands ahead of the "
+ f"ongoing stream. endpoint={config.name}"
+ )
+ return
- 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))
+ has_snapshot_instances = any(
+ walk_instance.is_snapshot for walk_instances in instances_by_date.values() for walk_instance in walk_instances
+ )
+ probed_segments: dict[str, list[dict[str, Any]]] = {}
+ if should_use_incremental_field and snapshot_ceiling is not None:
+ # Probe every instance at or below the snapshot for downloadable files before emitting
+ # anything: a not-ready instance below the snapshot would stop the walk mid-emission,
+ # ratchet the watermark, and strand the history until a manual resync.
+ for processing_date in sorted(candidate for candidate in instances_by_date if candidate <= snapshot_ceiling):
+ for walk_instance in instances_by_date[processing_date]:
+ segments = _analytics_segments(segments_session, token_provider, logger, walk_instance.instance_id)
+ if not segments:
+ logger.info(
+ f"App Store Connect: an analytics instance below the historical snapshot "
+ f"has no files yet; waiting so the snapshot isn't stranded. "
+ f"endpoint={config.name}, app_id={walk_instance.app_id}, "
+ f"processing_date={processing_date.isoformat()}"
+ )
+ return
+ probed_segments[walk_instance.instance_id] = segments
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:
+ for walk_instance in instances_by_date[processing_date]:
+ if instances_fetched >= ANALYTICS_MAX_INSTANCES_PER_RUN and not has_snapshot_instances:
# 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.
+ # table until the backlog fits in one run. A run carrying the snapshot is
+ # never truncated: stopping below the snapshot would strand the history the
+ # same way a mid-walk gap would, and its backlog is bounded by Apple's
+ # instance retention plus one snapshot per app.
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()))
+ manager.save_state(
+ AppStoreConnectResumeConfig(
+ processing_date=processing_date.isoformat(), include_snapshot=include_snapshot
+ )
+ )
return
- segments = _analytics_segments(segments_session, token_provider, logger, instance_id)
+ cached_segments = probed_segments.get(walk_instance.instance_id)
+ segments = (
+ cached_segments
+ if cached_segments is not None
+ else _analytics_segments(segments_session, token_provider, logger, walk_instance.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
@@ -1452,10 +1744,14 @@ def _get_analytics_report(
# 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"walk at this date. endpoint={config.name}, app_id={walk_instance.app_id}, "
f"processing_date={processing_date.isoformat()}"
)
- manager.save_state(AppStoreConnectResumeConfig(processing_date=processing_date.isoformat()))
+ manager.save_state(
+ AppStoreConnectResumeConfig(
+ processing_date=processing_date.isoformat(), include_snapshot=include_snapshot
+ )
+ )
return
line = 0
@@ -1465,8 +1761,21 @@ def _get_analytics_report(
try:
with _open_segment_text(spool) as text:
for row in _iter_segment_rows(text, processing_date, line, failures):
- row["app_id"] = app_id
+ row["app_id"] = walk_instance.app_id
line = row["_line"]
+ if walk_instance.is_snapshot:
+ if walk_instance.snapshot_cutoff is not None:
+ row_date = _to_date(row.get("date"))
+ # A row without a parseable report date can't be checked
+ # against the ongoing stream's coverage, so it's dropped
+ # rather than risked as a duplicate.
+ if row_date is None or row_date >= walk_instance.snapshot_cutoff:
+ continue
+ # Negative line numbers keyed by file position: they can never
+ # collide with the ongoing instance processed on the same date,
+ # and they don't shift when the cutoff moves, so a re-run
+ # re-emits identical keys and the merge folds it to no-ops.
+ row["_line"] = -line
batch.append(row)
if len(batch) >= ANALYTICS_ROWS_PER_BATCH:
yield batch
@@ -1482,7 +1791,10 @@ def _get_analytics_report(
# 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())
+ AppStoreConnectResumeConfig(
+ processing_date=(processing_date + timedelta(days=1)).isoformat(),
+ include_snapshot=include_snapshot,
+ )
)
@@ -1618,6 +1930,8 @@ def get_rows(
# Walked to completion, so drop the checkpoint — leaving it would let a later attempt on this job
# resume mid-stream instead of restarting cleanly.
+ if config.kind == "analytics_report":
+ resumable_source_manager.with_namespace(_ANALYTICS_SNAPSHOT_DECISION_NAMESPACE).clear_state()
resumable_source_manager.clear_state()
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 a2aa0cb57c84..61486b3dff93 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
@@ -18,7 +18,10 @@ _ANALYTICS_SHARED_COLUMNS: dict[str, str] = {
"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.",
+ "_line": (
+ "Position of the row within the report instance's files, unique per app and processing date. "
+ "Negative for rows backfilled from the one-time historical snapshot."
+ ),
"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.",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py
index 68396c2f6e25..67258a69ea49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/restatements.py
@@ -120,17 +120,23 @@ def _latest_vintage_join(table_name: str, identity_keys: list[str], vintage_colu
# Restricts the table to the newest restatement of each report date. A restatement
# republishes its report date in full, so a dimension tuple the newest one omits is gone
# rather than unchanged: reading a value for it from an older vintage would resurrect it.
+ # When a snapshot row ties with an ongoing row at that vintage, the ongoing row wins. The
+ # tie-break only looks at the newest vintage: an ongoing row in an older vintage must not
+ # discard a report date the snapshot alone carries at the newest one.
keys = [*identity_keys, _REPORT_DATE_COLUMN]
key_list = ", ".join(keys)
conditions = " AND ".join(f"raw.{key} = latest.{key}" for key in [*keys, vintage_column])
return (
f"FROM {table_name} AS raw\n"
"INNER JOIN (\n"
- f" SELECT {key_list}, max({vintage_column}) AS {vintage_column}\n"
+ f" SELECT {key_list}, {vintage_column}, max(_line >= 0) AS has_ongoing_row\n"
f" FROM {table_name}\n"
- f" GROUP BY {key_list}\n"
+ f" WHERE ({key_list}, {vintage_column}) IN (\n"
+ f" SELECT {key_list}, max({vintage_column}) FROM {table_name} GROUP BY {key_list}\n"
+ " )\n"
+ f" GROUP BY {key_list}, {vintage_column}\n"
") AS latest\n"
- f" ON {conditions}"
+ f" ON {conditions} AND (latest.has_ongoing_row = 0 OR raw._line >= 0)"
)
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 b49bb81b3146..afaf7a2be8ec 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
@@ -14,10 +14,13 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# - "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.
+# Per app: ensure an ONGOING report request exists, 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. On a
+# fresh table (first sync, resync, or full refresh) a ONE_TIME_SNAPSHOT request
+# is also ensured and, once Apple generates it, backfills history older than
+# the ongoing stream. Report request creation is the only account mutation this
+# source makes.
EndpointKind = Literal["collection", "app_fanout", "sales_report", "analytics_report"]
# Apple caps most collection pages at 200 resources.
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 1e08e2037912..b44896b42551 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,8 +1,9 @@
import gzip
import json
import hashlib
+from collections.abc import Generator
from datetime import UTC, date, datetime, timedelta
-from typing import Any
+from typing import Any, cast
import pytest
import time_machine
@@ -14,6 +15,7 @@ from cryptography.hazmat.primitives.asymmetric import ec
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (
+ _ANALYTICS_SNAPSHOT_DECISION_NAMESPACE,
APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,
APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,
APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,
@@ -68,10 +70,17 @@ PRIVATE_KEY_PEM = _make_pem()
class _FakeManager(ResumableSourceManager[AppStoreConnectResumeConfig]):
"""Minimal stand-in for ResumableSourceManager that records saved state in memory."""
- def __init__(self, state: AppStoreConnectResumeConfig | None = None) -> None:
+ def __init__(self, state: AppStoreConnectResumeConfig | None = None, persist_on_save: bool = False) -> None:
self._state = state
+ self._persist_on_save = persist_on_save
self.saved: list[AppStoreConnectResumeConfig] = []
self.cleared = 0
+ self.namespaces: dict[str, _FakeManager] = {}
+
+ def with_namespace(self, namespace: str) -> "_FakeManager":
+ if namespace not in self.namespaces:
+ self.namespaces[namespace] = _FakeManager(persist_on_save=True)
+ return self.namespaces[namespace]
def can_resume(self) -> bool:
return self._state is not None
@@ -80,9 +89,12 @@ class _FakeManager(ResumableSourceManager[AppStoreConnectResumeConfig]):
return self._state
def save_state(self, data: AppStoreConnectResumeConfig) -> None:
+ if self._persist_on_save:
+ self._state = data
self.saved.append(data)
def clear_state(self) -> None:
+ self._state = None
self.cleared += 1
@@ -701,6 +713,8 @@ 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"
+SNAPSHOT_REPORTS_URL = f"{BASE_URL}/v1/analyticsReportRequests/REQS1/reports"
+SNAPSHOT_INSTANCES_URL = f"{BASE_URL}/v1/analyticsReports/REPS1/instances"
def _segments_url(instance_id: str) -> str:
@@ -740,9 +754,11 @@ class _FakeAnalyticsApi(_FakeApi):
self,
bodies: dict[str, dict[str, Any]],
segment_payloads: dict[str, bytes] | None = None,
+ forbidden_access_types: tuple[str, ...] = (),
) -> None:
super().__init__(bodies)
self.segment_payloads = segment_payloads or {}
+ self.forbidden_access_types = forbidden_access_types
self.posts: list[tuple[str, Any]] = []
def get(self, url: str, **kwargs: Any) -> MagicMock:
@@ -752,8 +768,20 @@ class _FakeAnalyticsApi(_FakeApi):
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"}}}
+ payload = kwargs["json"]
+ self.posts.append((url, payload))
+ access_type = payload["data"]["attributes"]["accessType"]
+ if access_type in self.forbidden_access_types:
+ return _json_response(
+ {"errors": [{"code": "FORBIDDEN_ERROR", "detail": "Admin role required"}]}, status_code=403
+ )
+ body = {
+ "data": {
+ "type": "analyticsReportRequests",
+ "id": f"REQ-NEW-{access_type}",
+ "attributes": {"accessType": access_type},
+ }
+ }
return _json_response(body, status_code=201)
@@ -762,15 +790,29 @@ 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,
+ snapshot_requests_page: list[dict[str, Any]] | None = None,
+ snapshot_reports: list[dict[str, Any]] | None = None,
+ snapshot_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,
+ forbidden_access_types: tuple[str, ...] = (),
) -> _FakeAnalyticsApi:
+ # The default snapshot topology is a fulfilled request whose reports don't include the
+ # synced one, so tests about the ongoing stream keep their exact pre-snapshot behavior.
+ snapshot_requests = (
+ snapshot_requests_page
+ if snapshot_requests_page is not None
+ else [_resource("analyticsReportRequests", "REQS1", accessType="ONE_TIME_SNAPSHOT")]
+ )
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)]
+ (
+ requests_page
+ if requests_page is not None
+ else [_resource("analyticsReportRequests", "REQ1", accessType="ONGOING", stoppedDueToInactivity=False)]
+ )
+ + snapshot_requests
),
REPORTS_URL: _page(
reports
@@ -778,10 +820,16 @@ def _analytics_api(
else [_resource("analyticsReports", "REP1", name="App Sessions Standard", category="APP_USAGE")]
),
INSTANCES_URL: _page(instances if instances is not None else []),
+ SNAPSHOT_REPORTS_URL: _page(
+ snapshot_reports
+ if snapshot_reports is not None
+ else [_resource("analyticsReports", "REPX", name="Some Other Report", category="APP_USAGE")]
+ ),
+ SNAPSHOT_INSTANCES_URL: _page(snapshot_instances if snapshot_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)
+ return _FakeAnalyticsApi(bodies, segment_payloads=segment_payloads, forbidden_access_types=forbidden_access_types)
def _collect_analytics(
@@ -824,8 +872,9 @@ class TestAnalyticsReportStreams:
_collect_analytics(api, _FakeManager(), app_ids="A1")
- # The ONGOING request is this source's only write to the customer's account.
- assert [post[1]["data"]["relationships"]["app"]["data"]["id"] for post in api.posts] == ["A1"]
+ # The report requests are this source's only writes to the customer's account, so an
+ # unselected app must receive none of them.
+ assert {post[1]["data"]["relationships"]["app"]["data"]["id"] for post in api.posts} == {"A1"}
assert f"{BASE_URL}/v1/apps/A2/analyticsReportRequests" not in [url for url, _ in api.calls]
def test_full_chain_parses_daily_instances_into_keyed_rows(self) -> None:
@@ -863,7 +912,9 @@ class TestAnalyticsReportStreams:
assert api.posts == []
params_by_url = dict(api.calls)
- assert params_by_url[REQUESTS_URL]["filter[accessType]"] == "ONGOING"
+ # One unfiltered listing serves both the ongoing and snapshot ensures; the split happens
+ # client-side on the accessType attribute, so a server-side filter can't hide either kind.
+ assert "filter[accessType]" not in (params_by_url[REQUESTS_URL] or {})
assert params_by_url[REPORTS_URL]["filter[category]"] == "APP_USAGE"
assert params_by_url[INSTANCES_URL]["filter[granularity]"] == "DAILY"
@@ -872,20 +923,25 @@ class TestAnalyticsReportStreams:
(None, "2026-08-03"),
]
- def test_missing_request_is_created_once_and_the_app_skipped_this_run(self) -> None:
- api = _analytics_api(requests_page=[])
+ def test_missing_requests_create_ongoing_and_snapshot_and_the_app_is_skipped_this_run(self) -> None:
+ api = _analytics_api(requests_page=[], snapshot_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"}
+ # A first sync has to open both streams: the ongoing request for the daily feed, and the
+ # one-time snapshot request for history older than the connection date.
+ assert [url for url, _ in api.posts] == [CREATE_REQUEST_URL, CREATE_REQUEST_URL]
+ access_types = [payload["data"]["attributes"]["accessType"] for _, payload in api.posts]
+ assert access_types == ["ONGOING", "ONE_TIME_SNAPSHOT"]
+ for _, payload in api.posts:
+ 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:
+ # The page also carries the snapshot request, so a stopped ONGOING request must be
+ # recognized by its attributes rather than by being the only resource listed.
api = _analytics_api(
requests_page=[
_resource("analyticsReportRequests", "REQ1", accessType="ONGOING", stoppedDueToInactivity=True)
@@ -894,7 +950,7 @@ class TestAnalyticsReportStreams:
_collect_analytics(api, _FakeManager())
- assert [url for url, _ in api.posts] == [CREATE_REQUEST_URL]
+ assert [payload["data"]["attributes"]["accessType"] for _, payload in api.posts] == ["ONGOING"]
def test_incremental_walk_reads_from_the_watermark_day_inclusive(self) -> None:
payload = _gzip_csv("Date,Sessions\n2026-08-02,5\n")
@@ -1116,6 +1172,343 @@ class TestAnalyticsReportStreams:
assert response.sort_mode == "asc"
+_SNAPSHOT_READY_REPORTS = [_resource("analyticsReports", "REPS1", name="App Sessions Standard", category="APP_USAGE")]
+
+
+class TestAnalyticsSnapshotBackfill:
+ def _ready_api(self) -> _FakeAnalyticsApi:
+ """Two ongoing daily instances plus a fulfilled snapshot processed on the same day as the
+ newest ongoing instance — the collision- and overlap-prone topology."""
+ ongoing_1 = _gzip_csv("Date,Sessions\n2026-07-30,5\n")
+ ongoing_2 = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ snapshot = _gzip_csv("Date,Sessions\n2024-06-01,3\n2026-07-15,4\n2026-08-01,9\n")
+ return _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[_instance("IS1", "2026-08-02")],
+ segments_by_instance={
+ "I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", ongoing_1)],
+ "I2": [_segment("S2", "https://r.s3.amazonaws.com/o2", ongoing_2)],
+ "IS1": [_segment("SS1", "https://r.s3.amazonaws.com/s1", snapshot)],
+ },
+ segment_payloads={
+ "https://r.s3.amazonaws.com/o1": ongoing_1,
+ "https://r.s3.amazonaws.com/o2": ongoing_2,
+ "https://r.s3.amazonaws.com/s1": snapshot,
+ },
+ )
+
+ def test_snapshot_history_lands_behind_the_ongoing_window(self) -> None:
+ api = self._ready_api()
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ # Snapshot rows ride the snapshot instance's processing date with negative line numbers,
+ # so they can't collide with the ongoing instance processed the same day; and only report
+ # dates older than the earliest ongoing instance are kept — later dates belong to the
+ # ongoing stream, which is what keeps one report date from landing from both streams.
+ assert [(row["app_id"], row["processing_date"], row["_line"], row["date"]) for row in rows] == [
+ ("A1", date(2026, 8, 1), 1, date(2026, 7, 30)),
+ ("A1", date(2026, 8, 2), 1, date(2026, 7, 31)),
+ ("A1", date(2026, 8, 2), -1, date(2024, 6, 1)),
+ ("A1", date(2026, 8, 2), -2, date(2026, 7, 15)),
+ ]
+ # The fulfilled snapshot request is reused, never re-created.
+ assert api.posts == []
+
+ def test_readiness_probe_reuses_segments_during_snapshot_emission(self) -> None:
+ api = self._ready_api()
+
+ _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ for instance_id in ("I1", "I2", "IS1"):
+ assert [url for url, _ in api.calls].count(_segments_url(instance_id)) == 1
+
+ def test_running_the_backfill_twice_emits_identical_keys(self) -> None:
+ first = _collect_analytics(self._ready_api(), _FakeManager())
+ api = self._ready_api()
+ second = _collect_analytics(api, _FakeManager())
+
+ first_keys = [(row["app_id"], row["processing_date"], row["_line"]) for row in first]
+ second_keys = [(row["app_id"], row["processing_date"], row["_line"]) for row in second]
+ assert ("A1", date(2026, 8, 2), -1) in first_keys
+ # Identical, collision-free keys: the merge folds a re-run to zero new rows per report date.
+ assert first_keys == second_keys
+ assert len(set(second_keys)) == len(second_keys)
+ assert api.posts == []
+
+ def test_snapshot_ingests_fully_when_no_ongoing_instances_exist_yet(self) -> None:
+ # A new source whose snapshot generates before the first ongoing instance has no ongoing
+ # coverage to defer to, so every snapshot date lands.
+ snapshot = _gzip_csv("Date,Sessions\n2024-06-01,3\n2026-07-15,4\n")
+ api = _analytics_api(
+ instances=[],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[_instance("IS1", "2026-08-02")],
+ segments_by_instance={"IS1": [_segment("SS1", "https://r.s3.amazonaws.com/s1", snapshot)]},
+ segment_payloads={"https://r.s3.amazonaws.com/s1": snapshot},
+ )
+
+ rows = _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ assert [(row["processing_date"], row["_line"], row["date"]) for row in rows] == [
+ (date(2026, 8, 2), -1, date(2024, 6, 1)),
+ (date(2026, 8, 2), -2, date(2026, 7, 15)),
+ ]
+
+ def test_duplicate_snapshot_instances_for_one_processing_date_ingest_once(self) -> None:
+ # Apple can list several snapshot instances on one processing date; each numbers its rows
+ # from -1, so walking more than one would hand different rows the same merge key.
+ snapshot = _gzip_csv("Date,Sessions\n2024-06-01,3\n")
+ other = _gzip_csv("Date,Sessions\n2024-06-01,999\n")
+ api = _analytics_api(
+ instances=[],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[_instance("IS2", "2026-08-02"), _instance("IS1", "2026-08-02")],
+ segments_by_instance={
+ "IS1": [_segment("SS1", "https://r.s3.amazonaws.com/s1", snapshot)],
+ "IS2": [_segment("SS2", "https://r.s3.amazonaws.com/s2", other)],
+ },
+ segment_payloads={
+ "https://r.s3.amazonaws.com/s1": snapshot,
+ "https://r.s3.amazonaws.com/s2": other,
+ },
+ )
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ assert [(row["processing_date"], row["_line"], row["sessions"]) for row in rows] == [(date(2026, 8, 2), -1, 3)]
+ assert _segments_url("IS2") not in [url for url, _ in api.calls]
+
+ def test_fresh_incremental_sync_holds_until_the_snapshot_is_ready(self) -> None:
+ payload = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ # Snapshot request exists, generation not finished: no reports under it yet.
+ snapshot_reports=[],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/o1": payload},
+ )
+ manager = _FakeManager()
+
+ rows = _collect_analytics(api, manager, should_use_incremental_field=True)
+
+ # Emitting the ongoing rows now would ratchet the watermark past the snapshot's report
+ # dates and lock the history out for good, so a fresh incremental table waits.
+ assert rows == []
+ assert manager.saved == []
+ assert _segments_url("I1") not in [url for url, _ in api.calls]
+
+ def test_full_refresh_does_not_hold_for_a_generating_snapshot(self) -> None:
+ # A full refresh rebuilds the table wholesale each run, so the next rebuild picks the
+ # history up once it exists — stalling the table would buy nothing.
+ payload = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ snapshot_reports=[],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/o1": payload},
+ )
+
+ rows = _collect_analytics(api, _FakeManager())
+
+ assert [(row["processing_date"], row["_line"]) for row in rows] == [(date(2026, 8, 1), 1)]
+
+ def test_fresh_incremental_sync_holds_while_an_ongoing_instance_below_the_snapshot_is_unready(self) -> None:
+ # An ongoing instance without files below the snapshot would stop the walk mid-emission,
+ # ratchet the watermark, and strand the history — readiness has to be checked up front.
+ ongoing_1 = _gzip_csv("Date,Sessions\n2026-07-30,5\n")
+ snapshot = _gzip_csv("Date,Sessions\n2024-06-01,3\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01"), _instance("I2", "2026-08-02")],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[_instance("IS1", "2026-08-02")],
+ segments_by_instance={
+ "I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", ongoing_1)],
+ "I2": [],
+ "IS1": [_segment("SS1", "https://r.s3.amazonaws.com/s1", snapshot)],
+ },
+ segment_payloads={
+ "https://r.s3.amazonaws.com/o1": ongoing_1,
+ "https://r.s3.amazonaws.com/s1": snapshot,
+ },
+ )
+ manager = _FakeManager()
+
+ rows = _collect_analytics(api, manager, should_use_incremental_field=True)
+
+ assert rows == []
+ assert manager.saved == []
+
+ def test_per_run_instance_cap_yields_to_a_fresh_snapshot_backfill(self) -> None:
+ # Truncating a fresh incremental run below the snapshot would ratchet the watermark and
+ # strand the history, so the cap defers to the backfill instead of aborting it.
+ api = self._ready_api()
+
+ with patch(f"{MODULE}.ANALYTICS_MAX_INSTANCES_PER_RUN", 1):
+ rows = _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ assert [(row["processing_date"], row["_line"]) for row in rows] == [
+ (date(2026, 8, 1), 1),
+ (date(2026, 8, 2), 1),
+ (date(2026, 8, 2), -1),
+ (date(2026, 8, 2), -2),
+ ]
+
+ def test_expired_snapshot_is_rerequested_on_a_fresh_table(self) -> None:
+ # A fulfilled request whose instances aged out (Apple keeps them only weeks) can't serve a
+ # resync; history is only recoverable by asking Apple to generate a fresh snapshot.
+ payload = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/o1": payload},
+ )
+
+ rows = _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ assert rows == []
+ assert [payload["data"]["attributes"]["accessType"] for _, payload in api.posts] == ["ONE_TIME_SNAPSHOT"]
+
+ @parameterized.expand(
+ [
+ ("never_requested", {"snapshot_requests_page": []}),
+ ("expired", {"snapshot_reports": _SNAPSHOT_READY_REPORTS, "snapshot_instances": []}),
+ ]
+ )
+ def test_a_forbidden_snapshot_request_leaves_the_ongoing_stream_syncing(
+ self, _name: str, topology: dict[str, Any]
+ ) -> None:
+ # Apple gates the snapshot create on Admin, but a Finance or Sales key reads the ongoing
+ # reports fine. The backfill only adds to that stream, so its 403 must not take the stream
+ # down: the app loses its history, and nothing waits for a snapshot that can never exist.
+ payload = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/o1": payload},
+ forbidden_access_types=("ONE_TIME_SNAPSHOT",),
+ **topology,
+ )
+
+ rows = _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ assert [(row["processing_date"], row["_line"], row["sessions"]) for row in rows] == [(date(2026, 8, 1), 1, 7)]
+ assert [payload["data"]["attributes"]["accessType"] for _, payload in api.posts] == ["ONE_TIME_SNAPSHOT"]
+
+ def test_no_new_snapshot_request_while_a_replacement_is_generating(self) -> None:
+ # An expired snapshot request next to one that is still generating must not trigger
+ # another create, or every sync during the generation window piles a request onto the
+ # customer's account.
+ payload = _gzip_csv("Date,Sessions\n2026-07-31,7\n")
+ api = _analytics_api(
+ instances=[_instance("I1", "2026-08-01")],
+ snapshot_requests_page=[
+ _resource("analyticsReportRequests", "REQS1", accessType="ONE_TIME_SNAPSHOT"),
+ _resource("analyticsReportRequests", "REQS2", accessType="ONE_TIME_SNAPSHOT"),
+ ],
+ snapshot_reports=_SNAPSHOT_READY_REPORTS,
+ snapshot_instances=[],
+ segments_by_instance={"I1": [_segment("S1", "https://r.s3.amazonaws.com/o1", payload)]},
+ segment_payloads={"https://r.s3.amazonaws.com/o1": payload},
+ )
+ api.bodies[f"{BASE_URL}/v1/analyticsReportRequests/REQS2/reports"] = _page([])
+
+ rows = _collect_analytics(api, _FakeManager(), should_use_incremental_field=True)
+
+ assert rows == []
+ assert api.posts == []
+
+ def test_steady_state_incremental_sync_leaves_the_snapshot_alone(self) -> None:
+ # A table with a watermark holds ongoing history the source can't see, so no safe
+ # report-date boundary exists to dedupe a snapshot against — the backfill only runs on a
+ # fresh table (first sync, resync, or full refresh).
+ api = self._ready_api()
+
+ rows = _collect_analytics(
+ api,
+ _FakeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 8, 1),
+ )
+
+ assert [(row["processing_date"], row["_line"]) for row in rows] == [
+ (date(2026, 8, 1), 1),
+ (date(2026, 8, 2), 1),
+ ]
+ assert SNAPSHOT_REPORTS_URL not in [url for url, _ in api.calls]
+ assert api.posts == []
+
+ def test_snapshot_inclusion_survives_a_mid_job_retry(self) -> None:
+ # Pipelines can persist the watermark per batch, so a retried attempt of a first sync can
+ # arrive with a watermark before the snapshot has landed; the resume state carries the
+ # inclusion decision across attempts so the retry can't silently drop the history.
+ api = self._ready_api()
+ manager = _FakeManager(AppStoreConnectResumeConfig(processing_date="2026-08-02", include_snapshot=True))
+
+ rows = _collect_analytics(
+ api,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 8, 2),
+ )
+
+ assert [(row["processing_date"], row["_line"]) for row in rows] == [
+ (date(2026, 8, 2), 1),
+ (date(2026, 8, 2), -1),
+ (date(2026, 8, 2), -2),
+ ]
+
+ def test_snapshot_inclusion_is_saved_before_the_first_batch(self) -> None:
+ api = self._ready_api()
+ manager = _FakeManager()
+ session = MagicMock()
+ session.get.side_effect = api.get
+ session.post.side_effect = api.post
+
+ with (
+ patch(f"{MODULE}._make_session", return_value=session),
+ patch(f"{MODULE}._make_segment_download_session", return_value=session),
+ ):
+ rows = cast(
+ Generator[list[dict[str, Any]]],
+ 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,
+ should_use_incremental_field=True,
+ ),
+ )
+ next(rows)
+ rows.close()
+
+ decision = manager.namespaces[_ANALYTICS_SNAPSHOT_DECISION_NAMESPACE]
+ assert decision.saved == [AppStoreConnectResumeConfig(include_snapshot=True)]
+ assert manager.saved == []
+
+ retried_rows = _collect_analytics(
+ self._ready_api(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 8, 1),
+ )
+
+ assert [(row["processing_date"], row["_line"]) for row in retried_rows] == [
+ (date(2026, 8, 1), 1),
+ (date(2026, 8, 2), 1),
+ (date(2026, 8, 2), -1),
+ (date(2026, 8, 2), -2),
+ ]
+ assert decision.cleared == 1
+ assert not decision.can_resume()
+
+
class TestFindAnalyticsReport:
def _resolve(self, endpoint: str, *apple_names: str) -> str | None:
config = APP_STORE_CONNECT_ENDPOINTS[endpoint]
@@ -1713,9 +2106,10 @@ class TestForbiddenErrors:
session = MagicMock()
session.get.return_value = _json_response(_page(requests_page))
session.post.return_value = _forbidden_response(code="FORBIDDEN_ERROR", detail="Admin role required")
+ report_requests = [_flatten_resource(resource) for resource in requests_page]
with pytest.raises(AppStoreConnectPermissionError) as exc:
- _ensure_report_request(session, _FakeTokenProvider(), MagicMock(), "A1")
+ _ensure_report_request(session, _FakeTokenProvider(), MagicMock(), "A1", report_requests)
message = str(exc.value)
assert expected in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py
index 190d26cec1bd..1cb8f5b981e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_restatements.py
@@ -37,12 +37,14 @@ def _analytics_config(name: str) -> AppStoreConnectEndpointConfig:
# One report date restated across vintages, plus snapshot-backfilled history (negative _line):
-# - 2026-06-15 exists only in the snapshot vintage (processing_date 2026-07-02).
-# - 2026-07-01 has a snapshot row at the boundary plus two ongoing vintages (07-03, 07-04);
+# - 2026-06-15 has an older ongoing vintage (06-30) and a newer snapshot-only vintage (07-02).
+# - 2026-07-01 has a snapshot row tied with the newest ongoing vintage (07-04), plus an older
+# ongoing vintage (07-03);
# the (US) tuple is restated in every vintage, the (DE) tuple only in the older ongoing one.
_VINTAGE_ROWS: list[tuple[str, date, int, date, str, int]] = [
("app1", date(2026, 7, 2), -1, date(2026, 6, 15), "US", 7),
- ("app1", date(2026, 7, 2), -2, date(2026, 7, 1), "US", 99),
+ ("app1", date(2026, 6, 30), 1, date(2026, 6, 15), "US", 4),
+ ("app1", date(2026, 7, 4), -2, date(2026, 7, 1), "US", 99),
("app1", date(2026, 7, 3), 1, date(2026, 7, 1), "US", 5),
("app1", date(2026, 7, 3), 2, date(2026, 7, 1), "DE", 3),
("app1", date(2026, 7, 4), 1, date(2026, 7, 1), "US", 6),