: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(google_analytics): keep rows an incremental sync read when quota runs out (#118734)
Daniel RC8cf450b762a2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.pyindex a140b389dddd..87e8eec6649c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -339,22 +339,26 @@ class _SyncWindow:end: dt.date+def _watermark_date(db_incremental_field_last_value: Any) -> dt.date | None:+ if db_incremental_field_last_value is None:+ return None+ if isinstance(db_incremental_field_last_value, dt.datetime):+ return db_incremental_field_last_value.date()+ if isinstance(db_incremental_field_last_value, dt.date):+ return db_incremental_field_last_value+ return dt.date.fromisoformat(str(db_incremental_field_last_value)[:10])++def _resolve_window(today: dt.date, db_incremental_field_last_value: Any, history_days: int | None = None) -> _SyncWindow:# End at yesterday: today's aggregates are still accruing and would land as# permanently stale rows for schemas whose primary key is just `date`.end_date = today - dt.timedelta(days=1)- if db_incremental_field_last_value is None:+ last = _watermark_date(db_incremental_field_last_value)+ if last is None:return _SyncWindow(start=_initial_start_date(today, history_days), end=end_date)- if isinstance(db_incremental_field_last_value, dt.datetime):- last = db_incremental_field_last_value.date()- elif isinstance(db_incremental_field_last_value, dt.date):- last = db_incremental_field_last_value- else:- last = dt.date.fromisoformat(str(db_incremental_field_last_value)[:10])-start = max(last - dt.timedelta(days=LOOKBACK_DAYS), _initial_start_date(today, history_days))return _SyncWindow(start=start, end=end_date)@@ -409,6 +413,11 @@ def google_analytics_source(start_date = max(start_date, dt.date.fromisoformat(resume_chunk_start))session = google_analytics_session(config.google_analytics_integration_id, team_id)+ watermark = _watermark_date(db_incremental_field_last_value) if should_use_incremental_field else None+ # A resumed attempt continues a run whose earlier attempts read every date before the saved chunk.+ latest_date_read = (+ dt.date.fromisoformat(resume_chunk_start) - dt.timedelta(days=1) if resume_chunk_start else None+ )for chunk_start, chunk_end in _iter_chunks(start_date, end_date):chunk_start_iso = chunk_start.isoformat()@@ -418,20 +427,39 @@ def google_analytics_source(while True:# A safe point keeps the cursor saved after the last yield. The source holds no rows here.resumable_source_manager.safe_point()- payload = _run_report(- session=session,- property_id=config.property_id,- start_date=chunk_start_iso,- end_date=chunk_end.isoformat(),- dimensions=dimensions,- metrics=metrics,- offset=offset,- )+ try:+ payload = _run_report(+ session=session,+ property_id=config.property_id,+ start_date=chunk_start_iso,+ end_date=chunk_end.isoformat(),+ dimensions=dimensions,+ metrics=metrics,+ offset=offset,+ )+ except GoogleAnalyticsQuotaExceededError:+ # Rows arrive in date order, so an incremental run that ends here keeps them and the next run+ # re-reads the last date through the lookback window. A full refresh would replace the table,+ # and a run still inside the lookback window would leave the watermark where it was.+ advanced = latest_date_read is not None and (watermark is None or latest_date_read > watermark)+ if not (should_use_incremental_field and advanced):+ raise+ logger.warning(+ "Google Analytics Data API quota is used up. This sync keeps the rows it read, and the "+ "next sync continues from the last date it read.",+ property_id=config.property_id,+ chunk_start=chunk_start_iso,+ offset=offset,+ )+ returnrows = _rows_to_dicts(payload)if not rows:breakyield rows+ last_row_date = rows[-1].get("date")+ if isinstance(last_row_date, dt.date):+ latest_date_read = last_row_datenext_offset = offset + len(rows)row_count = payload.get("rowCount", 0)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.pyindex a8858aa88cbe..5596f6907d39 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py@@ -1,5 +1,5 @@import datetime as dt-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom typing import Any, castimport pytest@@ -9,9 +9,15 @@ from django.db import OperationalErrorimport requestsfrom google.auth.exceptions import RefreshError+from google.oauth2.credentials import Credentials as OAuthCredentialsfrom posthog.models.integration import Integration+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,+ ScriptedResponse,+ SourceDriver,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googleanalytics import (GoogleAnalyticsSourceConfig,)@@ -33,6 +39,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ana_runreport_backoff_seconds,google_analytics_source,)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.source import (+ GoogleAnalyticsSource,+)TODAY = dt.date(2026, 4, 30)@@ -497,6 +506,63 @@ def test_source_resume_past_end_date_yields_nothing(monkeypatch):fake_run_report.assert_not_called()+def _quota_after_pages(pages_before_quota: int) -> Callable[[RecordedRequest], ScriptedResponse]:+ page = ScriptedResponse(json=_report_payload(["20250816", "20250817"], [1, 2], row_count=5))+ quota = ScriptedResponse(status=429, json={"error": {"status": "RESOURCE_EXHAUSTED"}})+ answered: list[RecordedRequest] = []++ def answer(request: RecordedRequest) -> ScriptedResponse:+ answered.append(request)+ return page if len(answered) <= pages_before_quota else quota++ return answer+++ "should_use_incremental_field,resume_state,pages_before_quota,expected_rows,expect_raise",+ [+ (True, None, 1, 2, False),+ (True, None, 0, 0, True),+ (True, GoogleAnalyticsResumeConfig(chunk_start="2025-09-15", offset=0), 0, 0, False),+ (False, None, 1, 2, True),+ ],+)+def test_source_quota_exhaustion_keeps_rows_only_when_the_watermark_advances(+ monkeypatch, should_use_incremental_field, resume_state, pages_before_quota, expected_rows, expect_raise+):+ monkeypatch.setattr(ga, "_credentials", lambda *args: OAuthCredentials(token="test-token"))++ result = SourceDriver(GoogleAnalyticsSource(), _config()).run(+ "website_overview",+ _quota_after_pages(pages_before_quota),+ resume_state=resume_state,+ incremental_field="date",+ should_use_incremental_field=should_use_incremental_field,+ )++ assert len(result.rows) == expected_rows+ assert isinstance(result.raised, GoogleAnalyticsQuotaExceededError) is expect_raise+ if not expect_raise:+ assert result.raised is None+++def test_source_next_job_fails_when_quota_runs_out_inside_the_lookback_window(monkeypatch):+ monkeypatch.setattr(ga, "_credentials", lambda *args: OAuthCredentials(token="test-token"))+ driver = SourceDriver(GoogleAnalyticsSource(), _config())++ first = driver.run("website_overview", _quota_after_pages(1), incremental_field="date")+ assert first.raised is None++ second = driver.run(+ "website_overview",+ _quota_after_pages(1),+ incremental_field="date",+ db_incremental_field_last_value=max(row["date"] for row in first.rows),+ )++ assert isinstance(second.raised, GoogleAnalyticsQuotaExceededError)++def test_source_requests_user_defined_custom_report(monkeypatch):# A custom report drives the exact dimensions/metrics sent to runReport (date prepended),# proving user config reaches the generic fetch layer, and its primary key is date + dims.