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(data-warehouse): fix Google Play error counts and games-only syncs (#89688)

Tom Owers2ba019dae7e8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py
index f35a015d2bed..37af01c757c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py
@@ -18,7 +18,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_pla
AGGREGATION_PERIOD,
ERROR_HISTORY_DAYS,
LIST_ENDPOINTS,
- METRIC_SET_HISTORY_DAYS,
METRIC_SET_WINDOW_DAYS,
METRIC_SETS,
PRIMARY_KEYS,
@@ -404,6 +403,17 @@ def _query_metric_set(
return
+def _is_games_only_denial(error: requests.HTTPError) -> bool:
+ """True when Play denied a metric set that is only served for games.
+
+ Google returns `403 PERMISSION_DENIED` with a body like "slowRenderingRateMetricSet
+ resource is only accessible to games" when the app is not a game. The status code alone
+ cannot distinguish this from a real permission problem, so match the message.
+ """
+ response = error.response
+ return response is not None and response.status_code == 403 and "only accessible to games" in response.text
+
+
def _batch_by_date(rows: Iterable[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""Group a window's rows into one batch per day, oldest first.
@@ -446,7 +456,22 @@ def _iter_metric_set_rows(
window_start = _parse_date(resume_date) or history_start
resume_app = None
- latest = client.latest_available_date(package_name, endpoint.resource)
+ try:
+ latest = client.latest_available_date(package_name, endpoint.resource)
+ except requests.HTTPError as e:
+ if _is_games_only_denial(e):
+ # Play restricts some metric sets (slow rendering) to games. For every other app
+ # category the freshness read fails with 403, which the source's error classifier
+ # would read as missing account permissions and pause the schema with advice the
+ # user cannot act on. The app can never have this data, so skip it and let any
+ # games in the same account still sync.
+ logger.info(
+ "Skipping app: metric set is only available to games",
+ app=package_name,
+ resource=endpoint.resource,
+ )
+ continue
+ raise
if latest is None:
# No freshness for this metric set means the app has no data we can query for it — a metric
# set the app isn't eligible for, or one with too little volume to report. Querying a guessed
@@ -644,7 +669,7 @@ def _metric_set_response(
client=client,
endpoint=endpoint,
package_names=resolve_package_names(client, package_names),
- history_start=resolve_history_start(_today(), watermark, METRIC_SET_HISTORY_DAYS),
+ history_start=resolve_history_start(_today(), watermark, endpoint.history_days),
manager=manager,
resume=_load_resume_state(manager),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py
index 9537d6281a2c..0b6f0d2d6a33 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py
@@ -36,6 +36,10 @@ class MetricSetEndpoint:
metrics: tuple[str, ...]
dimensions: tuple[str, ...]
description: str
+ # Days of history requested on a first sync. The vitals rate metric sets serve years of
+ # daily data, but the error backend serves only about the last two months, and it rejects
+ # a query that starts earlier with a bare `400 INVALID_ARGUMENT`.
+ history_days: int = METRIC_SET_HISTORY_DAYS
@dataclass(frozen=True)
@@ -166,6 +170,10 @@ METRIC_SETS: dict[str, MetricSetEndpoint] = {
metrics=("errorReportCount", "distinctUsers"),
dimensions=("reportType", "versionCode"),
description="Daily error report counts, broken out by report type and app version.",
+ # Error counts come from the same short-retention backend as error reports, not from
+ # the vitals store. The Play Console errors page offers at most the last 56 days, and
+ # a query that starts 180 days back is rejected with `400 INVALID_ARGUMENT`.
+ history_days=ERROR_HISTORY_DAYS,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py
index bcd4f3ef4718..768e214d0d91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py
@@ -73,6 +73,12 @@ class GooglePlayConsoleSource(ResumableSource[GooglePlayConsoleSourceConfig, Goo
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ # The Reporting API answers a malformed or unsupported query with a deterministic 400,
+ # so retrying replays the identical rejection until the activity budget runs out.
+ "400 Client Error": (
+ "Google rejected a Play Console report query as invalid. "
+ "Contact PostHog support if this happens again on the next sync."
+ ),
"401 Client Error": "Google rejected the service account credentials. Please upload a current JSON key file.",
"403 Client Error": (
"The service account cannot read Play Console reporting data. Enable the Play Developer Reporting "
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py
index 7071832f8667..ba2638aa268d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py
@@ -438,6 +438,62 @@ def test_metric_set_skips_an_app_without_freshness() -> None:
assert not any(path.endswith(":query") for path in calls)
+def test_metric_set_skips_an_app_denied_a_games_only_metric_set() -> None:
+ manager = _manager()
+ queried: list[str] = []
+ games_denial = requests.HTTPError(
+ "403 Client Error: for url: https://playdeveloperreporting.googleapis.com",
+ response=_response(403, text="slowRenderingRateMetricSet resource is only accessible to games"),
+ )
+
+ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:
+ if path.endswith(":query"):
+ queried.append(path)
+ return {"rows": [_metric_row(dt.date(2024, 3, 5), 12, "0.01")]}
+ if path.startswith("apps/com.fintech.app/"):
+ raise games_denial
+ return _freshness(dt.date(2024, 3, 10))
+
+ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request):
+ client = _client(mock.MagicMock())
+ batches = list(
+ _iter_metric_set_rows(
+ client=client,
+ endpoint=METRIC_SETS["slow_rendering_rate"],
+ package_names=["com.fintech.app", "com.game.app"],
+ history_start=dt.date(2024, 3, 1),
+ manager=manager,
+ resume=None,
+ )
+ )
+
+ # The non-game app can never have this metric set, so it is skipped instead of failing the
+ # sync with a 403 the error classifier reads as missing permissions. The game still syncs.
+ assert queried == ["apps/com.game.app/slowRenderingRateMetricSet:query"]
+ assert len(batches) == 1
+
+
+def test_metric_set_reraises_a_403_that_is_not_the_games_restriction() -> None:
+ denial = requests.HTTPError(
+ "403 Client Error: for url: https://playdeveloperreporting.googleapis.com",
+ response=_response(403, text="The caller does not have permission"),
+ )
+
+ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=denial):
+ client = _client(mock.MagicMock())
+ with pytest.raises(requests.HTTPError):
+ list(
+ _iter_metric_set_rows(
+ client=client,
+ endpoint=METRIC_SETS["slow_rendering_rate"],
+ package_names=["com.example.app"],
+ history_start=dt.date(2024, 3, 1),
+ manager=_manager(),
+ resume=None,
+ )
+ )
+
+
def test_metric_set_query_follows_pagination_until_the_token_runs_out() -> None:
manager = _manager()
payloads: list[dict[str, Any]] = [
@@ -814,6 +870,45 @@ def test_metric_set_source_streams_rows_for_the_incremental_window() -> None:
assert manager.saved[-1].date == "2024-03-30"
+ "resource_name,expected_start",
+ [
+ # The vitals rate metric sets keep the deep 180-day backfill.
+ ("crash_rate", dt.date(2023, 10, 3)),
+ # Error counts live on the short-retention error backend, which rejects a start that
+ # far back with a 400, so the first sync begins inside the error history window.
+ ("error_counts", dt.date(2024, 3, 1)),
+ ],
+)
+def test_first_sync_history_window_depends_on_the_metric_set(resource_name: str, expected_start: dt.date) -> None:
+ bodies: list[dict[str, Any]] = []
+
+ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:
+ if path.endswith(":query"):
+ bodies.append(body)
+ return {"rows": []}
+ return _freshness(dt.date(2024, 3, 30))
+
+ response = google_play_console_source(
+ key=_key(),
+ package_names=("com.example.app",),
+ resource_name=resource_name,
+ api_version="v1beta1",
+ resumable_source_manager=_manager(),
+ logger=structlog.get_logger(),
+ )
+
+ with (
+ mock.patch(f"{MODULE}._today", return_value=TODAY),
+ mock.patch(f"{MODULE}.make_tracked_session", return_value=mock.MagicMock()),
+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),
+ ):
+ list(cast("Iterable[Any]", response.items()))
+
+ first_start = bodies[0]["timelineSpec"]["startTime"]
+ assert dt.date(first_start["year"], first_start["month"], first_start["day"]) == expected_start
+
+
def test_error_reports_always_carry_an_event_time_column() -> None:
endpoint = LIST_ENDPOINTS["error_reports"]