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): stop a resync truncating the history a schema already covers (#84015)

Javier Bahamondeseb414b099fe6
diff --git a/products/warehouse_sources/backend/migrations/0143_add_schema_history_start.py b/products/warehouse_sources/backend/migrations/0143_add_schema_history_start.py
new file mode 100644
index 000000000000..f8da34264b2a
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0143_add_schema_history_start.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-08-18 23:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0142_scaffold_microsoft_excel_source"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="externaldataschema",
+ name="history_start",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 436985cdacea..c59969b3018d 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0142_scaffold_microsoft_excel_source
\ No newline at end of file
+0143_add_schema_history_start
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 79e7ac076409..49e593e5d934 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -194,6 +194,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# ignored by version-migration tooling — only the user changes it. Not available for
# webhook-sync schemas (webhook payload versions are configured per source at the vendor).
api_version = models.CharField(max_length=128, null=True, blank=True)
+ # See `sources/common/history_window.py`. A column rather than a `sync_type_config` key
+ # because it has to outlive a reset, and clearing that blob is what a reset is for.
+ history_start = models.DateTimeField(null=True, blank=True)
# { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict } }
sync_type_config = models.JSONField(
default=dict,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 77b04fe12913..30df320e71c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -175,6 +175,11 @@ class _BaseSource(ABC, Generic[ConfigType]):
# in-product deprecation warning; no per-source UI work.
deprecated_versions: tuple[VersionDeprecation, ...] = ()
+ # How far back a first sync reaches, for a source that bounds one. A source that sets this
+ # reads `SourceInputs.history_start` instead of resolving a constant against the day it runs.
+ # See `sources/common/history_window.py`.
+ history_lookback: datetime.timedelta | None = None
+
@property
@abstractmethod
def source_type(self) -> ExternalDataSourceType:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py
new file mode 100644
index 000000000000..6946c0557c96
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py
@@ -0,0 +1,72 @@
+"""Where a sync with no cursor starts reading.
+
+A source that bounds a first sync to a lookback resolves it against today, so a re-import — which
+arrives with no cursor — narrows the range to the last window and the drain never walks back. The
+schema records the answer once instead.
+
+Still resolving it per run: `adobe_analytics`, `hatchet`, and `google_play_console`, whose own
+`resolve_history_start` is this name for the opposite idea.
+"""
+
+import uuid
+import datetime as dt
+from typing import TYPE_CHECKING
+
+from django.utils import timezone
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
+def history_start_for_schema(
+ schema: "ExternalDataSchema", current_job_id: str | uuid.UUID, now: dt.datetime | None = None
+) -> dt.datetime | None:
+ """The oldest point this schema covers, or None for no bound.
+
+ Written on a first sync, the one moment the lookback is the truthful answer. A schema already
+ holding data covers a range nobody recorded, and inventing one declares away the rest.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob # noqa: PLC0415
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import ( # noqa: PLC0415
+ SourceRegistry,
+ )
+ from products.warehouse_sources.backend.types import ExternalDataSourceType # noqa: PLC0415
+
+ try:
+ source = SourceRegistry.get_source(ExternalDataSourceType(schema.source.source_type))
+ except ValueError:
+ # An unknown type means the source's module failed to import, not that it reads everything.
+ # Both answer None here, so say which one this was rather than leave a widened range
+ # looking like a declared one.
+ logger.warning("history_window.unknown_source_type", source_type=schema.source.source_type)
+ return None
+
+ lookback = source.history_lookback
+ if lookback is None:
+ return None
+
+ if schema.history_start is not None:
+ return schema.history_start
+
+ # Whether a run before this one imported anything, not whether a table exists: `delete_table`
+ # nulls the table link on a schema that has synced for years, and jobs outlive the wipe.
+ #
+ # Rows landed rather than the job row itself, because a job is created several activities before
+ # the import runs and outlives every way a run can end early — a billing limit, a cancellation, a
+ # deploy. Counting those would leave the schema unrecorded forever, reading unbounded on every
+ # re-import. This run's own job is excluded too: it is created before this call, and a retry of
+ # this activity may already have landed rows under it.
+ if ExternalDataJob.objects.filter(schema_id=schema.pk, rows_synced__gt=0).exclude(pk=current_job_id).exists():
+ return None
+
+ # `update_fields` because the pipeline loaded this instance before the run linked its table.
+ # `skip_activity_log` for the reasons `save` gives: it avoids a read that fails the import on a
+ # dropped pooler connection, and forces an UPDATE rather than resurrecting a deleted row.
+ schema.history_start = (now or timezone.now()) - lookback
+ schema.save(update_fields=["history_start"], skip_activity_log=True)
+
+ return schema.history_start
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py
new file mode 100644
index 000000000000..37ed533c42d2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py
@@ -0,0 +1,139 @@
+import datetime as dt
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.history_window import (
+ history_start_for_schema,
+)
+
+NOW = dt.datetime(2026, 7, 17, tzinfo=dt.UTC)
+
+
+class TestHistoryStartForSchema(BaseTest):
+ def _schema(self, **kwargs) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(team=self.team, source_type="GoogleAds", job_inputs={})
+ return ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name="campaign_stats",
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={"incremental_field": "segments.date", "incremental_field_type": "date"},
+ **kwargs,
+ )
+
+ def test_a_schema_that_never_synced_starts_its_window_now(self):
+ schema = self._schema()
+
+ assert self._resolve(schema) == NOW - dt.timedelta(days=2 * 365)
+
+ schema.refresh_from_db()
+ assert schema.history_start == NOW - dt.timedelta(days=2 * 365)
+
+ def test_the_recorded_start_is_not_moved_by_a_later_run(self):
+ # Recording it once is the whole mechanism. Re-deriving it per run is what this replaces.
+ recorded = dt.datetime(2020, 2, 8, tzinfo=dt.UTC)
+ schema = self._schema(history_start=recorded)
+
+ assert self._resolve(schema) == recorded
+
+ def _job(self, schema: ExternalDataSchema, *, running: bool = False) -> ExternalDataJob:
+ return ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING if running else ExternalDataJob.Status.COMPLETED,
+ rows_synced=0 if running else 1,
+ workflow_id="wf",
+ )
+
+ def _resolve(self, schema: ExternalDataSchema) -> dt.datetime | None:
+ """Call it the way the activity does: this run's job row already exists."""
+ return history_start_for_schema(schema, self._job(schema, running=True).pk, now=NOW)
+
+ def test_a_schema_already_syncing_records_nothing(self):
+ # The lookback is only truthful for a schema with nothing yet. One already holding data
+ # covers a range nobody recorded, so it reads as unbounded rather than as a guess.
+ table = DataWarehouseTable.objects.create(team=self.team, name="campaign_stats", format="Delta")
+ schema = self._schema(table=table)
+ self._job(schema)
+
+ assert self._resolve(schema) is None
+
+ schema.refresh_from_db()
+ assert schema.history_start is None
+
+ def test_a_prior_run_that_landed_nothing_still_counts_as_a_first_sync(self):
+ # A job row is created several activities before the import runs, and outlives every way a
+ # run ends early — a billing limit, a cancellation, a deploy. Counting those would leave the
+ # schema unrecorded forever and reading unbounded on every re-import.
+ schema = self._schema()
+ ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=ExternalDataJob.Status.BILLING_LIMIT_REACHED,
+ rows_synced=0,
+ workflow_id="wf",
+ )
+
+ assert self._resolve(schema) == NOW - dt.timedelta(days=2 * 365)
+
+ def test_a_schema_whose_table_was_deleted_records_nothing(self):
+ # `delete_table` nulls the table link on a schema that has synced for years, so the table
+ # link cannot stand in for "never synced". Recording a lookback here writes down a narrower
+ # range than the schema covered, which every later re-import would then honour.
+ schema = self._schema()
+ self._job(schema)
+
+ assert self._resolve(schema) is None
+
+ schema.refresh_from_db()
+ assert schema.history_start is None
+
+ def test_recording_skips_the_activity_log(self):
+ # Pipeline bookkeeping, on a path where the extra read the audit trail needs fails the
+ # import when the pooler has dropped the connection mid-sync.
+ schema = self._schema()
+
+ with mock.patch.object(ExternalDataSchema, "save", autospec=True) as saved:
+ self._resolve(schema)
+
+ assert saved.call_args.kwargs["skip_activity_log"] is True
+
+ def test_a_source_without_a_window_records_nothing(self):
+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe", job_inputs={})
+ schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="charges")
+
+ assert self._resolve(schema) is None
+
+ schema.refresh_from_db()
+ assert schema.history_start is None
+
+ def test_recording_does_not_write_the_rest_of_the_row(self):
+ # The pipeline holds this instance from before the run linked its table, so a full save
+ # would put back the values it was loaded with.
+ schema = self._schema()
+ ExternalDataSchema.objects.filter(pk=schema.pk).update(status="Completed")
+
+ self._resolve(schema)
+
+ schema.refresh_from_db()
+ assert schema.status == "Completed"
+
+
[email protected]("source_type", ["GoogleAds"])
+def test_a_declared_window_is_reachable_through_the_registry(source_type: str) -> None:
+ # The declaration has to be readable without importing the source module, which for Google Ads
+ # would drag the vendor SDK onto a path that only wants a timedelta.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+ from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+ lookback = SourceRegistry.get_source(ExternalDataSourceType(source_type)).history_lookback
+
+ assert lookback == dt.timedelta(days=2 * 365)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
index 0c5492594459..b3a1c47d481d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
@@ -2,6 +2,7 @@
# module is reachable from warehouse_sources models at django.setup().
from __future__ import annotations
+import datetime
import dataclasses
from collections.abc import AsyncIterable, Callable, Iterable
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional, Protocol, TypeVar
@@ -79,7 +80,9 @@ class SourceResponse:
"""xmin syncs: epoch (high 32 bits of `xmin_ceiling_xid8`) at this run's ceiling."""
+# Not frozen: nothing mutates it in place today, so freezing it is plausible, but every source
+# reads it and that migration is its own change to make and verify.
[email protected](frozen=False)
class SourceInputs:
"""Contextual info required by a source to actually run"""
@@ -95,6 +98,12 @@ class SourceInputs:
job_id: str
logger: FilteringBoundLogger
reset_pipeline: bool
+ # `db_incremental_field_last_value` as stored, before the lookback shifted it back. Rows at or
+ # before it are overlap the table already holds rather than new ground.
+ db_incremental_field_last_value_before_lookback: Optional[Any] = None
+ # Resolved from the schema for a source that declares a `history_lookback`; `None` means
+ # unbounded. See `sources/common/history_window.py`.
+ history_start: Optional[datetime.datetime] = None
enabled_columns: Optional[list[str]] = None
row_filters: Optional[list[ValidatedRowFilter]] = None
# Multi-schema import context, read by `resolve_source_location`.
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 a5ea7ee26dfc..bd7c9f02b51f 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
@@ -16,6 +16,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
GoogleAdsSourceConfig,
)
+# Declared as the source's `history_lookback`. Not an API limit — Google serves older rows, so
+# this costs first-sync catch-up time rather than correctness.
+GOOGLE_ADS_INITIAL_BACKFILL_DAYS = 2 * 365
+
@dataclasses.dataclass
class GoogleAdsResumeConfig:
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 38ddcfd77c60..95772c589d29 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
@@ -71,15 +71,15 @@ GOOGLE_ADS_HOST = "googleads.googleapis.com"
# single small window covers the tail, so this is a no-op for healthy tables. Tune to trade
# catch-up speed against per-run size.
GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS = 7
-GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN = 5
-# How far back a *first* sync starts its windowed drain. A first sync has no cursor to start from,
-# and the drain cannot begin at the 1970 incremental sentinel: empty windows are cheap but not free
-# (one request each), so stepping from 1970 would spend the whole run on requests that return
-# nothing. This bound only decides where the walk begins — every window from here forward is
-# imported, and once the cursor exists the drain continues from it. It is not an API limit: Google
-# serves older rows than this, so raising it costs first-sync catch-up time rather than correctness.
-GOOGLE_ADS_INITIAL_BACKFILL_DAYS = 2 * 365
+# Wall time, not a count of windows: a window is anywhere from empty to a full day of rows, so a
+# count has to suit the widest one and then throttles every table to it. Bounds time spent importing
+# new ground rather than the run — see the arming rule in the drain loop.
+GOOGLE_ADS_MAX_DRAIN_SECONDS = 10 * 60
+
+# Lower bound for the "where does this resource's data begin" request. Google serves a date this old
+# and returns nothing from before an account existed, so it needs no per-account tuning.
+_GOOGLE_ADS_EARLIEST_QUERYABLE_DATE = "1970-01-01"
# The Google Ads SDK hardcodes `grpc.max_receive_message_length` to 64 MiB. A single
# `GoogleAdsService.Search` page can carry up to 10,000 rows, and wide resources routinely
@@ -484,6 +484,36 @@ def get_schemas(config: GoogleAdsSourceConfigUnion, team_id: int, api_version: s
return table_schemas
+def _earliest_date_with_data(
+ service: "GoogleAdsSearchService",
+ customer_id: str | None,
+ table: "GoogleAdsTable",
+ incremental_field: str,
+) -> dt.date | None:
+ """Return the first date this resource holds rows for, or None when it holds none.
+
+ How the drain reaches an unbounded range cheaply: it walks fixed windows and each empty one is a
+ request, so starting at the sentinel would spend the run on requests that return nothing. Google
+ sorts and truncates server-side, so this costs one request whatever the account holds. It
+ locates a range rather than choosing one — that is the schema's `history_start`.
+ """
+ query = (
+ f"SELECT {incremental_field} FROM {table.name} "
+ f"WHERE {incremental_field} >= '{_GOOGLE_ADS_EARLIEST_QUERYABLE_DATE}' "
+ f"AND {incremental_field} < '{(dt.date.today() + dt.timedelta(days=1)).isoformat()}'"
+ )
+ if table.extra_where:
+ query += f" AND {table.extra_where}"
+ query += f" ORDER BY {incremental_field} ASC LIMIT 1"
+
+ # Through the wrapper, so a manager account's missing login-customer-id header recovers here the
+ # same way it does for the drain's own queries.
+ for row in _search_with_transient_retry(service, {"customer_id": customer_id, "query": query}):
+ return dt.date.fromisoformat(_traverse_attributes(row, *incremental_field.split(".")))
+
+ return None
+
+
def _incremental_value_as_date(value: dt.date | dt.datetime | str) -> dt.date:
"""Coerce a stored incremental cursor value to a plain date for window arithmetic.
@@ -507,6 +537,8 @@ def google_ads_source(
db_incremental_field_last_value: typing.Any = None,
incremental_field: str | None = None,
incremental_field_type: IncrementalFieldType | None = None,
+ db_incremental_field_last_value_before_lookback: typing.Any = None,
+ history_start: typing.Any = None,
) -> SourceResponse:
"""A data warehouse Google Ads source.
@@ -571,30 +603,48 @@ def google_ads_source(
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
- # Bounded windowed drain for date-partitioned report tables (`requires_filter`), including
- # the first sync. Excluding first syncs is what stranded them: with no cursor they ran a
- # single open-ended 1970..2100 scan over the whole account history, and a run that never
- # finishes never lands a chunk, so the cursor stays empty and the next run repeats the same
- # unbounded scan — the very death spiral the windows exist to break, except nothing could
- # escape it. A first sync instead starts a bounded backfill window behind today.
- #
- # Only incremental pipelines take this path. The per-run window budget assumes the cursor
- # lands between runs so the next run continues where this one stopped. A full-refresh run
- # persists no cursor, so a budgeted drain restarts from the same backfill date every run,
- # and the refresh then replaces the whole table with that same first slice of history:
- # silent data loss that reports Completed.
+ # Date-partitioned report tables drain in bounded ascending windows rather than one
+ # open-ended scan (see the module constants). A full-refresh pipeline persists no cursor, so
+ # a budgeted drain would restart from the same date every run and the refresh would replace
+ # the table with that one slice; only incremental pipelines, which land a cursor between
+ # runs, take this path.
if pipeline_is_incremental and table.requires_filter and incremental_field_type == IncrementalFieldType.Date:
- start = (
- _incremental_value_as_date(db_incremental_field_last_value)
- if db_incremental_field_last_value is not None
- else dt.date.today() - dt.timedelta(days=GOOGLE_ADS_INITIAL_BACKFILL_DAYS)
- )
+ if db_incremental_field_last_value is not None:
+ 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.
+ cursor_before_lookback = (
+ _incremental_value_as_date(db_incremental_field_last_value_before_lookback)
+ if db_incremental_field_last_value_before_lookback is not None
+ 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()
+ cursor_before_lookback = start
+ logger.info(
+ "google_ads.history_start_used",
+ resource=table.name,
+ start=start.isoformat(),
+ bounded=history_start is not None,
+ )
+
# Exclusive upper bound of today+1 keeps today in range, matching the open-ended scan.
end = dt.date.today() + dt.timedelta(days=1)
- windows_with_data = 0
+ landed_new_ground = False
first_window = True
+ # The load side pulls this generator, so elapsed covers writing each window out too.
+ drain_started = time.monotonic()
+
+ while start < end:
+ if landed_new_ground and time.monotonic() - drain_started >= GOOGLE_ADS_MAX_DRAIN_SECONDS:
+ break
- while start < end and windows_with_data < GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN:
window_end = min(start + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS), end)
window_query = compose_query(f"'{start.isoformat()}'", f"'{window_end.isoformat()}'")
@@ -605,10 +655,12 @@ def google_ads_source(
had_data = True
yield pa_table
- # Empty windows don't count toward the per-run budget and don't stop the loop, so a
- # gap in the data is crossed within a single run instead of stalling the cursor on it.
- if had_data:
- windows_with_data += 1
+ # Arms the budget on new ground only, so a run that has not moved the cursor cannot
+ # be stopped and left for the next run to repeat. `start`, not `window_end`: the
+ # query is `>= start`, so a window merely ending past the cursor can hold only
+ # overlap rows at or before it.
+ if had_data and start > cursor_before_lookback:
+ landed_new_ground = True
first_window = False
start = window_end
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 aeddc14ddeeb..5b93038e7ed1 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
@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
GoogleAdsSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.configs import (
+ GOOGLE_ADS_INITIAL_BACKFILL_DAYS,
GoogleAdsResumeConfig,
GoogleAdsServiceAccountSourceConfig,
clean_customer_id,
@@ -99,6 +100,8 @@ class GoogleAdsSource(
VersionDeprecation(version="v24", sunset_at=None),
)
+ history_lookback = datetime.timedelta(days=GOOGLE_ADS_INITIAL_BACKFILL_DAYS)
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GOOGLEADS
@@ -243,6 +246,8 @@ class GoogleAdsSource(
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
+ db_incremental_field_last_value_before_lookback=inputs.db_incremental_field_last_value_before_lookback,
+ history_start=inputs.history_start,
)
@property
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 bd27c744c368..c7c45607c84f 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
@@ -1,6 +1,7 @@
import re
import typing
import datetime as dt
+import itertools
import collections.abc
from types import SimpleNamespace
@@ -39,7 +40,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (
GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS,
- GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN,
GoogleAdsColumn,
GoogleAdsSearchService,
GoogleAdsTable,
@@ -1427,6 +1427,7 @@ class TestGoogleAdsQueryConstruction:
*,
api_version: str = "v23",
window_rows: dict[str, int] | None = None,
+ earliest_date: str | None = None,
**source_kwargs,
):
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (
@@ -1449,10 +1450,20 @@ class TestGoogleAdsQueryConstruction:
assert table.alias is not None
config = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1)
+
+ def fake_probe(_service, request):
+ queries.append(request["query"])
+ if earliest_date is None:
+ return iter([])
+ row = mock.Mock()
+ row.segments.date = earliest_date
+ return iter([row])
+
with (
mock.patch(f"{self._MODULE}.get_schemas", return_value={table.alias: table}),
mock.patch(f"{self._MODULE}.google_ads_client"),
mock.patch(f"{self._MODULE}._search_as_arrow_tables", side_effect=fake_search),
+ mock.patch(f"{self._MODULE}._search_with_transient_retry", side_effect=fake_probe),
):
response = google_ads_source(
config,
@@ -1485,28 +1496,139 @@ class TestGoogleAdsQueryConstruction:
assert all("2100-01-01" not in q for q in queries)
assert response.sort_mode == "asc"
- def test_first_sync_drains_in_windows_from_a_bounded_backfill_start(self):
- # A first sync has no cursor. Running it as the open-ended `1970 .. 2100` scan meant one run
- # had to extract the whole account history before anything landed durably; it never
- # finished, so the cursor never advanced and the next run repeated the same scan — report
- # tables that had never synced could never start. It must window like any other run,
- # beginning a bounded backfill behind today.
+ def test_lookback_overlap_cannot_consume_a_whole_run(self):
+ # Spending the whole budget on lookback overlap leaves the cursor unmoved, so the next run
+ # repeats it and a schema behind by more than its lookback never advances.
+ clock = itertools.count()
+
+ with freeze_time("2026-07-17"), mock.patch(f"{self._MODULE}.time.monotonic", lambda: next(clock)):
+ # A budget of zero: the overlap alone would end the run before any new ground.
+ with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", 0):
+ _response, queries = self._run_source(
+ self._stats_table(),
+ should_use_incremental_field=True,
+ # A 2026-05-04 cursor, already shifted back 30 days by the caller.
+ db_incremental_field_last_value=dt.date(2026, 4, 4),
+ db_incremental_field_last_value_before_lookback=dt.date(2026, 5, 4),
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ window_rows=dict.fromkeys(
+ (
+ # Overlap the lookback re-reads.
+ "2026-04-04",
+ "2026-04-11",
+ "2026-04-18",
+ "2026-04-25",
+ # New ground past the cursor.
+ "2026-05-02",
+ "2026-05-09",
+ ),
+ 5,
+ ),
+ )
+
+ assert queries[0].startswith(
+ "SELECT campaign.id,segments.date FROM campaign_stats WHERE segments.date >= '2026-04-04'"
+ )
+ # The first window starting strictly past the cursor, so its rows are all new ground.
+ assert "segments.date >= '2026-05-09'" in queries[-1]
+
+ def test_a_straddling_window_of_only_overlap_rows_cannot_stop_the_drain(self):
+ # The same stall via a straddling window: it can hold only rows at or before the cursor, so
+ # arming on `window_end` rather than `start` stops the run with the cursor unmoved.
+ cursor = dt.date(2026, 1, 1)
+ w = GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS
+ # The pre-lookback cursor is 2026-01-31, straddled by the window starting 2026-01-29.
+ overlap_and_straddle = {(cursor + dt.timedelta(days=w * i)).isoformat(): 1 for i in range(5)}
+ data_past_gap = cursor + dt.timedelta(days=w * 22) # 2026-06-04, after a run of empty windows
+ # One second per loop check against a two-second budget: it is spent long before the walk
+ # reaches the data, so only refusing to arm on the straddle keeps the run going.
+ clock = itertools.count()
+
+ with freeze_time("2026-12-31"), mock.patch(f"{self._MODULE}.time.monotonic", lambda: next(clock)):
+ with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", 2):
+ _response, queries = self._run_source(
+ self._stats_table(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cursor,
+ db_incremental_field_last_value_before_lookback=dt.date(2026, 1, 31),
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ window_rows={**overlap_and_straddle, data_past_gap.isoformat(): 1},
+ )
+
+ assert any(f"segments.date >= '{data_past_gap.isoformat()}'" in q for q in queries)
+
+ @pytest.mark.parametrize(
+ "history_start,expected_start",
+ [
+ # A run with no cursor reads the recorded range, first sync or re-import alike.
+ ("2020-02-08", "2020-02-08"),
+ ("2025-03-01", "2025-03-01"),
+ ],
+ )
+ def test_drain_starts_at_the_schema_history_start(self, history_start, expected_start: 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,
+ history_start=history_start,
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ )
+
+ assert f"WHERE segments.date >= '{expected_start}'" in queries[0]
+ assert all("LIMIT 1" not in q for q in queries), "a recorded range needs no request to locate it"
+ # 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("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
+ ) -> None:
+ # A schema that predates the recorded range reads unbounded: one request locates the start,
+ # and an account holding nothing has no range to walk.
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,
+ history_start=None,
+ earliest_date=earliest_date,
incremental_field="segments.date",
incremental_field_type=IncrementalFieldType.Date,
)
assert queries[0] == (
- "SELECT campaign.id,segments.date FROM campaign_stats "
- "WHERE segments.date >= '2024-07-17' AND segments.date < '2024-07-24' "
- "ORDER BY segments.date ASC"
+ "SELECT segments.date FROM campaign_stats "
+ "WHERE segments.date >= '1970-01-01' AND segments.date < '2026-07-18' "
+ "ORDER BY segments.date ASC LIMIT 1"
+ )
+ assert f"WHERE segments.date >= '{expected_start}'" in queries[1]
+
+ def test_the_probe_repeats_the_resource_filter(self):
+ # Five report resources append `metrics.impressions > 0`. Without it the probe reports a
+ # start earlier than the first row the drain will import, and that start gets recorded.
+ table = self._stats_table()
+ table.extra_where = "metrics.impressions > 0"
+
+ with freeze_time("2026-07-17"):
+ _response, queries = self._run_source(
+ table,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ history_start=None,
+ earliest_date="2020-02-08",
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ )
+
+ assert queries[0] == (
+ "SELECT segments.date FROM campaign_stats "
+ "WHERE segments.date >= '1970-01-01' AND segments.date < '2026-07-18' "
+ "AND metrics.impressions > 0 ORDER BY segments.date ASC LIMIT 1"
)
- assert all("2100-01-01" not in q for q in queries)
- assert all("1970-01-01" not in q for q in queries)
def test_full_refresh_report_table_scans_the_full_range_without_windows(self):
# A full-refresh pipeline persists no cursor, so a budgeted windowed drain restarts from
@@ -1524,27 +1646,31 @@ class TestGoogleAdsQueryConstruction:
"ORDER BY segments.date ASC"
]
- def test_run_stops_after_max_data_windows(self):
- # Every window has data; the run must stop after GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN
- # non-empty windows so a single run stays short enough to complete and durably advance the
- # cursor, instead of re-extracting the whole backlog and dying to a heartbeat timeout.
+ # Parametrized so the count tracks the budget. A single case landing on five windows is the
+ # same number the deleted `MAX_DATA_WINDOWS_PER_RUN = 5` produced, so it could not tell the two
+ # rules apart.
+ @pytest.mark.parametrize("budget,expected_windows", [(4, 5), (9, 10), (19, 20)])
+ def test_a_run_takes_as_many_windows_as_the_budget_buys(self, budget: int, expected_windows: int) -> None:
cursor = dt.date(2026, 1, 1)
window_rows = {
- (cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * i)).isoformat(): 1
- for i in range(GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN + 3)
+ (cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * i)).isoformat(): 1 for i in range(40)
}
+ # One second of drain per loop check. The first window starts at the cursor, so its rows are
+ # not guaranteed past it and it does not arm the budget; the budget buys the rest.
+ clock = itertools.count()
+
+ with freeze_time("2026-07-17"), mock.patch(f"{self._MODULE}.time.monotonic", lambda: next(clock)):
+ with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", budget):
+ _response, queries = self._run_source(
+ self._stats_table(),
+ window_rows=window_rows,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cursor,
+ incremental_field="segments.date",
+ incremental_field_type=IncrementalFieldType.Date,
+ )
- with freeze_time("2026-07-17"):
- _response, queries = self._run_source(
- self._stats_table(),
- window_rows=window_rows,
- should_use_incremental_field=True,
- db_incremental_field_last_value=cursor,
- incremental_field="segments.date",
- incremental_field_type=IncrementalFieldType.Date,
- )
-
- assert len(queries) == GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN
+ assert len(queries) == expected_windows
assert "WHERE segments.date >= '2026-01-01' AND segments.date < '2026-01-08'" in queries[0]
def test_empty_windows_are_crossed_within_one_run(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index dc770744164e..970bc17ea1bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -62,6 +62,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag import (
is_fanout_warehouse_reuse_enabled,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.history_window import (
+ history_start_for_schema,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_context import bind_job_context
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientNonRetryableError,
@@ -306,6 +309,8 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
processed_incremental_last_value = None
processed_incremental_earliest_value = None
+ # The cursor as stored, before the lookback shift below moves it back.
+ incremental_last_value_before_lookback = None
if reset_pipeline is not True:
processed_incremental_last_value = process_incremental_value(
@@ -322,6 +327,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
# overlap window and catches late or backdated rows. Incremental merge makes the
# re-read idempotent — append would duplicate, so it's gated to incremental.
if schema.is_incremental:
+ incremental_last_value_before_lookback = processed_incremental_last_value
processed_incremental_last_value = apply_incremental_lookback(
processed_incremental_last_value,
schema.incremental_field_type,
@@ -334,6 +340,11 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
if processed_incremental_earliest_value:
await logger.adebug(f"Incremental earliest value being used is: {processed_incremental_earliest_value}")
+ # None for a source that reads everything, which is most of them.
+ history_start = await database_sync_to_async_pool(history_start_for_schema)(schema, inputs.run_id)
+ if history_start is not None:
+ await logger.adebug(f"History start for this schema is: {history_start}")
+
# Re-validate against current metadata so a stale filter (dropped column, changed type)
# fails here with an actionable message rather than emitting a broken query downstream.
try:
@@ -375,6 +386,8 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
db_incremental_field_earliest_value=processed_incremental_earliest_value
if schema.should_use_incremental_field
else None,
+ db_incremental_field_last_value_before_lookback=incremental_last_value_before_lookback,
+ history_start=history_start,
logger=logger,
job_id=inputs.run_id,
reset_pipeline=reset_pipeline,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 441949a58c0e..a5e7b47cb193 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -562,13 +562,15 @@ def _inputs_no_reset() -> ImportDataActivityInputs:
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "is_incremental,expected_last_value",
+ "is_incremental,expected_last_value,expected_before_lookback",
[
- (True, datetime(2026, 6, 14, 14, 33, 31, 802833)),
- (False, datetime(2026, 6, 14, 15, 33, 31, 802833)),
+ (True, datetime(2026, 6, 14, 14, 33, 31, 802833), datetime(2026, 6, 14, 15, 33, 31, 802833)),
+ (False, datetime(2026, 6, 14, 15, 33, 31, 802833), None),
],
)
-async def test_incremental_lookback_shifts_query_value_not_stored_watermark(is_incremental, expected_last_value):
+async def test_incremental_lookback_shifts_query_value_not_stored_watermark(
+ is_incremental, expected_last_value, expected_before_lookback
+):
source = mock.MagicMock(spec=SimpleSource)
source.parse_config.return_value = {}
source.source_for_pipeline.return_value = mock.MagicMock()
@@ -580,6 +582,10 @@ async def test_incremental_lookback_shifts_query_value_not_stored_watermark(is_i
_, source_inputs = source.source_for_pipeline.call_args.args
assert source_inputs.db_incremental_field_last_value == expected_last_value
assert schema.sync_type_config["incremental_field_last_value"] == "2026-06-14T15:33:31.802833"
+ # The unshifted cursor travels alongside the shifted one. A consumer needs both to tell overlap
+ # from new ground, and capturing it after the shift would make them equal and silently disarm
+ # that rule with every test still passing.
+ assert source_inputs.db_incremental_field_last_value_before_lookback == expected_before_lookback
@pytest.mark.asyncio