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(data-warehouse): let a google ads source state how far back to import (#84589)

Javier Bahamondes2a1a5dc5dc5c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleads.py
index a59a5e54001d..c1922f961944 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleads.py
@@ -15,3 +15,4 @@ class GoogleAdsSourceConfig(config.Config):
customer_id: str
google_ads_integration_id: int = config.value(converter=config.str_to_int)
is_mcc_account: GoogleAdsIsMccAccountConfig | None = None
+ start_date: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py
index bd7c9f02b51f..92f347efd610 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py
@@ -9,6 +9,7 @@ run path in ``source.py``. See ``google_ads.py`` for the SDK-backed functions.
"""
import re
+import datetime
import dataclasses
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@@ -21,6 +22,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
GOOGLE_ADS_INITIAL_BACKFILL_DAYS = 2 * 365
+def parse_start_date(value: str) -> datetime.date:
+ """Read a configured start date, or raise `ValueError`.
+
+ Strict where a cursor's own coercion is lenient: a permissive parser fills the missing part of
+ "2020" from the current date, so the same stored value would mean a different day on a different
+ run and import less than it plainly reads as, without failing. Stripped because the field is
+ free text and a date pasted from a spreadsheet carries whitespace.
+
+ Shared with `validate_credentials` deliberately: a value accepted at setup and rejected at sync
+ time, or the reverse, is the shape that puts an unasked-for range in a table.
+ """
+ return datetime.datetime.fromisoformat(value.strip()).date()
+
+
@dataclasses.dataclass
class GoogleAdsResumeConfig:
"""Resumable state for the Google Ads source.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
index 95772c589d29..d1d485886fa9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
@@ -48,6 +48,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
GoogleAdsResumeConfig,
GoogleAdsSourceConfigUnion,
clean_customer_id,
+ parse_start_date,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.schemas import (
FIELD_ALIASES,
@@ -527,6 +528,54 @@ def _incremental_value_as_date(value: dt.date | dt.datetime | str) -> dt.date:
return dateutil_parser.parse(value).date()
+def _resolve_start(
+ requested_start: str | None,
+ history_start: typing.Any,
+ service: "GoogleAdsSearchService",
+ customer_id: str | None,
+ table: "GoogleAdsTable",
+ incremental_field: str,
+) -> tuple[dt.date, str]:
+ """Where a run with no cursor begins, and which of the three answers it came from.
+
+ A stated start date wins over the range the schema recorded: it is the only one of the two
+ anybody chose, and it wins in both directions, so a source can narrow its range as well as widen
+ it. Neither is a first sync versus a re-import question — both land here and read the same
+ answer, which is what stops the two diverging on which button was pressed.
+ """
+ if requested_start:
+ try:
+ requested = parse_start_date(requested_start)
+ except ValueError:
+ # Validation rejects an unreadable value, so reaching here means one stored before that
+ # check existed. Fall through to the recorded range rather than fail the sync -- the
+ # range this source would have had without the field. Truncated in the log because the
+ # field has no length limit of its own and this runs once per schema per run.
+ logger.warning("google_ads.unparseable_start_date", start_date=requested_start[:32])
+ else:
+ # Clamped to the span that can hold rows. Below the account's first day the walk spends
+ # a request per empty week, and since only a window past the cursor counts as progress,
+ # the drain budget cannot end a run that never reaches data. Past today it leaves
+ # `start` beyond the loop's end, so every run imports nothing and reports that as the
+ # answer.
+ earliest = _earliest_date_with_data(service, customer_id, table, incremental_field)
+ today = dt.date.today()
+ resolved = min(max(requested, earliest), today) if earliest is not None else today
+ if resolved != requested:
+ # The range imported is then not the one the source states, so leave a trace.
+ logger.warning(
+ "google_ads.clamped_start_date", requested=requested.isoformat(), resolved=resolved.isoformat()
+ )
+ return resolved, "stated"
+
+ if history_start is not None:
+ return _incremental_value_as_date(history_start), "recorded"
+
+ # Neither: unbounded, which this drain reaches by asking the account rather than walking to it.
+ # An account holding nothing has no range to walk.
+ return _earliest_date_with_data(service, customer_id, table, incremental_field) or dt.date.today(), "probe"
+
+
def google_ads_source(
config: GoogleAdsSourceConfigUnion,
resource_name: str,
@@ -539,6 +588,7 @@ def google_ads_source(
incremental_field_type: IncrementalFieldType | None = None,
db_incremental_field_last_value_before_lookback: typing.Any = None,
history_start: typing.Any = None,
+ requested_start: str | None = None,
) -> SourceResponse:
"""A data warehouse Google Ads source.
@@ -610,6 +660,10 @@ def google_ads_source(
# runs, take this path.
if pipeline_is_incremental and table.requires_filter and incremental_field_type == IncrementalFieldType.Date:
if db_incremental_field_last_value is not None:
+ # A stated start date is deliberately not read here: the cursor is where this table
+ # got to, and reading anything older would re-import a range it already holds on
+ # every run. Stating an earlier date therefore takes effect on the next re-import,
+ # which is what the field's caption says.
start = _incremental_value_as_date(db_incremental_field_last_value)
# The cursor arrives shifted back by the schema's lookback, so the windows up to the
# cursor itself re-read rows the table already has. They don't count as progress.
@@ -619,19 +673,15 @@ def google_ads_source(
else start
)
else:
- # A first sync and a re-import both land here and read the same recorded range, so
- # the two stop needing to be told apart. No range means unbounded, which this drain
- # reaches by asking the account rather than walking to it.
- if history_start is not None:
- start = _incremental_value_as_date(history_start)
- else:
- start = _earliest_date_with_data(service, customer_id, table, incremental_field) or dt.date.today()
+ start, resolved_from = _resolve_start(
+ requested_start, history_start, service, customer_id, table, incremental_field
+ )
cursor_before_lookback = start
logger.info(
"google_ads.history_start_used",
resource=table.name,
start=start.isoformat(),
- bounded=history_start is not None,
+ resolved_from=resolved_from,
)
# Exclusive upper bound of today+1 keeps today in range, matching the open-ended scan.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
index 5b93038e7ed1..e84d3b148d32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
GoogleAdsServiceAccountSourceConfig,
clean_customer_id,
format_customer_id,
+ parse_start_date,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -248,6 +249,7 @@ class GoogleAdsSource(
else None,
db_incremental_field_last_value_before_lookback=inputs.db_incremental_field_last_value_before_lookback,
history_start=inputs.history_start,
+ requested_start=config.start_date if isinstance(config, GoogleAdsSourceConfig) else None,
)
@property
@@ -280,6 +282,20 @@ class GoogleAdsSource(
required=True,
placeholder="123-456-7890",
),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ caption=(
+ "Earliest date to import, as YYYY-MM-DD. On a source that has already "
+ "synced, changing this takes effect on the next full re-import — Sync "
+ "keeps going from where it left off. Leave empty for the last two years; "
+ "an earlier date imports more rows, which count towards your billed row usage."
+ ),
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2020-01-01",
+ secret=False,
+ ),
SourceFieldSwitchGroupConfig(
name="is_mcc_account",
label="Using MCC account?",
@@ -449,6 +465,14 @@ class GoogleAdsSource(
google_ads_client,
)
+ # Caught here rather than at sync time: an unreadable value is treated as unset there, so
+ # the source would import a range nobody asked for with nothing to say why.
+ if isinstance(config, GoogleAdsSourceConfig) and config.start_date:
+ try:
+ parse_start_date(config.start_date)
+ except ValueError:
+ return False, "Start date must be a date in YYYY-MM-DD format, for example 2020-01-01."
+
# The SDK's client default is the newest bundled version, so leaving these probes unpinned
# would validate against a version the source may not sync with.
resolved_version = self.resolve_api_version(api_version)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
index c7c45607c84f..adda8fbe3788 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
@@ -406,6 +406,32 @@ class TestGrpcReceiveLimit:
class TestValidateCredentials:
+ @pytest.mark.parametrize("start_date", ["last tuesday", "2020", "01/02/2020", "9999999999"])
+ def test_an_unreadable_start_date_is_rejected_at_setup(self, start_date: str) -> None:
+ # The sync treats an unreadable value as unset, so without this the source would import a
+ # range nobody asked for and nothing would say why. A partial date is the worse case: it
+ # reads as a year but a lenient parser would resolve it against the day the sync ran.
+ config = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1, start_date=start_date)
+
+ ok, message = GoogleAdsSource().validate_credentials(config, team_id=1)
+
+ assert ok is False
+ # Names the field as the form labels it, since this reaches the user as the body of a 400.
+ assert message is not None and message.startswith("Start date")
+
+ def test_a_readable_start_date_passes_validation_through(self) -> None:
+ # Whitespace and a full timestamp are both readable, and neither should stop a connection.
+ config = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1, start_date=" 2020-01-01 ")
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.google_ads_client",
+ side_effect=Integration.DoesNotExist(),
+ ):
+ ok, message = GoogleAdsSource().validate_credentials(config, team_id=1)
+
+ # Reaches the connection attempt rather than being turned away on the date.
+ assert ok is False
+ assert "no longer exists" in (message or "")
+
def test_missing_integration_does_not_exist_returns_reconnect_message(self):
# `google_ads_client` calls `Integration.objects.get(...)`, which raises the typed
# `Integration.DoesNotExist` when the OAuth connection row is gone. Surface an
@@ -1583,6 +1609,62 @@ class TestGoogleAdsQueryConstruction:
# Windowed, not the open-ended `.. 2100` scan a first sync used to run.
assert all("2100-01-01" not in q for q in queries)
+ @pytest.mark.parametrize(
+ "requested,earliest_date,expected",
+ [
+ # Within the span that holds rows, the stated date is what the drain reads.
+ ("2022-06-01", "2020-02-08", "2022-06-01"),
+ # Whitespace survives a paste from a spreadsheet.
+ (" 2022-06-01 ", "2020-02-08", "2022-06-01"),
+ # Before the account's first row: the walk would spend a request per empty week to reach
+ # the same rows, and the budget cannot end a run that has not reached data.
+ ("2015-01-01", "2020-02-08", "2020-02-08"),
+ # Past today: `start` would sit beyond the loop's end, so every run imports nothing and
+ # reports that as the answer.
+ ("2030-01-01", "2020-02-08", "2026-07-17"),
+ # An account holding nothing has no span to clamp to.
+ ("2015-01-01", None, "2026-07-17"),
+ ],
+ )
+ def test_a_stated_start_date_is_clamped_to_the_span_that_holds_rows(
+ self, requested: str, earliest_date: str | None, expected: str
+ ) -> None:
+ with freeze_time("2026-07-17"):
+ _response, queries = self._run_source(
+ self._stats_table(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ requested_start=requested,
+ # Recorded, and deliberately different: the stated date has to win over it.
+ history_start=dt.datetime(2024, 1, 1, tzinfo=dt.UTC),
+ earliest_date=earliest_date,
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ )
+
+ drain = [q for q in queries if "LIMIT 1" not in q]
+ assert f"WHERE segments.date >= '{expected}'" in drain[0]
+
+ @pytest.mark.parametrize("requested", ["last tuesday", "2020", "01/02/2020"])
+ def test_an_unreadable_stated_date_falls_back_to_the_recorded_range(self, requested: str) -> None:
+ # Validation rejects these at setup, so reaching the sync means a value stored before that
+ # check existed. Failing the sync over it is worse than importing the range this source
+ # would have had without the field.
+ with freeze_time("2026-07-17"):
+ _response, queries = self._run_source(
+ self._stats_table(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ requested_start=requested,
+ history_start=dt.datetime(2024, 1, 1, tzinfo=dt.UTC),
+ earliest_date="2020-02-08",
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ )
+
+ drain = [q for q in queries if "LIMIT 1" not in q]
+ assert "WHERE segments.date >= '2024-01-01'" in drain[0]
+
@pytest.mark.parametrize("earliest_date,expected_start", [("2020-02-08", "2020-02-08"), (None, "2026-07-17")])
def test_no_recorded_range_asks_the_account_where_its_rows_begin(
self, earliest_date: str | None, expected_start: str