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-imports): complete zero-row syncs without extracting (#86729)

Daniel RCe10c64df980f
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index bede22c9e082..de5a9d56e805 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1356,7 +1356,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py
1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
-1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
1 products/web_analytics/backend/hogql_queries/bot_definitions.py
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index e1f736c07db9..d08e6fd3e9e5 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -401,6 +401,15 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return None
+ @property
+ def last_full_run_at(self) -> str | None:
+ """ISO timestamp of the last run that actually extracted, so a schema completing on a
+ negative probe still gets one full run per interval (see `_fast_return_eligible`)."""
+ if self.sync_type_config:
+ return self.sync_type_config.get("last_full_run_at", None)
+
+ return None
+
@property
def incremental_field_lookback_seconds(self) -> int | None:
if self.sync_type_config:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 84151fa8ad62..5a9ad16ee4bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -52,6 +52,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
)
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
get_data_import_finished_metric,
+ get_fast_returned_run_metric,
get_v3_lock_skipped_metric,
get_version_check_skipped_metric,
)
@@ -633,6 +634,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
enrichment_needed = False
statistics_needed = False
person_property_sync_enabled = False
+ fast_return_eligible = False
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -643,6 +645,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
enrichment_needed = create_job_result.enrichment_needed
statistics_needed = create_job_result.statistics_needed
person_property_sync_enabled = create_job_result.person_property_sync_enabled
+ fast_return_eligible = create_job_result.fast_return_eligible
update_inputs.job_id = str(job_id) if job_id is not None else None
# Check billing limits
@@ -690,6 +693,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
schema_id=inputs.external_data_schema_id,
source_id=inputs.external_data_source_id,
reset_pipeline=inputs.reset_pipeline,
+ fast_return_eligible=fast_return_eligible,
)
is_resumable_source = False
@@ -739,6 +743,12 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
consumer_manages_job_status = pipeline_result.get("consumer_manages_job_status", False)
skip_post_import_activities = pipeline_result.get("skip_post_import_activities", False)
+ # A fast-returned run completed on a negative source probe, before any extraction.
+ # Its skip_post_import_activities=True does the actual skipping below; the job row,
+ # COMPLETED status and last_synced_at are all written as usual.
+ if pipeline_result.get("fast_returned", False):
+ get_fast_returned_run_metric(source_type=source_type).add(1)
+
# The load-dependent post-import steps have one home: `data-import-post-import`
# (post_import_job.py). V3 with batches: the load consumer starts it after the final
# batch is loaded, so the steps must not race the load from here. Everywhere else:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index 00aa0314a060..afe42f4c7cb8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -48,6 +48,16 @@ def get_data_import_finished_metric(source_type: str | None, status: str) -> Met
)
+def get_fast_returned_run_metric(source_type: str | None) -> MetricCounter:
+ # Separate from `data_import_finished` (which still counts these as completed) so the
+ # rollout can be read as a share of runs without double-counting them there.
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown"})
+ .create_counter("data_import_fast_returned", "Runs completed on a negative source probe, without extracting.")
+ )
+
+
def get_v3_lock_skipped_metric() -> MetricCounter:
# A skipped run leaves no job row and no schema-status change; without this
# counter a schema can silently miss every scheduled slot for days.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
index 2d077c617f89..48b06535a83f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
@@ -12,7 +12,6 @@ import asyncio
from typing import TYPE_CHECKING, Any
from django.conf import settings
-from django.db import InterfaceError, OperationalError
from django.utils import timezone
import deltalake as deltalake
@@ -21,7 +20,6 @@ from dateutil import parser
from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
-from posthog.temporal.common.utils import retry_on_db_connection_drop
from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -39,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DELTA_COARSEN_DECLINE_TOTAL,
DELTA_REPARTITION_SKIP_TOTAL,
)
+from products.warehouse_sources.backend.temporal.data_imports.schema_flags import is_schema_flag_enabled
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -103,59 +102,15 @@ def repartition_oom_window_days() -> int:
def is_auto_repartition_enabled(schema: ExternalDataSchema) -> bool:
- return _is_flag_enabled(schema, WAREHOUSE_AUTO_REPARTITION_FLAG)
+ return is_schema_flag_enabled(schema, WAREHOUSE_AUTO_REPARTITION_FLAG)
def is_auto_coarsen_enabled(schema: ExternalDataSchema) -> bool:
- return _is_flag_enabled(schema, WAREHOUSE_AUTO_COARSEN_FLAG)
+ return is_schema_flag_enabled(schema, WAREHOUSE_AUTO_COARSEN_FLAG)
def is_repartition_hold_enabled(schema: ExternalDataSchema) -> bool:
- return _is_flag_enabled(schema, WAREHOUSE_REPARTITION_HOLD_FLAG)
-
-
-def _is_flag_enabled(schema: ExternalDataSchema, flag: str) -> bool:
- """Evaluate a rollout flag for this schema.
-
- `schema_id`, `team_id`, and `source_type` are passed as person properties so the flag can be
- released to a single table — set a release condition `schema_id = <id>` to dogfood the controller
- on one schema before rolling out by team/org/project.
- """
- from posthog.models import Team
-
- try:
- team = retry_on_db_connection_drop(lambda: Team.objects.only("uuid", "organization_id").get(id=schema.team_id))
- except Team.DoesNotExist:
- return False
- except (OperationalError, InterfaceError) as e:
- # retry_on_db_connection_drop already retried once; a second failure is a genuinely degraded
- # DB, not a bug here. Some callers (repartition_table.py) evaluate this flag with no enclosing
- # try/except, so this function's contract of "never raises, defaults to disabled" must hold on
- # its own.
- capture_exception(e)
- return False
- try:
- return bool(
- posthoganalytics.feature_enabled(
- flag,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- person_properties={
- "schema_id": str(schema.id),
- "team_id": str(schema.team_id),
- "source_type": schema.source.source_type,
- },
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception as e:
- capture_exception(e)
- return False
+ return is_schema_flag_enabled(schema, WAREHOUSE_REPARTITION_HOLD_FLAG)
def base_event_props(schema: ExternalDataSchema, source: ExternalDataSource, job_id: str | None) -> dict[str, Any]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
index 665c59888c20..e289d9318f88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
@@ -29,7 +29,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
-from products.warehouse_sources.backend.temporal.data_imports import workload_report
+from products.warehouse_sources.backend.temporal.data_imports import schema_flags, workload_report
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition_controller as ctrl
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
@@ -304,7 +304,7 @@ class TestIsAutoRepartitionEnabled:
with (
patch("posthog.models.Team.objects.only", return_value=mock_queryset),
- patch.object(ctrl, "capture_exception") as mock_capture_exception,
+ patch.object(schema_flags, "capture_exception") as mock_capture_exception,
):
assert ctrl.is_auto_repartition_enabled(schema) is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
index 166538fbee4b..322f799079fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
@@ -21,9 +21,14 @@ class PipelineResult(TypedDict):
runs some other party already finalized, where True likewise means "workflow: hands off".
Making this a pure version property requires an empty-final-batch queue message so the
consumer hears about every v3 run — deferred until the v2 pipeline is deleted.
+
+ `fast_returned` marks a run completed on a negative source probe, before any extraction.
+ It always rides with `skip_post_import_activities=True` (which does the actual skipping);
+ the workflow reads it only to count these runs separately from other skipped ones.
"""
should_trigger_cdp_producer: bool
consumer_manages_job_status: NotRequired[bool]
skip_post_import_activities: NotRequired[bool]
prepared_queryable_folder: NotRequired[str]
+ fast_returned: NotRequired[bool]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 299d53b30d70..2617d5ffd9c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -1,4 +1,5 @@
import uuid
+import datetime as dt
from dataclasses import dataclass
from datetime import date, datetime
from typing import Any, Optional
@@ -27,6 +28,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
mark_initial_sync_complete,
+ update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
@@ -125,11 +127,16 @@ async def update_last_synced_at(job_id: str, schema_id: str, team_id: int) -> No
@retry_on_operational_error
def _update():
job = ExternalDataJob.objects.get(pk=job_id)
- schema = ExternalDataSchema.objects.exclude(deleted=True).get(id=schema_id, team_id=team_id)
- schema.last_synced_at = job.created_at
- # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
- # `_get_before_update` SELECT that also needs a pooler connection (see save()).
- schema.save(skip_activity_log=True)
+ # `last_full_run_at` rides along in the same locked write: only a run that reached
+ # post-load extracted anything, which is what bounds how long a schema can go on
+ # negative probes alone (see `_fast_return_eligible`). The helper's select_for_update
+ # also stops this save from clobbering a concurrent `sync_type_config` update.
+ update_sync_type_config_keys(
+ schema_id,
+ team_id,
+ updates={"last_full_run_at": dt.datetime.now(dt.UTC).isoformat()},
+ extra_model_fields={"last_synced_at": job.created_at},
+ )
await _update()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
index e86985b16494..a6e1288fa697 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
@@ -372,25 +372,36 @@ class TestUpdateLastSyncedAt:
# failing the whole import activity over a momentary blip.
job = MagicMock()
get_job = MagicMock(side_effect=[OperationalError("query_wait_timeout"), job])
- schema = MagicMock()
- get_schema = MagicMock(return_value=schema)
+ update_keys = MagicMock()
with (
patch(f"{_PIPELINE_SYNC_MODULE}.ExternalDataJob.objects.get", get_job),
- patch(
- f"{_PIPELINE_SYNC_MODULE}.ExternalDataSchema.objects.exclude", return_value=MagicMock(get=get_schema)
- ),
+ patch(f"{_PIPELINE_SYNC_MODULE}.update_sync_type_config_keys", update_keys),
patch(f"{_DB_RETRY_MODULE}.close_old_connections") as close,
patch(f"{_DB_RETRY_MODULE}.time.sleep") as sleep,
):
await update_last_synced_at(job_id="job-1", schema_id="schema-1", team_id=1)
assert get_job.call_count == 2
- assert schema.last_synced_at == job.created_at
- schema.save.assert_called_once_with(skip_activity_log=True)
+ update_keys.assert_called_once()
+ assert update_keys.call_args.kwargs["extra_model_fields"] == {"last_synced_at": job.created_at}
close.assert_called_once()
sleep.assert_called_once_with(2)
+ @pytest.mark.asyncio
+ async def test_stamps_the_full_run_marker(self):
+ # `_fast_return_eligible` reads this to force one extracting run per interval, so a run
+ # that reaches post-load must leave it behind.
+ update_keys = MagicMock()
+
+ with (
+ patch(f"{_PIPELINE_SYNC_MODULE}.ExternalDataJob.objects.get", MagicMock(return_value=MagicMock())),
+ patch(f"{_PIPELINE_SYNC_MODULE}.update_sync_type_config_keys", update_keys),
+ ):
+ await update_last_synced_at(job_id="job-1", schema_id="schema-1", team_id=1)
+
+ assert "last_full_run_at" in update_keys.call_args.kwargs["updates"]
+
class TestSetInitialSyncComplete(BaseTest):
"""The purge-then-flip contract: a CDC snapshot schema's buffer prefix is purged before the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/schema_flags.py b/products/warehouse_sources/backend/temporal/data_imports/schema_flags.py
new file mode 100644
index 000000000000..17a0c9aac966
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/schema_flags.py
@@ -0,0 +1,70 @@
+"""Per-schema rollout flags for the import pipeline.
+
+A leaf module (no deltalake/pyarrow, no pipeline imports) so an activity can gate on a flag
+without pulling the Delta stack into its import graph.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.db import InterfaceError, OperationalError
+
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.utils import retry_on_db_connection_drop
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+# Rollout for completing a run on a negative source probe (see `_fast_return_eligible`).
+WAREHOUSE_FAST_RETURN_FLAG = "data-warehouse-fast-return"
+
+
+def is_fast_return_enabled(schema: ExternalDataSchema) -> bool:
+ return is_schema_flag_enabled(schema, WAREHOUSE_FAST_RETURN_FLAG)
+
+
+def is_schema_flag_enabled(schema: ExternalDataSchema, flag: str) -> bool:
+ """Evaluate a rollout flag for this schema.
+
+ `schema_id`, `team_id`, and `source_type` are passed as person properties so the flag can be
+ released to a single table — set a release condition `schema_id = <id>` to dogfood a feature
+ on one schema before rolling out by team/org/project.
+ """
+ from posthog.models import Team # noqa: PLC0415 — keeps this module importable before app registry setup
+
+ try:
+ team = retry_on_db_connection_drop(lambda: Team.objects.only("uuid", "organization_id").get(id=schema.team_id))
+ except Team.DoesNotExist:
+ return False
+ except (OperationalError, InterfaceError) as e:
+ # retry_on_db_connection_drop already retried once; a second failure is a genuinely degraded
+ # DB, not a bug here. Some callers (repartition_table.py) evaluate this flag with no enclosing
+ # try/except, so this function's contract of "never raises, defaults to disabled" must hold on
+ # its own.
+ capture_exception(e)
+ return False
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ flag,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ person_properties={
+ "schema_id": str(schema.id),
+ "team_id": str(schema.team_id),
+ "source_type": schema.source.source_type,
+ },
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
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 96eb7396f882..0e56eeeb10d7 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
@@ -97,6 +97,9 @@ SourceCredentialsValidationResult = tuple[bool, str | None]
# opaque vendor labels (Stripe date versions, semver, names) — never parsed or ordered.
UNVERSIONED_API_VERSION = "v1"
+# Wall-clock bound on `probe_new_data` before the import falls back to the full sync.
+FAST_RETURN_PROBE_TIMEOUT = datetime.timedelta(minutes=2)
+
def error_message_matches(error_msg: str, patterns: Iterable[str]) -> bool:
"""Case-insensitive match of `error_msg` against `get_non_retryable_errors`/`get_retryable_errors` patterns.
@@ -352,6 +355,21 @@ class _BaseSource(ABC, Generic[ConfigType]):
instance being validated, or ``None`` (→ `default_version`) before a row exists."""
return True, None
+ def probe_new_data(self, config: ConfigType, inputs: SourceInputs) -> bool | None:
+ """Whether the source has data past this schema's stored watermark.
+
+ `False` lets the run complete without extracting anything, so only return it when the
+ source is provably unchanged. `None` (the default) means "unknown" and runs the normal
+ sync, which is also the right answer for any error: never let a probe failure suppress
+ a sync. Callers guarantee the schema is incremental/append, past its initial sync, and
+ has no repair work pending.
+
+ The caller stops waiting after FAST_RETURN_PROBE_TIMEOUT but cannot interrupt this
+ method's thread, so implementations should bound their own remote call below that limit
+ (for example a server-side statement timeout) to avoid orphaned queries.
+ """
+ return None
+
def get_endpoint_permissions(
self, config: ConfigType, team_id: int, endpoints: list[str], api_version: str | None = None
) -> dict[str, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index de108da3eba6..92799ba7c9a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -2021,6 +2021,42 @@ def _capture_xmin_ceiling(
)
+def build_incremental_condition(
+ incremental_field: str,
+ incremental_field_type: IncrementalFieldType,
+ db_incremental_field_last_value: Any,
+ *,
+ upper_bound_inclusive: Optional[Any] = None,
+) -> sql.Composed:
+ """The `field <op> watermark` predicate every incremental read of a table shares.
+
+ One builder so the streaming read, the row count and the has-new-rows probe cannot drift
+ apart on the operator or on how a missing watermark is normalized. A probe whose predicate
+ is narrower than the read's would report "nothing new" for rows the read would return.
+
+ `>=` for Date comes from `incremental_type_to_operator`; a windowed read passes
+ `upper_bound_inclusive` and keeps `>`, because consecutive windows reuse the previous
+ window's high value as the next one's low and `>=` would re-fetch the boundary rows.
+ """
+ if incremental_field_type == IncrementalFieldType.XID:
+ raise ValueError(XMIN_AS_INCREMENTAL_FIELD_ERROR)
+
+ # A stored watermark of "" (a stale or corrupted sync_type_config value) must not become a
+ # literal `''`: Postgres rejects casting it against a numeric/date column with "invalid input
+ # syntax", so treat it the same as no watermark at all.
+ if db_incremental_field_last_value is None or db_incremental_field_last_value == "":
+ db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
+
+ operator = (
+ sql.SQL(incremental_type_to_operator(incremental_field_type)) if upper_bound_inclusive is None else sql.SQL(">")
+ )
+ return sql.SQL("{incremental_field} {op} {last_value}").format(
+ incremental_field=sql.Identifier(incremental_field),
+ op=operator,
+ last_value=sql.Literal(db_incremental_field_last_value),
+ )
+
+
def _build_query(
schema: str,
table_name: str,
@@ -2085,36 +2121,20 @@ def _build_query(
# `xmin` is a synthetic system column with no ordering operators against a plain integer
# (see `_xmin_predicate`) — it only works through the dedicated xmin replication sync type,
# which never reaches this generic path (it always sets `xmin_bounds` and returns above).
- # Picking `xmin` as a plain incremental/append field builds `"xmin" >= 0`, which Postgres
- # rejects with `UndefinedFunction`.
- if incremental_field_type == IncrementalFieldType.XID:
- raise ValueError(XMIN_AS_INCREMENTAL_FIELD_ERROR)
-
- # A stored watermark of "" (e.g. a stale/corrupted sync_type_config value) must not become a
- # literal `''` in the WHERE clause — Postgres rejects casting it against a numeric/date/etc.
- # column with "invalid input syntax", so treat it the same as no watermark at all.
- if db_incremental_field_last_value is None or db_incremental_field_last_value == "":
- db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
-
- # Use the type-aware operator (`>=` for Date) only for single-shot scans. Windowed
- # scans (upper_bound_inclusive set) must keep `>` because consecutive windows use the
- # previous window's hi as the next window's lo — `>=` would re-fetch every row at the
- # boundary value, duplicating each window's hi inside a single run.
- operator = (
- sql.SQL(incremental_type_to_operator(incremental_field_type)) if upper_bound_inclusive is None else sql.SQL(">")
+ incremental_condition = build_incremental_condition(
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ upper_bound_inclusive=upper_bound_inclusive,
)
if add_sampling:
if table_type == "view":
- query = sql.SQL(
- "SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value} AND random() < 0.01"
- ).format(
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {predicate} AND random() < 0.01").format(
cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
- incremental_field=sql.Identifier(incremental_field),
- op=operator,
- last_value=sql.Literal(db_incremental_field_last_value),
+ predicate=incremental_condition,
)
else:
# Sized like the full-refresh sample, but never below the fixed 1% this has always
@@ -2124,25 +2144,20 @@ def _build_query(
# to fall under 1% keeps exactly the sample it has today, where the slice it filters
# to is the part the estimate cannot speak for.
query = sql.SQL(
- "SELECT {cols} FROM {schema}.{table} TABLESAMPLE SYSTEM ({percent}) "
- "WHERE {incremental_field} {op} {last_value}"
+ "SELECT {cols} FROM {schema}.{table} TABLESAMPLE SYSTEM ({percent}) WHERE {predicate}"
).format(
percent=sql.Literal(max(sample_percent, 1.0) if sample_percent is not None else 1),
cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
- incremental_field=sql.Identifier(incremental_field),
- op=operator,
- last_value=sql.Literal(db_incremental_field_last_value),
+ predicate=incremental_condition,
)
else:
- query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {predicate}").format(
cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
- incremental_field=sql.Identifier(incremental_field),
- op=operator,
- last_value=sql.Literal(db_incremental_field_last_value),
+ predicate=incremental_condition,
)
if add_sampling:
@@ -2228,19 +2243,38 @@ def _build_count_query(
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
- if incremental_field_type == IncrementalFieldType.XID:
- raise ValueError(XMIN_AS_INCREMENTAL_FIELD_ERROR)
+ return sql.SQL("SELECT COUNT(*) FROM {schema}.{table} WHERE {predicate}").format(
+ schema=sql.Identifier(schema),
+ table=sql.Identifier(table_name),
+ predicate=build_incremental_condition(
+ incremental_field, incremental_field_type, db_incremental_field_last_value
+ ),
+ )
- if db_incremental_field_last_value is None or db_incremental_field_last_value == "":
- db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
- operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
- return sql.SQL("SELECT COUNT(*) FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
+def build_has_new_rows_query(
+ schema: str,
+ table_name: str,
+ incremental_field: str,
+ incremental_field_type: IncrementalFieldType,
+ db_incremental_field_last_value: Any,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
+) -> sql.Composed:
+ """Existence check over the same rows `_build_query` would stream.
+
+ Shares its predicate and row filters, and drops only what a "does anything match" question
+ does not need: the projection, the ordering, and every row past the first. No
+ `upper_bound_inclusive` either, since that windows one run's reads rather than defining what
+ counts as new.
+ """
+ conditions = [
+ build_incremental_condition(incremental_field, incremental_field_type, db_incremental_field_last_value),
+ *render_psycopg_row_filter_conditions(row_filters or []),
+ ]
+ return sql.SQL("SELECT 1 FROM {schema}.{table} WHERE {predicate} LIMIT 1").format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
- incremental_field=sql.Identifier(incremental_field),
- op=operator,
- last_value=sql.Literal(db_incremental_field_last_value),
+ predicate=and_join(conditions),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 360549e5e107..e4b7a47c6be1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -23,7 +23,10 @@ from posthog.exceptions_capture import capture_exception
from products.data_warehouse.backend.facade.api import reconcile_postgres_schemas
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ FAST_RETURN_PROBE_TIMEOUT,
+ FieldType,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
SSHTunnelMixin,
ValidateDatabaseHostMixin,
@@ -32,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.reg
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import resolve_source_location
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (
PostgresSourceConfig,
@@ -52,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
SSLRequiredError,
_rls_active_from_conn,
_xmin_capable_tables_from_conn,
+ build_has_new_rows_query,
filter_postgres_incremental_fields,
get_connection_metadata as get_postgres_connection_metadata,
get_foreign_keys as get_postgres_foreign_keys,
@@ -216,6 +221,9 @@ PostgresErrors = {
_POSTGRES_IMPLEMENTATION = PostgresImplementation()
+# Just under the caller's wall-clock bound so the probe query dies server-side first.
+_PROBE_STATEMENT_TIMEOUT_MS = int((FAST_RETURN_PROBE_TIMEOUT.total_seconds() - 10) * 1000)
+
RLS_WARNING_MESSAGE = (
"Row-level security is active on this table for the sync role, so PostHog can only read "
"rows the policy permits, and cannot detect how many rows are hidden. "
@@ -1335,6 +1343,63 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
finally:
conn.close()
+ def probe_new_data(self, config: PostgresSourceConfig, inputs: SourceInputs) -> bool | None:
+ """One indexed existence check against the same predicate the sync would run.
+
+ Returns None for anything this cannot answer with certainty — a non-incremental schema, a
+ cursor Postgres tracks itself (xmin, CDC), or any error reaching the source — so the
+ caller runs the full sync.
+ """
+ # Deferred like the sibling read path below: the source registry imports this module at
+ # startup, before the Django app registry is ready to hand out models.
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema # noqa: PLC0415
+
+ if (
+ not inputs.should_use_incremental_field
+ or inputs.incremental_field is None
+ or inputs.incremental_field_type is None
+ or inputs.incremental_field_type == IncrementalFieldType.XID
+ or inputs.db_incremental_field_last_value is None
+ ):
+ return None
+
+ try:
+ schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)
+ if schema.is_cdc or schema.is_xmin:
+ return None
+
+ location = resolve_source_location(inputs, config_namespace=config.schema, default="public")
+ if location.schema is None:
+ return None
+
+ query = build_has_new_rows_query(
+ schema=location.schema,
+ table_name=location.table_name,
+ incremental_field=inputs.incremental_field,
+ incremental_field_type=inputs.incremental_field_type,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ row_filters=inputs.row_filters,
+ )
+ require_ssl = source_requires_ssl(schema.source, config)
+ with self.get_implementation.connect(config, require_ssl=require_ssl) as conn:
+ # Autocommit so a rejected SET (engines without statement_timeout support) is its
+ # own statement and cannot poison the probe query's transaction.
+ conn.autocommit = True
+ with conn.cursor() as cursor:
+ # The caller stops waiting after FAST_RETURN_PROBE_TIMEOUT but cannot
+ # interrupt this thread, so cap the query server-side just under that: on an
+ # unindexed watermark column, proving "no new rows" is a full scan, and the
+ # cap turns it into a clean fallback instead of an orphaned query.
+ try:
+ cursor.execute(f"SET statement_timeout = {_PROBE_STATEMENT_TIMEOUT_MS}")
+ except Exception:
+ pass
+ cursor.execute(query)
+ return cursor.fetchone() is not None
+ except Exception as e:
+ inputs.logger.debug(f"probe_new_data: falling back to a full sync: {e}", exc_info=e)
+ return None
+
def _buffered_cdc_source(self, schema: "ExternalDataSchema", inputs: SourceInputs) -> SourceResponse | None:
"""A `SourceResponse` reading this schema's S3 change buffer, or None if it isn't flipped.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_has_new_rows_query.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_has_new_rows_query.py
new file mode 100644
index 000000000000..247df6b1d9ca
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_has_new_rows_query.py
@@ -0,0 +1,76 @@
+"""The probe query must ask exactly what the sync query asks.
+
+A probe predicate narrower than the sync's reports "nothing new" for rows the sync would
+have read, and the run completes having silently skipped them. Nothing else in the fast
+return catches that, so these lock the two predicates together.
+"""
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
+ ColumnTypeCategory,
+ ValidatedRowFilter,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (
+ _build_query,
+ build_has_new_rows_query,
+)
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+_FILTERS = [ValidatedRowFilter(column="region", operator="=", value="eu", category=ColumnTypeCategory.STRING)]
+
+
+def _sync_predicate(field_type, last_value, row_filters) -> str:
+ query = _build_query(
+ schema="public",
+ table_name="orders",
+ should_use_incremental_field=True,
+ table_type="table",
+ incremental_field="updated_at",
+ incremental_field_type=field_type,
+ db_incremental_field_last_value=last_value,
+ row_filters=row_filters,
+ ).as_string()
+ return query.split(" WHERE ", 1)[1].split(" ORDER BY ")[0]
+
+
+def _probe_predicate(field_type, last_value, row_filters) -> str:
+ query = build_has_new_rows_query(
+ schema="public",
+ table_name="orders",
+ incremental_field="updated_at",
+ incremental_field_type=field_type,
+ db_incremental_field_last_value=last_value,
+ row_filters=row_filters,
+ ).as_string()
+ return query.split(" WHERE ", 1)[1].removesuffix(" LIMIT 1")
+
+
+class TestBuildHasNewRowsQuery:
+ @parameterized.expand(
+ [
+ ("datetime", IncrementalFieldType.DateTime, "2026-08-01", None),
+ ("integer", IncrementalFieldType.Integer, 42, None),
+ ("date_uses_inclusive_operator", IncrementalFieldType.Date, "2026-08-01", None),
+ ("empty_watermark_falls_back", IncrementalFieldType.Integer, "", None),
+ ("with_row_filters", IncrementalFieldType.DateTime, "2026-08-01", _FILTERS),
+ ("integer_with_row_filters", IncrementalFieldType.Integer, 42, _FILTERS),
+ ]
+ )
+ def test_predicate_matches_the_sync_query(self, _name: str, field_type, last_value, row_filters):
+ assert _probe_predicate(field_type, last_value, row_filters) == _sync_predicate(
+ field_type, last_value, row_filters
+ )
+
+ def test_stops_at_the_first_matching_row(self):
+ query = build_has_new_rows_query(
+ schema="public",
+ table_name="orders",
+ incremental_field="updated_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2026-08-01",
+ ).as_string()
+
+ assert query.startswith("SELECT 1 ")
+ assert query.endswith("LIMIT 1")
+ assert "ORDER BY" not in query
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
index a9a093661cd8..72e7295da167 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
@@ -56,7 +56,13 @@ _JOB_ID = "01960000-0000-0000-0000-000000000000"
def _stub_activities(
- executed: list[str], *, is_v3: bool, consumer_manages_job_status: bool, skip_post_import_activities: bool = False
+ executed: list[str],
+ *,
+ is_v3: bool,
+ consumer_manages_job_status: bool,
+ skip_post_import_activities: bool = False,
+ fast_return_eligible: bool = False,
+ source_has_new_data: bool = True,
) -> list:
@activity.defn(name="check_pipeline_version_activity")
async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:
@@ -85,6 +91,7 @@ def _stub_activities(
enrichment_needed=True,
statistics_needed=True,
person_property_sync_enabled=True,
+ fast_return_eligible=fast_return_eligible,
)
@activity.defn(name="check_billing_limits_activity")
@@ -99,6 +106,12 @@ def _stub_activities(
@activity.defn(name="import_data_activity_sync")
async def import_data(inputs: ImportDataActivityInputs) -> PipelineResult:
executed.append("import_data_activity_sync")
+ if inputs.fast_return_eligible and not source_has_new_data:
+ return PipelineResult(
+ should_trigger_cdp_producer=False,
+ skip_post_import_activities=True,
+ fast_returned=True,
+ )
return PipelineResult(
should_trigger_cdp_producer=False,
consumer_manages_job_status=consumer_manages_job_status,
@@ -132,7 +145,12 @@ def _stub_activities(
async def _run_workflow(
- *, is_v3: bool, consumer_manages_job_status: bool, skip_post_import_activities: bool = False
+ *,
+ is_v3: bool,
+ consumer_manages_job_status: bool,
+ skip_post_import_activities: bool = False,
+ fast_return_eligible: bool = False,
+ source_has_new_data: bool = True,
) -> tuple[list[str], list[str]]:
"""Run the workflow with stubbed activities; return (executed activities + child starts in
order, started child ids)."""
@@ -161,6 +179,8 @@ async def _run_workflow(
is_v3=is_v3,
consumer_manages_job_status=consumer_manages_job_status,
skip_post_import_activities=skip_post_import_activities,
+ fast_return_eligible=fast_return_eligible,
+ source_has_new_data=source_has_new_data,
),
workflow_runner=UnsandboxedWorkflowRunner(),
activity_executor=ThreadPoolExecutor(max_workers=10),
@@ -240,6 +260,34 @@ async def test_post_import_fork(
assert "create_source_templates" in executed
+ "fast_return_eligible,source_has_new_data,expect_fast_return",
+ [
+ pytest.param(True, False, True, id="eligible_and_source_unchanged_fast_returns"),
+ pytest.param(True, True, False, id="eligible_but_source_changed_syncs"),
+ pytest.param(False, False, False, id="not_eligible_runs_the_full_path"),
+ ],
+)
+async def test_fast_return_skips_post_import_only_when_the_source_is_unchanged(
+ fast_return_eligible: bool, source_has_new_data: bool, expect_fast_return: bool
+):
+ executed, child_ids = await _run_workflow(
+ is_v3=False,
+ consumer_manages_job_status=False,
+ fast_return_eligible=fast_return_eligible,
+ source_has_new_data=source_has_new_data,
+ )
+
+ assert "import_data_activity_sync" in executed
+ assert "update_external_data_job_model" in executed
+ if expect_fast_return:
+ assert "create_source_templates" not in executed
+ assert child_ids == []
+ else:
+ assert "create_source_templates" in executed
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"steps_mode",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index 37da6bb9dbdf..bd9a76498435 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -1,5 +1,6 @@
import uuid
import typing
+import datetime as dt
import dataclasses
from typing import Any
@@ -24,6 +25,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exter
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ data_quality_checks_needed_for,
emit_signals_enabled_for,
person_property_sync_enabled_for,
schema_binding,
@@ -34,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.d
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
get_v3_pipeline_lock_holder,
)
+from products.warehouse_sources.backend.temporal.data_imports.schema_flags import is_fast_return_enabled
WAREHOUSE_PIPELINES_V3_FLAG = "warehouse-pipelines-v3"
@@ -190,6 +193,65 @@ class CreateExternalDataJobModelActivityInputs:
}
+FAST_RETURN_FULL_RUN_INTERVAL = dt.timedelta(hours=24)
+
+
+def _fast_return_eligible(
+ *,
+ schema: ExternalDataSchema,
+ team_id: int,
+ enrichment_needed: bool,
+ statistics_needed: bool,
+) -> bool:
+ """Whether this run may complete on a negative probe instead of extracting.
+
+ Every condition here answers one of two questions: is the schema's own state simple enough
+ that "no new source rows" means "nothing to do" (cursor-tracked, past its initial sync, no
+ reset or repartition in flight), and does the pipeline owe this schema any repair work that
+ only a full run performs? A repair loop that runs solely on the sync path — the managed-view
+ sync, DuckLake copies, the person-property prefix sweep — would never run again on a schema
+ that always fast-returns, so anything outstanding forces the full path, and
+ FAST_RETURN_FULL_RUN_INTERVAL forces one anyway for whatever this list cannot see.
+ """
+ if not is_fast_return_enabled(schema):
+ return False
+ if not (schema.is_incremental or schema.is_append):
+ return False
+ # xmin and CDC keep their cursor outside `incremental_field_last_value`, and a webhook
+ # schema's "source" is an S3 prefix rather than a queryable cursor.
+ if schema.is_xmin or schema.is_cdc or schema.is_webhook:
+ return False
+ if not schema.initial_sync_complete or schema.incremental_field_last_value is None:
+ return False
+ if schema.reset_pipeline:
+ return False
+ # A lookback deliberately re-reads rows at or before the watermark, so "nothing past the
+ # watermark" does not mean the sync would have written nothing.
+ if schema.incremental_field_lookback_seconds:
+ return False
+ if (
+ schema.repartition_pending is not None
+ or schema.repartition_swap is not None
+ or schema.delta_revive_required is not None
+ ):
+ return False
+ if enrichment_needed or statistics_needed:
+ return False
+ if data_quality_checks_needed_for(team_id, schema.table_id):
+ return False
+
+ last_full_run_at = schema.last_full_run_at
+ if last_full_run_at is None:
+ return False
+ try:
+ stamped = dt.datetime.fromisoformat(last_full_run_at)
+ except (TypeError, ValueError):
+ return False
+ if stamped.tzinfo is None:
+ return False
+ return dt.datetime.now(dt.UTC) - stamped < FAST_RETURN_FULL_RUN_INTERVAL
+
+
@dataclasses.dataclass(frozen=True)
class CreateExternalDataJobModelActivityOutputs:
job_id: str
@@ -213,6 +275,11 @@ class CreateExternalDataJobModelActivityOutputs:
# True when the schema feeds at least one enabled person-target Customer analytics source, so the
# workflow should start the person-property sync child. Gated up front to avoid a no-op child per sync.
person_property_sync_enabled: bool = False
+ # True when this run may complete without extracting if the source proves it has nothing new:
+ # the schema tracks a cursor, is past its initial sync, and no repair work is outstanding.
+ # Computed here because this activity already resolves the repair gates the decision needs.
+ # Defaults False so a payload from a worker that predates the field takes the full path.
+ fast_return_eligible: bool = False
@activity.defn
@@ -302,6 +369,13 @@ def create_external_data_job_model_activity(
# customer_analytics via external_product_hooks; not imported here).
person_property_sync_enabled = person_property_sync_enabled_for(inputs.team_id, schema_binding(schema.id))
+ fast_return_eligible = _fast_return_eligible(
+ schema=schema,
+ team_id=inputs.team_id,
+ enrichment_needed=enrichment_needed,
+ statistics_needed=statistics_needed,
+ )
+
return CreateExternalDataJobModelActivityOutputs(
job_id=str(job.id),
incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,
@@ -314,6 +388,7 @@ def create_external_data_job_model_activity(
enrichment_needed=enrichment_needed,
statistics_needed=statistics_needed,
person_property_sync_enabled=person_property_sync_enabled,
+ fast_return_eligible=fast_return_eligible,
)
except Exception as e:
logger.exception(
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 0df096a9a084..674db365165f 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
@@ -15,6 +15,7 @@ from structlog.typing import FilteringBoundLogger
from temporalio import activity
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.integration_secrets.errors import IntegrationSecretsFailure
from posthog.models.integration import UndecryptedIntegrationSecretError
@@ -57,6 +58,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_tracking
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ FAST_RETURN_PROBE_TIMEOUT,
AnySource,
ResumableSource,
SimpleSource,
@@ -90,13 +92,17 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
LOGGER = get_logger(__name__)
+@frozen
class ImportDataActivityInputs:
team_id: int
schema_id: uuid.UUID
source_id: uuid.UUID
run_id: str
reset_pipeline: Optional[bool] = None
+ # From `create_external_data_job_model_activity` (`_fast_return_eligible`): the schema tracks
+ # a cursor, is past its initial sync, and owes no repair work, so a negative probe may
+ # complete this run without extracting. Defaults False so old payloads keep the full path.
+ fast_return_eligible: bool = False
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -106,6 +112,7 @@ class ImportDataActivityInputs:
"source_id": self.source_id,
"run_id": self.run_id,
"reset_pipeline": self.reset_pipeline,
+ "fast_return_eligible": self.fast_return_eligible,
}
@@ -259,6 +266,37 @@ def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: Filt
return True
+async def _probe_found_new_data(
+ source: AnySource,
+ config: Any,
+ source_inputs: SourceInputs,
+ logger: FilteringBoundLogger,
+) -> bool:
+ """False only when the source proves it has nothing past the watermark; True on any doubt.
+
+ The timeout bounds how long the run waits, but cannot interrupt the probe's thread: a probe
+ stuck on a remote call keeps running until the source's own bound fires (implementations cap
+ their query server-side, see `probe_new_data`). Either way this run continues into the full
+ sync, so a slow or broken probe costs time, never data.
+ """
+ try:
+ has_new_data = await asyncio.wait_for(
+ database_sync_to_async_pool(source.probe_new_data)(config, source_inputs),
+ timeout=FAST_RETURN_PROBE_TIMEOUT.total_seconds(),
+ )
+ except TimeoutError:
+ await logger.ainfo("Fast-return probe timed out, running the full sync")
+ return True
+ except Exception as e:
+ await logger.ainfo(f"Fast-return probe failed, running the full sync: {e}")
+ return True
+
+ if has_new_data is False:
+ await logger.ainfo("Fast-return probe: source has no new data")
+ return False
+ return True
+
+
@activity.defn
async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> PipelineResult:
bind_contextvars(team_id=inputs.team_id)
@@ -496,6 +534,26 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, str(e), logger, e
)
+ # Probing before source setup is what makes the fast return cheap: everything past
+ # this point (connections, metadata queries, the delta log read) is spent whether or
+ # not the sync has anything to move. The probe reads the same `source_inputs` the
+ # extraction below would, so watermark processing and row filters cannot drift.
+ # `reset_pipeline` is re-checked here because a reset asked for through the workflow
+ # input never reaches `sync_type_config`, which is all eligibility can see.
+ if inputs.fast_return_eligible and not reset_pipeline:
+ if not await _probe_found_new_data(new_source, config, source_inputs, logger):
+ # The run checked the source, so the schema must not read as stale. Mirrors
+ # `update_last_synced_at` on the extracting path (which also stamps
+ # `last_full_run_at`; a fast return deliberately does not).
+ await database_sync_to_async_pool(
+ ExternalDataSchema.objects.filter(id=schema.id, team_id=inputs.team_id).update
+ )(last_synced_at=model.created_at, updated_at=dt.datetime.now(dt.UTC))
+ return PipelineResult(
+ should_trigger_cdp_producer=False,
+ skip_post_import_activities=True,
+ fast_returned=True,
+ )
+
resumable_source_manager: ResumableSourceManager | None = None
try:
if isinstance(new_source, ResumableSource):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py
new file mode 100644
index 000000000000..5a81bf4a8655
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py
@@ -0,0 +1,113 @@
+"""Eligibility for completing a run on a negative source probe.
+
+Every condition here exists because skipping a run that owed repair work broke something:
+a repair loop that only runs on the sync path stops running at all on a schema that always
+fast-returns. A dropped condition is silent until a customer notices stale state.
+"""
+
+import uuid
+import datetime as dt
+
+from freezegun import freeze_time
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
+ _fast_return_eligible,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model"
+
+
+def _recent() -> str:
+ return (dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)).isoformat()
+
+
+def _schema(**config_overrides) -> ExternalDataSchema:
+ config = {
+ "incremental_field": "updated_at",
+ "incremental_field_type": "datetime",
+ "incremental_field_last_value": "2026-08-01T00:00:00+00:00",
+ "last_full_run_at": _recent(),
+ }
+ config.update(config_overrides)
+ return ExternalDataSchema(
+ id=uuid.uuid4(),
+ name="orders",
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ initial_sync_complete=True,
+ sync_type_config=config,
+ )
+
+
+def _run(schema: ExternalDataSchema, *, enrichment=False, statistics=False, data_quality=False, flag_enabled=True):
+ with (
+ patch(f"{_MODULE}.data_quality_checks_needed_for", return_value=data_quality),
+ patch(f"{_MODULE}.is_fast_return_enabled", return_value=flag_enabled),
+ ):
+ return _fast_return_eligible(
+ schema=schema,
+ team_id=1,
+ enrichment_needed=enrichment,
+ statistics_needed=statistics,
+ )
+
+
+class TestFastReturnEligibility:
+ def test_steady_state_incremental_schema_is_eligible(self):
+ assert _run(_schema()) is True
+
+ @parameterized.expand(
+ [
+ ("full_refresh", ExternalDataSchema.SyncType.FULL_REFRESH),
+ ("cdc", ExternalDataSchema.SyncType.CDC),
+ ("xmin", ExternalDataSchema.SyncType.XMIN),
+ ("webhook", ExternalDataSchema.SyncType.WEBHOOK),
+ ]
+ )
+ def test_sync_types_without_a_queryable_cursor_are_not_eligible(self, _name: str, sync_type: str):
+ schema = _schema()
+ schema.sync_type = sync_type
+
+ assert _run(schema) is False
+
+ @parameterized.expand(
+ [
+ ("no_watermark", {"incremental_field_last_value": None}),
+ ("reset_pending", {"reset_pipeline": True}),
+ ("lookback_rereads_rows", {"incremental_field_lookback_seconds": 3600}),
+ ("repartition_pending", {"repartition_pending": {"partition_mode": "md5"}}),
+ ("repartition_swap", {"repartition_swap": {"state": "ready"}}),
+ ("delta_revive_required", {"delta_revive_required": {"reason": "hollow"}}),
+ ("never_ran_fully", {"last_full_run_at": None}),
+ ("last_full_run_too_old", {"last_full_run_at": "2026-08-01T00:00:00+00:00"}),
+ ("unparseable_full_run_stamp", {"last_full_run_at": "not-a-date"}),
+ ]
+ )
+ def test_schema_state_that_blocks_eligibility(self, _name: str, config_overrides: dict):
+ assert _run(_schema(**config_overrides)) is False
+
+ @freeze_time("2026-08-24T12:00:00Z")
+ def test_naive_full_run_stamp_is_not_eligible(self):
+ assert _run(_schema(last_full_run_at="2026-08-24T11:00:00")) is False
+
+ def test_incomplete_initial_sync_is_not_eligible(self):
+ schema = _schema()
+ schema.initial_sync_complete = False
+
+ assert _run(schema) is False
+
+ @parameterized.expand(
+ [
+ ("enrichment", {"enrichment": True}),
+ ("statistics", {"statistics": True}),
+ ("data_quality", {"data_quality": True}),
+ ]
+ )
+ def test_outstanding_repair_work_blocks_eligibility(self, _name: str, gates: dict):
+ assert _run(_schema(), **gates) is False
+
+ def test_rollout_flag_off_is_not_eligible(self):
+ assert _run(_schema(), flag_enabled=False) is False
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 74dd471267e5..a3c0287fea00 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
@@ -62,17 +62,19 @@ def _passthrough(fn):
@contextlib.contextmanager
-def _patched_activity(source_mock):
+def _patched_activity(source_mock, model=None, schema=None):
"""Patch out every dependency import_data_activity_sync touches before source setup."""
- model = mock.MagicMock()
- model.pipeline.source_type = "MongoDB"
- model.pipeline.job_inputs = {}
- model.folder_path = mock.Mock(return_value="dataset")
-
- schema = mock.MagicMock()
- schema.should_use_incremental_field = False
- schema.row_filters = None
- schema.delta_revive_required = None
+ if model is None:
+ model = mock.MagicMock()
+ model.pipeline.source_type = "MongoDB"
+ model.pipeline.job_inputs = {}
+ model.folder_path = mock.Mock(return_value="dataset")
+
+ if schema is None:
+ schema = mock.MagicMock()
+ schema.should_use_incremental_field = False
+ schema.row_filters = None
+ schema.delta_revive_required = None
with (
mock.patch.object(module, "tag_queries"),
@@ -881,6 +883,130 @@ async def test_parent_gate_inert_for_sources_without_requirements():
flag_check.assert_not_called()
+def _probe_model() -> mock.MagicMock:
+ model = mock.MagicMock()
+ model.pipeline.source_type = "Postgres"
+ model.pipeline.job_inputs = {}
+ model.folder_path = mock.Mock(return_value="dataset")
+ return model
+
+
+def _probe_schema() -> mock.MagicMock:
+ schema = mock.MagicMock()
+ schema.id = uuid.uuid4()
+ schema.should_use_incremental_field = False
+ schema.is_incremental = False
+ schema.sync_type_config = {}
+ schema.incremental_field_earliest_value = None
+ schema.incremental_field_type = None
+ schema.row_filters = None
+ schema.schema_metadata = None
+ schema.delta_revive_required = None
+ return schema
+
+
+def _probe_source(probe: Any) -> mock.MagicMock:
+ source = mock.MagicMock(spec=SimpleSource)
+ source.parse_config.return_value = {}
+ source.get_non_retryable_errors.return_value = {}
+ source.get_required_parent_schemas.return_value = []
+ if isinstance(probe, Exception):
+ source.probe_new_data.side_effect = probe
+ else:
+ source.probe_new_data.return_value = probe
+ source.source_for_pipeline.return_value = mock.MagicMock()
+ return source
+
+
+def _probe_inputs(**overrides: Any) -> ImportDataActivityInputs:
+ kwargs: dict[str, Any] = {
+ "team_id": 1,
+ "schema_id": uuid.uuid4(),
+ "source_id": uuid.uuid4(),
+ "run_id": str(uuid.uuid4()),
+ "reset_pipeline": False,
+ "fast_return_eligible": True,
+ }
+ kwargs.update(overrides)
+ return ImportDataActivityInputs(**kwargs)
+
+
+_FULL_SYNC_RESULT: Any = {"should_trigger_cdp_producer": True}
+
+
+def _probe_ctx(source: mock.MagicMock, model: mock.MagicMock):
+ with (
+ _patched_activity(source, model=model, schema=_probe_schema()),
+ mock.patch.object(module, "history_start_for_schema", return_value=None),
+ mock.patch.object(module, "ExternalDataSchema") as schema_model,
+ mock.patch.object(module, "_run", new=mock.AsyncMock(return_value=_FULL_SYNC_RESULT)),
+ ):
+ yield schema_model
+
+
+async def test_fast_return_completes_without_source_setup():
+ model = _probe_model()
+ source = _probe_source(probe=False)
+
+ with _probe_ctx(source, model) as schema_model:
+ result = await import_data_activity_sync(_probe_inputs())
+
+ assert result == {
+ "should_trigger_cdp_producer": False,
+ "skip_post_import_activities": True,
+ "fast_returned": True,
+ }
+ source.source_for_pipeline.assert_not_called()
+ update = schema_model.objects.filter.return_value.update
+ update.assert_called_once()
+ assert update.call_args.kwargs["last_synced_at"] is model.created_at
+ assert set(update.call_args.kwargs) == {"last_synced_at", "updated_at"}
+
+
+ "probe",
+ [
+ pytest.param(True, id="source_has_new_data"),
+ pytest.param(None, id="source_cannot_answer"),
+ pytest.param(RuntimeError("probe blew up"), id="probe_raises"),
+ pytest.param(TimeoutError(), id="probe_times_out"),
+ ],
+)
+async def test_probe_uncertainty_runs_the_full_sync(probe: Any):
+ model = _probe_model()
+ source = _probe_source(probe=probe)
+
+ with _probe_ctx(source, model):
+ result = await import_data_activity_sync(_probe_inputs())
+
+ assert result is _FULL_SYNC_RESULT
+ source.probe_new_data.assert_called_once()
+ source.source_for_pipeline.assert_called_once()
+
+
+ "overrides",
+ [
+ pytest.param({"fast_return_eligible": False}, id="not_eligible"),
+ pytest.param({"reset_pipeline": True}, id="reset_requested"),
+ ],
+)
+async def test_probe_never_runs_when_not_eligible_or_resetting(overrides: dict[str, Any]):
+ model = _probe_model()
+ source = _probe_source(probe=False)
+
+ with _probe_ctx(source, model):
+ result = await import_data_activity_sync(_probe_inputs(**overrides))
+
+ assert result is _FULL_SYNC_RESULT
+ source.probe_new_data.assert_not_called()
+ source.source_for_pipeline.assert_called_once()
+
+
# Credentials the integration service holds are PostHog's own — the OAuth app secrets and API keys
# we own, not anything a customer configured. Every failure state it has is therefore ours, and
# every one of them ends on its own (a key in recovery is re-provisioned, a missing key is added, an