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.

fix(warehouse-sources): stop App Store Connect reports swallowing 400s (#86126)

posthog[bot]25dbb7f3cd15
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 99bb579d0eba..b653976ba043 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -616,7 +616,12 @@ async def run_post_load_operations(
1, 2 and 4 and returns None.
"""
if delta_table_ref is None or await delta_table_ref.get_delta_table() is None:
- logger.debug("No deltalake table, not continuing with post-run ops")
+ # A clean run that wrote zero rows creates no delta table, so there is nothing to publish or
+ # register. Finalize the sync bookkeeping anyway: without it last_synced_at and
+ # initial_sync_complete never advance, leaving the schema stuck "completed but not
+ # initial-synced" on every subsequent run.
+ logger.debug("No deltalake table; finalizing bookkeeping for a zero-row run")
+ await _finalize_sync_bookkeeping(job, schema, resource, last_incremental_field_value, logger)
return None
# Detect CDC companion writes — scd2_append writes always go to the companion _cdc resource.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index fbfc488568c1..ef179acd8132 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -340,6 +340,40 @@ class TestCdcCompanionSeeding:
assert seed.await_count == (1 if expect_seed else 0)
+class TestZeroRowRunFinalizesBookkeeping:
+ @pytest.mark.asyncio
+ async def test_no_delta_table_still_sets_initial_sync_complete(self) -> None:
+ # A clean run that wrote zero rows creates no delta table. Post-load used to bail before the
+ # bookkeeping, so initial_sync_complete never advanced and the schema stayed "completed but
+ # not initial-synced" forever. It must be finalized even with no table to register.
+ schema = _make_schema(is_cdc=False, initial_sync_complete=False)
+ job = MagicMock()
+ job.id = uuid.uuid4()
+ job.team_id = schema.team_id
+ logger = MagicMock(debug=MagicMock(), adebug=AsyncMock())
+ helper = MagicMock(get_delta_table=AsyncMock(return_value=None))
+
+ set_complete = AsyncMock()
+ with (
+ patch(f"{_LOAD_MODULE}.set_initial_sync_complete", set_complete),
+ patch(f"{_PIPELINE_SYNC_MODULE}.update_last_synced_at", AsyncMock()) as synced,
+ ):
+ result = await run_post_load_operations(
+ job=job,
+ schema=schema,
+ source=MagicMock(),
+ delta_table_ref=helper,
+ row_count=0,
+ table_schema_dict={},
+ resource_name="subscription_reports",
+ logger=logger,
+ )
+
+ assert result is None
+ set_complete.assert_awaited_once()
+ synced.assert_awaited_once()
+
+
class TestGetIncrementalFieldValue:
def _schema(self, incremental_field: str, sync_type: str = ExternalDataSchema.SyncType.INCREMENTAL) -> MagicMock:
schema = MagicMock()
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 70bd62ca86f1..0a6fa24ebf7e 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
@@ -82,6 +82,14 @@ class AppStoreConnectPermissionError(Exception):
"""A 403 from App Store Connect: the key's role can't perform this call. Non-retryable."""
+class AppStoreConnectReportError(Exception):
+ """Apple rejected a report request, and the rejection is not its "no data for this date" quirk.
+
+ Retrying can't fix a malformed request or a vendor number Apple doesn't know, so this fails the
+ schema loudly instead of reading as a quiet account across the whole lookback window.
+ """
+
+
# 403 on a report or resource read. The key's role can't read this data, so the fix is a role
# that can. `AppStoreConnectSource.get_non_retryable_errors` matches on this text to fail fast.
APP_STORE_CONNECT_READ_FORBIDDEN_ERROR = (
@@ -112,6 +120,17 @@ APP_STORE_CONNECT_MISSING_VENDOR_NUMBER_ERROR = (
"Add it in the source settings, then run the sync again."
)
+# Apple rejected a report request as malformed — the report type, sub type, or version this source
+# asks for no longer matches its specification. Raised with Apple's own words appended.
+APP_STORE_CONNECT_INVALID_REPORT_ERROR = "App Store Connect rejected a report request as invalid"
+
+# The vendor number in the source settings is one Apple doesn't know. Every retry fails identically
+# until the user corrects it, so this fails fast rather than burning the activity's retry budget.
+APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR = (
+ "App Store Connect does not recognize the vendor number this source is configured with. "
+ "Check the vendor number in the source settings, then run the sync again."
+)
+
@frozen
class _AppleApiError:
@@ -741,6 +760,122 @@ def _parse_report(payload: bytes, report_date: date, failures: _ParseFailureCoun
return rows
+# A subscription-family report day with no data comes back as a 400 whose body carries one of these
+# markers. A 400 matching none of them, and not the vendor-number marker below, is a genuinely
+# malformed request rather than a quiet day.
+_EMPTY_REPORT_400_MARKERS = (
+ "there were no results",
+ "no results for the request",
+)
+
+# Apple's long-standing misleading wording for an empty subscription day, which it also returns for a
+# vendor number it doesn't know. Ambiguous on its own, so `_VendorNumberCheck` settles it.
+_VENDOR_NUMBER_400_MARKER = "invalid vendor number"
+
+
+def _apple_error_text(error: _AppleApiError) -> str:
+ """Apple's words as one folded string, for matching against the markers above."""
+ return " ".join(part for part in (error.code, error.title, error.detail) if part).casefold()
+
+
+class _ToleratedReportDays:
+ """Counts report days Apple answered with a tolerated "no data" status, keeping one sample error.
+
+ A 404 is Apple's "no activity for this date" for the SALES report; the subscription report
+ families return a 400 for the same condition instead, and Apple words that 400 the same way it
+ words a genuinely bad request. A whole run of tolerated days that never produced a row is logged
+ when the walk ends, so an operator can tell an account with no data for this report from a
+ request Apple keeps rejecting, rather than reading both as a quiet account.
+ """
+
+ def __init__(self, logger: FilteringBoundLogger, config: AppStoreConnectEndpointConfig) -> None:
+ self._logger = logger
+ self._config = config
+ self.days_fetched = 0
+ self.days_tolerated = 0
+ self.days_with_rows = 0
+ self._sample_detail = ""
+
+ def record_tolerated(self, sample: str = "") -> None:
+ self.days_tolerated += 1
+ if sample and not self._sample_detail:
+ self._sample_detail = sample
+
+ def flush(self) -> None:
+ if self.days_fetched == 0 or self.days_with_rows > 0:
+ return
+ self._logger.warning(
+ f"App Store Connect: the {self._config.name} run produced no rows. "
+ f"days_requested={self.days_fetched}, days_tolerated_as_empty={self.days_tolerated}, "
+ f"report_type={self._config.report_type}, report_sub_type={self._config.report_sub_type}, "
+ f"report_version={self._config.report_version or 'unset'}, "
+ f"sample_apple_error={self._sample_detail or 'none'}. This is either an account with no "
+ f"data for this report or a request Apple keeps rejecting; check the report filters if "
+ f"you expected data."
+ )
+
+
+class _VendorNumberCheck:
+ """Resolves once per run whether Apple knows the configured vendor number.
+
+ Apple answers a subscription-family day with no data and a vendor number it doesn't know with the
+ same "Invalid vendor number specified" 400, so that response alone cannot tell a quiet account
+ from a typo. The SALES report separates them: it answers 404 for a known vendor with no data on
+ the date, and keeps the vendor-number 400 for one it doesn't know. An inconclusive check — a key
+ without a Sales role, a network failure — reads as known, so a sync never fails on the check
+ itself and the all-empty run warning stays the backstop.
+ """
+
+ def __init__(
+ self,
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+ vendor_number: str,
+ ) -> None:
+ self._session = session
+ self._token_provider = token_provider
+ self._logger = logger
+ self._vendor_number = vendor_number
+ self._known: bool | None = None
+
+ def known(self, report_date: date) -> bool:
+ if self._known is None:
+ self._known = self._probe(report_date)
+ return self._known
+
+ def _probe(self, report_date: date) -> bool:
+ sales = APP_STORE_CONNECT_ENDPOINTS["sales_reports"]
+ try:
+ response = _get(
+ self._session,
+ f"{BASE_URL}/v1/salesReports",
+ token_provider=self._token_provider,
+ logger=self._logger,
+ params={
+ "filter[frequency]": sales.report_frequency,
+ "filter[reportDate]": report_date.isoformat(),
+ "filter[reportType]": sales.report_type,
+ "filter[reportSubType]": sales.report_sub_type,
+ "filter[version]": sales.report_version,
+ "filter[vendorNumber]": self._vendor_number,
+ },
+ accept=REPORT_ACCEPT,
+ timeout=REPORT_TIMEOUT_SECONDS,
+ tolerate=(400, 404),
+ )
+ except Exception as e:
+ self._logger.warning(
+ f"App Store Connect: could not check the vendor number against the sales report, "
+ f"treating it as known. error={e}"
+ )
+ return True
+
+ if response.status_code != 400:
+ return True
+ return _VENDOR_NUMBER_400_MARKER not in _apple_error_text(_parse_apple_error(response))
+
+
def _fetch_report(
session: requests.Session,
config: AppStoreConnectEndpointConfig,
@@ -749,6 +884,8 @@ def _fetch_report(
vendor_number: str,
report_date: date,
failures: _ParseFailureCounter,
+ tolerated: _ToleratedReportDays,
+ vendor_check: _VendorNumberCheck,
) -> list[dict[str, Any]]:
params: dict[str, str] = {
"filter[frequency]": config.report_frequency,
@@ -771,9 +908,37 @@ def _fetch_report(
tolerate=config.missing_report_status_codes,
)
if response.status_code in config.missing_report_status_codes:
- # Apple 404s any date with no activity at all — normal for quiet days and for dates before the
- # app shipped — so a missing day is not an error. Subscription-family report types 400 for the
- # same condition instead (see `missing_report_status_codes`).
+ # A 404 is always Apple's "no activity for this date" — normal for quiet days and for dates
+ # before the app shipped. A tolerated 400 is the subscription-family equivalent, but Apple
+ # reuses 400 for a genuinely malformed request and for a vendor number it doesn't know too,
+ # so read the body: only a day Apple really has no data for is tolerated and counted, and
+ # anything else fails loudly instead of masquerading as a quiet account across the lookback.
+ if response.status_code == 400:
+ apple_error = _parse_apple_error(response)
+ text = _apple_error_text(apple_error)
+ if _VENDOR_NUMBER_400_MARKER in text:
+ if not vendor_check.known(report_date):
+ logger.error(
+ f"App Store Connect rejected the vendor number: endpoint={config.name}, "
+ f"status=400, apple_error={text!r}"
+ )
+ raise AppStoreConnectReportError(
+ f"{APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR} ({_apple_error_suffix(apple_error, 400)})"
+ )
+ elif not any(marker in text for marker in _EMPTY_REPORT_400_MARKERS):
+ logger.error(
+ f"App Store Connect report request rejected as invalid: endpoint={config.name}, "
+ f"status=400, apple_error={text!r}, report_type={config.report_type}, "
+ f"report_sub_type={config.report_sub_type}, report_version={config.report_version or 'unset'}"
+ )
+ raise AppStoreConnectReportError(
+ f"{APP_STORE_CONNECT_INVALID_REPORT_ERROR}: the report type, sub type, or version "
+ f"this source asks for may no longer match Apple's report specification "
+ f"({_apple_error_suffix(apple_error, 400)})"
+ )
+ tolerated.record_tolerated(_apple_error_suffix(apple_error, 400))
+ else:
+ tolerated.record_tolerated()
return []
return _parse_report(response.content, report_date, failures)
@@ -811,16 +976,24 @@ def _get_sales_report(
start = resumed
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, failures)
- if rows:
- yield rows
+ tolerated = _ToleratedReportDays(logger, config)
+ vendor_check = _VendorNumberCheck(session, token_provider, logger, vendor_number)
+ try:
+ while report_date <= end and tolerated.days_fetched < SALES_REPORT_MAX_DAYS_PER_RUN:
+ rows = _fetch_report(
+ session, config, token_provider, logger, vendor_number, report_date, failures, tolerated, vendor_check
+ )
+ tolerated.days_fetched += 1
+ if rows:
+ tolerated.days_with_rows += 1
+ yield rows
- days_fetched += 1
- report_date += timedelta(days=1)
- if report_date <= end:
- manager.save_state(AppStoreConnectResumeConfig(report_date=report_date.isoformat()))
+ report_date += timedelta(days=1)
+ if report_date <= end:
+ manager.save_state(AppStoreConnectResumeConfig(report_date=report_date.isoformat()))
+ finally:
+ # Flush on teardown too, so an abandoned or failed walk still surfaces an all-empty run.
+ tolerated.flush()
if report_date <= end:
logger.info(
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 c6ee059952fe..470f0a729c22 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
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -45,7 +47,7 @@ ANALYTICS_GRANULARITY = "DAILY"
ANALYTICS_MAX_INSTANCES_PER_RUN = 400
-@dataclass
+@frozen
class AppStoreConnectEndpointConfig:
name: str
kind: EndpointKind
@@ -86,7 +88,11 @@ class AppStoreConnectEndpointConfig:
# Apple 404s a SALES report request for a date with no data. Subscription-family report types
# (SUBSCRIPTION, SUBSCRIPTION_EVENT) instead 400 with a misleading "Invalid vendor number
# specified" error for that same condition — a longstanding, publicly reported Apple API quirk,
- # not an actual credentials problem. Treat both as "no report for this day" for those types.
+ # usually not an actual credentials problem. A tolerated 400 is not swallowed blindly:
+ # `_fetch_report` reads the body, so a genuinely malformed request (wrong version or sub type)
+ # still fails loudly instead of reading as a quiet account. Apple words that same 400 for a
+ # vendor number it doesn't know, so a sales-report check separates the two before the misleading
+ # wording is tolerated across the whole lookback.
missing_report_status_codes: tuple[int, ...] = (404,)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
index 658676cc6b0f..4cf8f634cb05 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py
@@ -12,8 +12,10 @@ from posthog.schema import (
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (
APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,
APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,
+ APP_STORE_CONNECT_INVALID_REPORT_ERROR,
APP_STORE_CONNECT_MISSING_VENDOR_NUMBER_ERROR,
APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,
+ APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR,
AppStoreConnectResumeConfig,
app_store_connect_source,
check_credentials,
@@ -159,6 +161,11 @@ The analytics tables need a key with the Admin role. Apple lets only an Admin ke
# A report sync selected without a vendor number can never read `/v1/salesReports`, so fail
# fast instead of retrying the activity's whole budget until the user adds the number.
APP_STORE_CONNECT_MISSING_VENDOR_NUMBER_ERROR: APP_STORE_CONNECT_MISSING_VENDOR_NUMBER_ERROR,
+ # Apple rejected the report request itself. Retrying can't change the answer, and the fix
+ # is a source update rather than anything the user can do.
+ APP_STORE_CONNECT_INVALID_REPORT_ERROR: "App Store Connect rejected this report request. The report type or version it asks for may no longer be valid. This usually needs a source update — contact support if it keeps failing.",
+ # A vendor number Apple doesn't know. Every retry fails identically until it is corrected.
+ APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR: "App Store Connect does not recognize your vendor number. Find it in App Store Connect under Payments and Financial Reports, update it in this source's settings, then run the sync again.",
}
def get_retryable_errors(self) -> set[str]:
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 649c0d3abe71..7aeb6b4db098 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
@@ -1,4 +1,5 @@
import gzip
+import json
import hashlib
from datetime import UTC, date, datetime, timedelta
from typing import Any
@@ -21,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_
JWT_LIFETIME_SECONDS,
AppStoreConnectAuthError,
AppStoreConnectPermissionError,
+ AppStoreConnectReportError,
AppStoreConnectResumeConfig,
AppStoreConnectTokenProvider,
AppStoreConnectUrlError,
@@ -105,13 +107,21 @@ def _json_response(body: dict[str, Any], status_code: int = 200) -> MagicMock:
return response
-def _report_response(tsv: str | None, missing_status_code: int = 404) -> MagicMock:
- """A gzipped-TSV report response, or the 404 Apple returns for a date with no activity."""
+def _report_response(tsv: str | None, missing_status_code: int = 404, error_detail: str | None = None) -> MagicMock:
+ """A gzipped-TSV report response, or the "no data" status Apple returns for a date with no activity.
+
+ A missing 400 defaults to Apple's misleading "Invalid vendor number specified" body — its wording
+ for a subscription-family day with no report yet, not a real credentials failure.
+ """
response = MagicMock()
if tsv is None:
response.status_code = missing_status_code
response.ok = False
- response.text = '{"errors":[{"code":"NOT_FOUND"}]}'
+ if error_detail is None:
+ error_detail = "Invalid vendor number specified" if missing_status_code == 400 else "Not found"
+ body = {"errors": [{"status": str(missing_status_code), "detail": error_detail}]}
+ response.text = json.dumps(body)
+ response.json.return_value = body
return response
response.status_code = 200
response.ok = True
@@ -156,17 +166,41 @@ class _FakeApi:
class _FakeReportApi:
- """Serves `/v1/salesReports` per requested report date; an unknown date 404s like Apple's does."""
+ """Serves `/v1/salesReports` per requested report date; an unknown date 404s like Apple's does.
+
+ SALES requests are answered apart from the subscription families, because the vendor-number check
+ relies on Apple answering them differently: 404 for a known vendor with no data on the date, and
+ the vendor-number 400 for one it doesn't know. `sales_status_code` picks which, and `sales_error`
+ makes the check itself fail, as it does for a key with no Sales role.
+ """
- def __init__(self, tsv_by_date: dict[str, str], missing_status_code: int = 404) -> None:
+ def __init__(
+ self,
+ tsv_by_date: dict[str, str],
+ missing_status_code: int = 404,
+ missing_error_detail: str | None = None,
+ sales_status_code: int = 404,
+ sales_error: Exception | None = None,
+ ) -> None:
self.tsv_by_date = tsv_by_date
self.missing_status_code = missing_status_code
+ self.missing_error_detail = missing_error_detail
+ self.sales_status_code = sales_status_code
+ self.sales_error = sales_error
self.calls: list[tuple[str, dict[str, Any]]] = []
def get(self, url: str, **kwargs: Any) -> MagicMock:
params: dict[str, Any] = kwargs.get("params") or {}
self.calls.append((url, params))
- return _report_response(self.tsv_by_date.get(params["filter[reportDate]"]), self.missing_status_code)
+ tsv = self.tsv_by_date.get(params["filter[reportDate]"])
+ if params["filter[reportType]"] == "SALES":
+ if self.sales_error is not None:
+ raise self.sales_error
+ return _report_response(tsv, self.sales_status_code)
+ return _report_response(tsv, self.missing_status_code, self.missing_error_detail)
+
+ def report_dates(self, report_type: str) -> list[str]:
+ return [params["filter[reportDate]"] for _, params in self.calls if params["filter[reportType]"] == report_type]
def _collect(
@@ -1207,7 +1241,60 @@ class TestSalesReports:
)
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"]
+ assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
+
+ @freeze_time("2026-03-05 09:00:00")
+ def test_unknown_vendor_number_fails_instead_of_completing_empty(self) -> None:
+ # Apple words a vendor number it doesn't know exactly like an empty subscription day, so a
+ # typo used to be tolerated across the whole lookback and complete with zero rows. The sales
+ # report separates the two, and an unknown vendor number now fails the sync.
+ api = _FakeReportApi({}, missing_status_code=400, sales_status_code=400)
+
+ with pytest.raises(AppStoreConnectReportError, match="does not recognize the vendor number"):
+ _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 2),
+ )
+
+ @freeze_time("2026-03-05 09:00:00")
+ def test_vendor_number_is_checked_once_per_run(self) -> None:
+ # The check costs an extra request. Repeating it per tolerated day would add one for every
+ # day of the lookback window.
+ api = _FakeReportApi({}, missing_status_code=400)
+
+ _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 2),
+ )
+
+ assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
+ assert api.report_dates("SALES") == ["2026-03-02"]
+
+ @freeze_time("2026-03-05 09:00:00")
+ def test_unreadable_sales_report_leaves_the_day_tolerated(self) -> None:
+ # A key with a Finance role but no Sales role can read the subscription report and not the
+ # sales one. The check can't run, so it must not fail a sync it cannot judge.
+ api = _FakeReportApi({}, missing_status_code=400, sales_error=Exception("403 Client Error: Forbidden"))
+
+ rows = _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 2),
+ )
+
+ assert rows == []
+ assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
@freeze_time("2026-03-05 09:00:00")
def test_sales_report_400_is_not_tolerated(self) -> None:
@@ -1232,6 +1319,68 @@ class TestSalesReports:
)
)
+ @freeze_time("2026-03-05 09:00:00")
+ def test_subscription_report_unrecognized_400_fails_loudly(self) -> None:
+ # A 400 whose body is not Apple's "no data" quirk is a genuinely malformed request (a wrong
+ # version or sub type). It must fail rather than read as an empty day across the whole
+ # lookback, so an operator can tell a bad request from a quiet account.
+ api = _FakeReportApi(
+ {},
+ missing_status_code=400,
+ missing_error_detail="filter[version] '9_9' is not a valid value",
+ )
+
+ with pytest.raises(AppStoreConnectReportError, match="rejected a report request as invalid"):
+ _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 4),
+ )
+
+ @freeze_time("2026-03-05 09:00:00")
+ def test_all_empty_run_logs_a_warning(self) -> None:
+ # Every day tolerated as empty and no rows anywhere: log once at the end so an operator can
+ # tell an account with no subscription data from a request Apple keeps rejecting.
+ api = _FakeReportApi({}, missing_status_code=400)
+ logger = MagicMock()
+
+ rows = _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ logger=logger,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 2),
+ )
+
+ assert rows == []
+ warnings = [call.args[0] for call in logger.warning.call_args_list]
+ run_summary = [message for message in warnings if "produced no rows" in message]
+ assert len(run_summary) == 1
+ assert "days_tolerated_as_empty=3" in run_summary[0]
+ assert "Invalid vendor number specified" in run_summary[0]
+
+ @freeze_time("2026-03-05 09:00:00")
+ def test_run_with_rows_does_not_log_the_empty_warning(self) -> None:
+ api = _FakeReportApi({"2026-03-04": "SKU\tUnits\nacme\t1\n"}, missing_status_code=400)
+ logger = MagicMock()
+
+ _collect(
+ "subscription_reports",
+ api,
+ _FakeManager(),
+ vendor_number="85234567",
+ logger=logger,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 3, 2),
+ )
+
+ assert not any("produced no rows" in call.args[0] for call in logger.warning.call_args_list)
+
@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