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): type App Store Connect columns at ingest (#82973)

jake sciottoc7019a66c753
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 7fed0e8e0203..992e12fe2201 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
@@ -2,11 +2,12 @@ import io
import re
import csv
import gzip
+import math
import time
import hashlib
import tempfile
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
from typing import IO, Any, Optional
from urllib.parse import urlsplit
@@ -239,6 +240,196 @@ def _flatten_resource(resource: dict[str, Any]) -> dict[str, Any]:
return row
+class _ParseFailureCounter:
+ """Counts typed-column values that failed to parse and were stored as null.
+
+ Null-on-unparseable is the deliberate failure policy for typed ingest: a malformed cell must
+ never fail the whole sync, and keeping the raw string instead would flip the column's Arrow
+ type between batches, which degrades the whole column back to text. Failures are logged as one
+ warning per column on its first occurrence (with a truncated sample) plus one aggregate summary
+ per run, never one line per value, so a systematically wrong file stays visible without
+ flooding the logs. The typed columns hold only dates, counts, and prices, so a sample value
+ can't carry personal data.
+ """
+
+ def __init__(self, logger: FilteringBoundLogger, endpoint: str) -> None:
+ self._logger = logger
+ self._endpoint = endpoint
+ self.counts: dict[str, int] = {}
+
+ def record(self, column: str, value: Any) -> None:
+ self.counts[column] = self.counts.get(column, 0) + 1
+ if self.counts[column] == 1:
+ self._logger.warning(
+ f"App Store Connect: unparseable value stored as null. "
+ f"endpoint={self._endpoint}, column={column}, value={str(value)[:40]!r}. "
+ f"Further failures in this column are counted and summarized when the run ends."
+ )
+
+ def flush(self) -> None:
+ if not self.counts:
+ return
+ total = sum(self.counts.values())
+ self._logger.warning(
+ f"App Store Connect: {total} unparseable value(s) stored as null this run. "
+ f"endpoint={self._endpoint}, failures_by_column={self.counts}"
+ )
+
+
+# Name-driven typing for the delimited report families (sales/subscription reports and the
+# analytics report streams), whose files are text with no type information. Columns are typed by
+# NAME wherever they appear rather than per endpoint: Apple varies each report's column set by
+# report type and version, and publishes Standard/Detailed variants of the analytics reports, so a
+# name-driven mapping covers a column in every stream that carries it, including variants added
+# later. Names not listed stay text; identifier-like numeric columns (apple_identifier,
+# app_apple_id, subscription_apple_id, ...) deliberately stay text because they are join keys, not
+# quantities, as do the Detailed-only attribution columns (campaign, page_title, source_info).
+_REPORT_DATE_COLUMNS = frozenset(
+ {
+ # Sales and subscription-event reports carry month-first MM/DD/YYYY dates.
+ "begin_date",
+ "end_date",
+ "event_date",
+ "original_start_date",
+ # Analytics reports carry ISO YYYY-MM-DD dates.
+ "date",
+ "app_download_date",
+ "pre_order_start_date",
+ "pre_order_end_date",
+ }
+)
+_REPORT_INTEGER_COLUMNS = frozenset(
+ {
+ # Sales/subscription reports. Units can be negative: Apple books refunds as negative units.
+ "units",
+ "quantity",
+ "subscribers",
+ "consecutive_paid_periods",
+ "days_before_canceling",
+ "days_canceled",
+ # Analytics reports.
+ "sessions",
+ "unique_devices",
+ "counts",
+ "unique_counts",
+ "crashes",
+ "pre_orders_placed",
+ "pre_orders_canceled",
+ }
+)
+_REPORT_FLOAT_COLUMNS = frozenset(
+ {
+ # Monetary columns are amounts in the row's own currency column (customer_currency,
+ # currency_of_proceeds/proceeds_currency); the numeric type makes them filterable and
+ # summable WITHIN one currency, never across currencies.
+ "customer_price",
+ "developer_proceeds",
+ "total_session_duration",
+ }
+)
+
+_REPORT_DATE_FORMATS = ("%m/%d/%Y", "%Y-%m-%d")
+
+
+def _parse_report_date(text: str) -> date | None:
+ # Apple documents sales-report dates as month-first MM/DD/YYYY for every report type (layouts
+ # are fixed per report version, not localized per territory); analytics report files carry ISO
+ # YYYY-MM-DD. Both formats use strictly numeric strptime directives, which never consult the
+ # process locale, and a day-first reading is never attempted: a value like 13/01/2026 fails to
+ # parse rather than being silently guessed as January 13.
+ for fmt in _REPORT_DATE_FORMATS:
+ try:
+ return datetime.strptime(text, fmt).date()
+ except ValueError:
+ continue
+ return None
+
+
+def _parse_report_int(text: str) -> int | None:
+ # Commas only ever appear as US-style thousands separators in Apple's reports; the decimal
+ # separator is always a point.
+ digits = text.replace(",", "")
+ try:
+ return int(digits)
+ except ValueError:
+ pass
+ try:
+ number = float(digits)
+ except ValueError:
+ return None
+ # A count that arrives as a whole-valued float ("3.0") still lands as an integer. A fractional
+ # or non-finite value nulls rather than silently truncating, and 2**53 bounds the conversion to
+ # where float holds integers exactly.
+ return int(number) if math.isfinite(number) and number.is_integer() and abs(number) <= 2**53 else None
+
+
+def _parse_report_float(text: str) -> float | None:
+ try:
+ number = float(text.replace(",", ""))
+ except ValueError:
+ return None
+ # float() accepts "nan"/"inf", which no report legitimately contains.
+ return number if math.isfinite(number) else None
+
+
+def _parse_iso_datetime(text: str) -> datetime | None:
+ try:
+ parsed = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.astimezone(UTC)
+
+
+def _typed_report_value(column: str, value: Any, failures: _ParseFailureCounter) -> Any:
+ """Parse one delimited-report cell into its typed value, or null when it can't be parsed."""
+ if not isinstance(value, str):
+ return value
+ if column in _REPORT_DATE_COLUMNS:
+ parse: Callable[[str], Any] = _parse_report_date
+ elif column in _REPORT_INTEGER_COLUMNS:
+ parse = _parse_report_int
+ elif column in _REPORT_FLOAT_COLUMNS:
+ parse = _parse_report_float
+ else:
+ return value
+
+ text = value.strip()
+ if not text:
+ # Blank cells are routine (an empty price on a free row, an unset offer duration); they
+ # are nulls, not parse failures.
+ return None
+ parsed = parse(text)
+ if parsed is None:
+ failures.record(column, value)
+ return parsed
+
+
+def _typed_json_api_row(row: dict[str, Any], failures: _ParseFailureCounter) -> dict[str, Any]:
+ """Convert a JSON:API row's ISO 8601 date-time attributes to UTC datetimes, in place.
+
+ Apple's JSON:API resources carry every timestamp in an attribute named `...Date` (createdDate,
+ uploadedDate, expirationDate, earliestReleaseDate, lastModifiedDate), so the rule is
+ suffix-driven rather than a per-endpoint column list and covers attributes added later. Values
+ normalize to UTC because Apple emits varying local offsets and one column must stay in one
+ zone. Only table rows come through here; the resources the sync reads internally
+ (analyticsReportInstances and friends) keep their raw strings.
+ """
+ for key, value in row.items():
+ if not key.endswith("Date") or not isinstance(value, str):
+ continue
+ text = value.strip()
+ if not text:
+ row[key] = None
+ continue
+ parsed = _parse_iso_datetime(text)
+ if parsed is None:
+ failures.record(key, value)
+ row[key] = parsed
+ return row
+
+
@dataclasses.dataclass(frozen=True, kw_only=True)
class _Page:
"""One JSON:API page. ``resources`` and ``included`` share a type, so construction is
@@ -291,12 +482,14 @@ def _iter_pages(
page_params = None
-def _page_rows(config: AppStoreConnectEndpointConfig, page: _Page) -> list[dict[str, Any]]:
+def _page_rows(
+ config: AppStoreConnectEndpointConfig, page: _Page, failures: _ParseFailureCounter
+) -> list[dict[str, Any]]:
"""Rows for one page: the flattened ``data`` resources, or, for endpoints configured to read a
related resource off another collection's pages, the flattened ``included`` resources of that type.
"""
if config.rows_from_included_type is None:
- return [_flatten_resource(resource) for resource in page.resources]
+ return [_typed_json_api_row(_flatten_resource(resource), failures) for resource in page.resources]
# JSON:API full linkage guarantees every included resource is referenced from a primary
# resource's relationship linkage; that linkage is where each row's parent id comes from.
@@ -320,7 +513,7 @@ def _page_rows(config: AppStoreConnectEndpointConfig, page: _Page) -> list[dict[
continue
row = _flatten_resource(resource)
row[config.included_parent_column] = parent_ids.get(str(resource.get("id")))
- rows.append(row)
+ rows.append(_typed_json_api_row(row, failures))
return rows
@@ -347,6 +540,7 @@ def _get_collection(
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
+ failures: _ParseFailureCounter,
) -> Iterator[list[dict[str, Any]]]:
resume = _load_resume(manager)
resumed_url = resume.next_url if resume is not None else None
@@ -355,7 +549,7 @@ def _get_collection(
params: dict[str, Any] | None = None if resumed_url else dict(config.params)
for page in _iter_pages(session, token_provider, logger, url, params):
- rows = _page_rows(config, page)
+ rows = _page_rows(config, page, failures)
if rows:
yield rows
# Save AFTER yielding so a crash re-fetches the page we just emitted rather than skipping it;
@@ -370,6 +564,7 @@ def _get_app_fanout(
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
+ failures: _ParseFailureCounter,
) -> Iterator[list[dict[str, Any]]]:
app_ids = _list_app_ids(session, token_provider, logger)
resume = _load_resume(manager)
@@ -393,7 +588,7 @@ def _get_app_fanout(
params = dict(config.params)
for page in _iter_pages(session, token_provider, logger, url, params):
- rows = _page_rows(config, page)
+ rows = _page_rows(config, page, failures)
if rows:
for row in rows:
row["app_id"] = app_id
@@ -434,7 +629,7 @@ def _decompress_report(payload: bytes) -> str:
return raw.decode("utf-8-sig", errors="replace")
-def _parse_report(payload: bytes, report_date: date) -> list[dict[str, Any]]:
+def _parse_report(payload: bytes, report_date: date, failures: _ParseFailureCounter) -> list[dict[str, Any]]:
reader = csv.reader(io.StringIO(_decompress_report(payload)), delimiter="\t")
try:
header = next(reader)
@@ -442,16 +637,16 @@ def _parse_report(payload: bytes, report_date: date) -> list[dict[str, Any]]:
return []
columns = [_normalize_report_column(column) for column in header]
- report_date_str = report_date.isoformat()
rows: list[dict[str, Any]] = []
for values in reader:
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)
+ column: _typed_report_value(column, values[index] if index < len(values) else None, failures)
+ for index, column in enumerate(columns)
}
- row["report_date"] = report_date_str
+ row["report_date"] = report_date
# 1-based position in the file. A published day's report is immutable, so (report_date, _line)
# is a stable unique key and re-reading a day merges instead of duplicating.
row["_line"] = len(rows) + 1
@@ -467,6 +662,7 @@ def _fetch_report(
logger: FilteringBoundLogger,
vendor_number: str,
report_date: date,
+ failures: _ParseFailureCounter,
) -> list[dict[str, Any]]:
params: dict[str, str] = {
"filter[frequency]": config.report_frequency,
@@ -494,7 +690,7 @@ def _fetch_report(
# same condition instead (see `missing_report_status_codes`).
return []
- return _parse_report(response.content, report_date)
+ return _parse_report(response.content, report_date, failures)
def _get_sales_report(
@@ -503,6 +699,7 @@ def _get_sales_report(
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
+ failures: _ParseFailureCounter,
vendor_number: str | None,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
@@ -533,7 +730,7 @@ def _get_sales_report(
report_date = start
days_fetched = 0
while report_date <= end and days_fetched < SALES_REPORT_MAX_DAYS_PER_RUN:
- rows = _fetch_report(session, config, token_provider, logger, vendor_number, report_date)
+ rows = _fetch_report(session, config, token_provider, logger, vendor_number, report_date, failures)
if rows:
yield rows
@@ -790,7 +987,9 @@ def _open_segment_text(spool: IO[bytes]) -> IO[str]:
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]]:
+def _iter_segment_rows(
+ text: IO[str], processing_date: date, line_start: int, failures: _ParseFailureCounter
+) -> Iterator[dict[str, Any]]:
header_line = text.readline()
if not header_line.strip():
return
@@ -799,16 +998,16 @@ def _iter_segment_rows(text: IO[str], processing_date: date, line_start: int) ->
# 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)
+ column: _typed_report_value(column, values[index] if index < len(values) else None, failures)
+ for index, column in enumerate(columns)
}
- row["processing_date"] = processing_date_str
+ row["processing_date"] = processing_date
# 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.
@@ -824,6 +1023,7 @@ def _get_analytics_report(
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
+ failures: _ParseFailureCounter,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
) -> Iterator[list[dict[str, Any]]]:
@@ -903,7 +1103,7 @@ def _get_analytics_report(
spool = _download_segment(logger, segment)
try:
with _open_segment_text(spool) as text:
- for row in _iter_segment_rows(text, processing_date, line):
+ for row in _iter_segment_rows(text, processing_date, line, failures):
row["app_id"] = app_id
line = row["_line"]
batch.append(row)
@@ -963,36 +1163,44 @@ def get_rows(
config = APP_STORE_CONNECT_ENDPOINTS[endpoint]
session = _make_session(private_key)
token_provider = AppStoreConnectTokenProvider(issuer_id, key_id, private_key)
+ failures = _ParseFailureCounter(logger, endpoint)
- if config.kind == "collection":
- 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,
- config,
- token_provider,
- logger,
- resumable_source_manager,
- vendor_number,
- should_use_incremental_field,
- db_incremental_field_last_value,
- )
+ try:
+ if config.kind == "collection":
+ yield from _get_collection(session, config, token_provider, logger, resumable_source_manager, failures)
+ elif config.kind == "app_fanout":
+ yield from _get_app_fanout(session, config, token_provider, logger, resumable_source_manager, failures)
+ 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,
+ failures,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ else: # "sales_report"
+ yield from _get_sales_report(
+ session,
+ config,
+ token_provider,
+ logger,
+ resumable_source_manager,
+ failures,
+ vendor_number,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ finally:
+ # The unparseable-value summary rides the generator's teardown so it also surfaces for a
+ # run that fails or is abandoned mid-walk.
+ failures.flush()
# Walked to completion, so drop the checkpoint — leaving it would let a later attempt on this job
# resume mid-stream instead of restarting cleanly.
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 70bb9cb09dc7..34ad8a6029db 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
@@ -154,7 +154,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "One row of Apple's daily Sales and Trends summary report: units and developer proceeds per SKU, territory and product type.",
"docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",
"columns": {
- "report_date": "Date the report covers, as `YYYY-MM-DD`.",
+ "report_date": "Date the report covers.",
"_line": "1-based line number within that date's report file, used with report_date as the row key.",
"provider": "Provider of the content, normally `APPLE`.",
"provider_country": "Country of the provider.",
@@ -164,14 +164,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"version": "Version of the app the transaction applied to.",
"product_type_identifier": "Code describing the transaction type, such as a first download, update or in-app purchase.",
"units": "Number of units for this row; negative values are refunds.",
- "developer_proceeds": "Amount paid to you per unit, in the currency of proceeds.",
+ "developer_proceeds": "Amount paid to you per unit, in the row's currency_of_proceeds. Sum it only within a single currency.",
"begin_date": "First date covered by the row.",
"end_date": "Last date covered by the row.",
"customer_currency": "Currency the customer was charged in.",
"country_code": "App Store territory the transaction happened in.",
"currency_of_proceeds": "Currency your proceeds are reported in.",
"apple_identifier": "Apple's numeric identifier for the app.",
- "customer_price": "Price the customer paid, in customer currency.",
+ "customer_price": "Price the customer paid, in the row's customer_currency. Amounts in different currencies are not comparable, so sum this only within a single currency.",
"promo_code": "Promotional or offer code applied to the transaction.",
"parent_identifier": "SKU of the parent app for an in-app purchase row.",
"subscription": "Whether the row relates to a subscription product.",
@@ -190,7 +190,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "One row of Apple's daily Subscription summary report: active, paid and trial subscription counts by state and territory.",
"docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",
"columns": {
- "report_date": "Date the report covers, as `YYYY-MM-DD`.",
+ "report_date": "Date the report covers.",
"_line": "1-based line number within that date's report file, used with report_date as the row key.",
"app_name": "Name of the app the subscription belongs to.",
"app_apple_id": "Apple's numeric identifier for the app.",
@@ -200,9 +200,9 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"standard_subscription_duration": "Billing duration of the subscription, such as 1 Month.",
"promotional_offer_name": "Name of the promotional offer applied, if any.",
"promotional_offer_id": "Identifier of the promotional offer applied, if any.",
- "customer_price": "Price the customer pays per period, in customer currency.",
+ "customer_price": "Price the customer pays per period, in the row's customer_currency. Amounts in different currencies are not comparable, so sum this only within a single currency.",
"customer_currency": "Currency the customer is charged in.",
- "developer_proceeds": "Proceeds paid to you per period.",
+ "developer_proceeds": "Proceeds paid to you per period, in the row's proceeds_currency. Sum it only within a single currency.",
"proceeds_currency": "Currency your proceeds are reported in.",
"preserved_pricing": "Whether legacy preserved pricing applies.",
"proceeds_reason": "Reason the applied proceeds rate was used.",
@@ -217,7 +217,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "One row of Apple's daily Subscription Event report: counts of subscription lifecycle events such as renewals, cancellations and plan changes.",
"docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",
"columns": {
- "report_date": "Date the report covers, as `YYYY-MM-DD`.",
+ "report_date": "Date the report covers.",
"_line": "1-based line number within that date's report file, used with report_date as the row key.",
"event_date": "Date the events happened.",
"event": "Lifecycle event counted, such as Subscribe, Renew, Cancel or Reactivate.",
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 090b5349b20a..5f1d2b68eb56 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,6 +1,6 @@
import gzip
import hashlib
-from datetime import date, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import Any
import pytest
@@ -27,7 +27,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_
_normalize_report_column,
_Page,
_parse_report,
+ _ParseFailureCounter,
_require_api_url,
+ _typed_report_value,
app_store_connect_source,
check_credentials,
get_rows,
@@ -168,6 +170,7 @@ def _collect(
manager: _FakeManager,
*,
vendor_number: str | None = None,
+ logger: MagicMock | None = None,
**kwargs: Any,
) -> list[dict[str, Any]]:
session = MagicMock()
@@ -180,7 +183,7 @@ def _collect(
private_key=PRIVATE_KEY_PEM,
vendor_number=vendor_number,
endpoint=endpoint,
- logger=MagicMock(),
+ logger=logger if logger is not None else MagicMock(),
resumable_source_manager=manager,
**kwargs,
):
@@ -514,6 +517,39 @@ class TestReviewResponses:
assert response.partition_keys is None
+class TestJsonApiDateTimeColumns:
+ def test_iso_datetime_attributes_become_utc_datetimes(self) -> None:
+ api = _FakeApi(
+ {
+ f"{BASE_URL}/v1/betaGroups": _page(
+ [
+ _resource("betaGroups", "1", name="Zulu", createdDate="2026-03-04T10:00:00Z"),
+ _resource("betaGroups", "2", name="Offset", createdDate="2026-03-04T12:30:00+02:00"),
+ _resource("betaGroups", "3", name="Fractional", createdDate="2026-03-04T10:00:00.123456-05:00"),
+ ]
+ )
+ }
+ )
+
+ rows = _collect("beta_groups", api, _FakeManager())
+
+ # Apple emits varying local offsets; normalizing to UTC keeps one column in one zone.
+ assert [row["createdDate"] for row in rows] == [
+ datetime(2026, 3, 4, 10, 0, tzinfo=UTC),
+ datetime(2026, 3, 4, 10, 30, tzinfo=UTC),
+ datetime(2026, 3, 4, 15, 0, 0, 123456, tzinfo=UTC),
+ ]
+ assert [row["name"] for row in rows] == ["Zulu", "Offset", "Fractional"]
+
+ def test_unparseable_datetime_is_nulled_rather_than_failing_the_sync(self) -> None:
+ api = _FakeApi({f"{BASE_URL}/v1/betaGroups": _page([_resource("betaGroups", "1", createdDate="last Tuesday")])})
+
+ rows = _collect("beta_groups", api, _FakeManager())
+
+ assert rows[0]["createdDate"] is None
+ assert rows[0]["id"] == "1"
+
+
APPS_URL = f"{BASE_URL}/v1/apps"
REQUESTS_URL = f"{BASE_URL}/v1/apps/A1/analyticsReportRequests"
CREATE_REQUEST_URL = f"{BASE_URL}/v1/analyticsReportRequests"
@@ -653,9 +689,9 @@ class TestAnalyticsReportStreams:
# _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"),
+ ("A1", date(2026, 8, 1), 1, 5),
+ ("A1", date(2026, 8, 1), 2, 7),
+ ("A1", date(2026, 8, 2), 1, 2),
]
assert rows[0]["app_apple_identifier"] == "123"
assert api.posts == []
@@ -709,7 +745,7 @@ class TestAnalyticsReportStreams:
db_incremental_field_last_value=date(2026, 8, 2),
)
- assert [row["processing_date"] for row in rows] == ["2026-08-02"]
+ assert [row["processing_date"] for row in rows] == [date(2026, 8, 2)]
assert _segments_url("I1") not in [url for url, _ in api.calls]
def test_resume_bookmark_floors_the_walk(self) -> None:
@@ -723,7 +759,7 @@ class TestAnalyticsReportStreams:
rows = _collect_analytics(api, manager)
- assert [row["processing_date"] for row in rows] == ["2026-08-02"]
+ assert [row["processing_date"] for row in rows] == [date(2026, 8, 2)]
assert _segments_url("I1") not in [url for url, _ in api.calls]
def test_unavailable_report_degrades_the_table_without_failing(self) -> None:
@@ -793,7 +829,7 @@ class TestAnalyticsReportStreams:
rows = _collect_analytics(api, _FakeManager())
- assert [(row["date"], row["sessions"]) for row in rows] == [("2026-08-01", "5")]
+ assert [(row["date"], row["sessions"]) for row in rows] == [(date(2026, 8, 1), 5)]
def test_per_run_instance_cap_saves_a_resumable_bookmark(self) -> None:
payload = _gzip_csv("Date,Sessions\n2026-08-01,5\n")
@@ -807,7 +843,7 @@ class TestAnalyticsReportStreams:
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 [row["processing_date"] for row in rows] == [date(2026, 8, 1)]
assert manager.saved[-1].processing_date == "2026-08-02"
def test_dates_walk_in_order_across_apps(self) -> None:
@@ -842,11 +878,42 @@ class TestAnalyticsReportStreams:
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"),
+ ("A1", date(2026, 8, 1)),
+ ("A2", date(2026, 8, 2)),
+ ("A1", date(2026, 8, 3)),
]
+ def test_columns_are_typed_by_name_and_attribution_columns_stay_text(self) -> None:
+ # Typing is column-name-driven rather than per-endpoint: Apple publishes Standard and
+ # Detailed variants of each report with differing column sets, so any stream carrying a
+ # known date or metric column gets it typed, while the Detailed-only attribution columns
+ # (campaign, page_title, source_info) stay text by omission from the mapping.
+ payload = _gzip_csv(
+ "Date,App Name,App Download Date,Campaign,Page Title,Source Info,"
+ "Sessions,Total Session Duration,Unique Devices\n"
+ "2026-08-01,Example,2026-07-15,summer-launch,Alternate page,com.example.social,5,321.5,4\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},
+ )
+
+ row = _collect_analytics(api, _FakeManager())[0]
+
+ assert row["processing_date"] == date(2026, 8, 1)
+ assert row["date"] == date(2026, 8, 1)
+ assert row["app_download_date"] == date(2026, 7, 15)
+ assert row["sessions"] == 5 and isinstance(row["sessions"], int)
+ assert row["total_session_duration"] == 321.5
+ assert row["unique_devices"] == 4
+ assert (row["campaign"], row["page_title"], row["source_info"]) == (
+ "summer-launch",
+ "Alternate page",
+ "com.example.social",
+ )
+ assert row["app_name"] == "Example"
+
def test_analytics_source_response_checkpoints_ascending(self) -> None:
response = app_store_connect_source(
issuer_id="issuer",
@@ -895,6 +962,68 @@ class TestFindAnalyticsReport:
assert self._resolve("analytics_app_store_preorders", "App Store Pre-orders Standard") == "REP1"
+def _failures() -> _ParseFailureCounter:
+ return _ParseFailureCounter(MagicMock(), "sales_reports")
+
+
+class TestTypedReportValues:
+ @parameterized.expand(
+ [
+ ("month_first_date", "begin_date", "03/04/2026", date(2026, 3, 4)),
+ ("single_digit_month_and_day", "begin_date", "3/4/2026", date(2026, 3, 4)),
+ ("iso_analytics_date", "date", "2026-03-04", date(2026, 3, 4)),
+ # 02/03/2026 must read as February 3, never March 2: the parse is month-first by
+ # Apple's report spec, independent of any locale or dayfirst heuristic.
+ ("ambiguous_date_reads_month_first", "event_date", "02/03/2026", date(2026, 2, 3)),
+ ("padded_date", "end_date", " 03/04/2026 ", date(2026, 3, 4)),
+ ("count", "units", "3", 3),
+ ("negative_refund_count", "units", "-2", -2),
+ ("count_with_thousands_separator", "units", "1,234", 1234),
+ ("whole_valued_float_count", "units", "3.0", 3),
+ ("price", "customer_price", "0.99", 0.99),
+ ("price_with_thousands_separator", "customer_price", "1,234.56", 1234.56),
+ ("unmapped_column_untouched", "promo_code", "0099", "0099"),
+ ("identifier_stays_text", "apple_identifier", "123456789", "123456789"),
+ ]
+ )
+ def test_mapped_columns_parse_and_unmapped_stay_text(
+ self, _name: str, column: str, value: str, expected: Any
+ ) -> None:
+ failures = _failures()
+
+ parsed = _typed_report_value(column, value, failures)
+
+ assert parsed == expected
+ assert type(parsed) is type(expected)
+ assert failures.counts == {}
+
+ @parameterized.expand([("empty", "begin_date", ""), ("whitespace", "units", " ")])
+ def test_blank_cells_are_null_but_not_counted_as_failures(self, _name: str, column: str, value: str) -> None:
+ failures = _failures()
+
+ assert _typed_report_value(column, value, failures) is None
+ assert failures.counts == {}
+
+ @parameterized.expand(
+ [
+ # A heuristic parser would read 13/01/2026 as January 13 once the month overflows;
+ # rejecting it keeps a mis-formatted file loud instead of silently day-first.
+ ("day_first_date", "begin_date", "13/01/2026"),
+ ("nonsense_date", "begin_date", "garbage"),
+ ("out_of_range_date", "begin_date", "04/31/2026"),
+ ("non_numeric_count", "units", "N/A"),
+ ("fractional_count", "units", "2.5"),
+ ("currency_prefixed_price", "customer_price", "USD 0.99"),
+ ("non_finite_price", "customer_price", "inf"),
+ ]
+ )
+ def test_unparseable_values_are_null_and_counted(self, _name: str, column: str, value: str) -> None:
+ failures = _failures()
+
+ assert _typed_report_value(column, value, failures) is None
+ assert failures.counts == {column: 1}
+
+
class TestReportColumnNames:
@parameterized.expand(
[
@@ -912,26 +1041,40 @@ class TestReportColumnNames:
class TestParseReport:
- def test_gzipped_tsv_becomes_keyed_rows(self) -> None:
- tsv = "Provider\tSKU\tUnits\tDeveloper Proceeds\nAPPLE\tacme-pro\t3\t2.10\nAPPLE\tacme-lite\t1\t0.70\n"
+ def test_gzipped_tsv_becomes_keyed_and_typed_rows(self) -> None:
+ tsv = (
+ "Provider\tSKU\tUnits\tCustomer Price\tDeveloper Proceeds\tBegin Date\tEnd Date\tApple Identifier\n"
+ "APPLE\tacme-pro\t3\t2.99\t2.10\t03/04/2026\t03/04/2026\t123456789\n"
+ "APPLE\tacme-lite\t1\t0.99\t0.70\t03/04/2026\t03/04/2026\t123456789\n"
+ )
- rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))
+ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4), _failures())
+ # Dates and quantities arrive typed; identifier-like numeric columns stay text because
+ # they are join keys, not quantities.
assert rows == [
{
"provider": "APPLE",
"sku": "acme-pro",
- "units": "3",
- "developer_proceeds": "2.10",
- "report_date": "2026-03-04",
+ "units": 3,
+ "customer_price": 2.99,
+ "developer_proceeds": 2.10,
+ "begin_date": date(2026, 3, 4),
+ "end_date": date(2026, 3, 4),
+ "apple_identifier": "123456789",
+ "report_date": date(2026, 3, 4),
"_line": 1,
},
{
"provider": "APPLE",
"sku": "acme-lite",
- "units": "1",
- "developer_proceeds": "0.70",
- "report_date": "2026-03-04",
+ "units": 1,
+ "customer_price": 0.99,
+ "developer_proceeds": 0.70,
+ "begin_date": date(2026, 3, 4),
+ "end_date": date(2026, 3, 4),
+ "apple_identifier": "123456789",
+ "report_date": date(2026, 3, 4),
"_line": 2,
},
]
@@ -939,26 +1082,26 @@ class TestParseReport:
def test_blank_lines_are_skipped_so_line_numbers_stay_dense(self) -> None:
tsv = "SKU\tUnits\nacme-pro\t3\n\n \nacme-lite\t1\n"
- rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))
+ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4), _failures())
assert [(row["sku"], row["_line"]) for row in rows] == [("acme-pro", 1), ("acme-lite", 2)]
def test_short_rows_are_padded_with_none(self) -> None:
tsv = "SKU\tUnits\tDevice\nacme-pro\t3\n"
- rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))
+ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4), _failures())
assert rows[0]["device"] is None
def test_uncompressed_payload_is_parsed_too(self) -> None:
# urllib3 unwraps a `Content-Encoding: gzip` body before we see it.
- rows = _parse_report(b"SKU\tUnits\nacme-pro\t3\n", date(2026, 3, 4))
+ rows = _parse_report(b"SKU\tUnits\nacme-pro\t3\n", date(2026, 3, 4), _failures())
assert rows[0]["sku"] == "acme-pro"
@parameterized.expand([("empty", b""), ("header_only", b"SKU\tUnits\n")])
def test_reports_without_data_rows_yield_nothing(self, _name: str, payload: bytes) -> None:
- assert _parse_report(payload, date(2026, 3, 4)) == []
+ assert _parse_report(payload, date(2026, 3, 4), _failures()) == []
class TestSalesReports:
@@ -983,7 +1126,10 @@ class TestSalesReports:
)
# Yesterday (2026-03-04) is the newest date Apple has published; 03-03 404s and is skipped.
- assert [(row["report_date"], row["units"]) for row in rows] == [("2026-03-02", "1"), ("2026-03-04", "2")]
+ assert [(row["report_date"], row["units"]) for row in rows] == [
+ (date(2026, 3, 2), 1),
+ (date(2026, 3, 4), 2),
+ ]
assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-02", "2026-03-03", "2026-03-04"]
@freeze_time("2026-03-05 09:00:00")
@@ -1002,7 +1148,7 @@ class TestSalesReports:
db_incremental_field_last_value=date(2026, 3, 2),
)
- assert [(row["report_date"], row["units"]) for row in rows] == [("2026-03-04", "1")]
+ assert [(row["report_date"], row["units"]) for row in rows] == [(date(2026, 3, 4), 1)]
assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-02", "2026-03-03", "2026-03-04"]
@freeze_time("2026-03-05 09:00:00")
@@ -1028,6 +1174,31 @@ class TestSalesReports:
)
)
+ @freeze_time("2026-03-05 09:00:00")
+ def test_unparseable_values_are_nulled_with_counted_warnings(self) -> None:
+ # Three bad units and one bad date must produce one first-occurrence warning per column
+ # plus one end-of-run summary, never one log line per value.
+ tsv = "SKU\tUnits\tBegin Date\nsku-1\tN/A\t03/04/2026\nsku-2\tN/A\t04/31/2026\nsku-3\tN/A\t03/04/2026\n"
+ api = self._api({"2026-03-04": tsv})
+ logger = MagicMock()
+
+ rows = _collect(
+ "sales_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ logger=logger,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 4),
+ )
+
+ assert [row["units"] for row in rows] == [None, None, None]
+ assert [row["begin_date"] for row in rows] == [date(2026, 3, 4), None, date(2026, 3, 4)]
+ warning_messages = [call.args[0] for call in logger.warning.call_args_list]
+ assert len(warning_messages) == 3
+ assert "'units': 3" in warning_messages[-1]
+ assert "'begin_date': 1" in warning_messages[-1]
+
@freeze_time("2026-03-05 09:00:00")
def test_sends_the_report_type_filters_from_settings(self) -> None:
api = self._api({"2026-03-04": "SKU\tUnits\nacme\t1\n"})