:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse): skip settled deployments in status reconciliation (#94610)
Raúl Negrón-Otero3faf8d5b180c
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.pyindex f83c31597be7..c88fc4224836 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@@ -108,6 +108,8 @@ class SourceInputs:# 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+ # Start of the previous successful sync (the job's created_at), so a safe lower bound for "seen".+ last_synced_at: Optional[datetime.datetime] = Noneenabled_columns: Optional[list[str]] = Nonerow_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/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex b27de9dc59dd..3ec1df3387f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -12,6 +12,7 @@ import pyarrow as paimport requestsfrom asgiref.sync import async_to_syncfrom dateutil import parser as dateutil_parser+from prometheus_client import Counterfrom structlog.types import FilteringBoundLoggerfrom temporalio import activityfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter@@ -47,6 +48,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.setGITHUB_BASE_URL = "https://api.github.com"+# A capped fan-out drops the oldest admitted parents, and the cursor still advances past them.+FAN_OUT_PARENT_CAP_HITS = Counter(+ "warehouse_github_fan_out_parent_cap_hits_total",+ "Fan-out walks that hit max_fan_out_parents and skipped older parents in the window.",+ labelnames=["endpoint"],+)++# The reconcile cursor is a PostHog job timestamp compared against GitHub's updated_at, so allow+# for clock skew between the two before trusting it to skip a parent.+_RECONCILE_SKEW_ALLOWANCE = timedelta(minutes=5)+# GitHub's date-based REST API versions are sent in the X-GitHub-Api-Version header. The header is# the only version-dependent part for the endpoints we sync — response shapes are compatible across# these versions. Every caller — sync, credential validation, webhook management — passes the@@ -1232,6 +1244,7 @@ def _fan_out_get_rows():continueif max_parents is not None and fanned_out_parents >= max_parents:+ FAN_OUT_PARENT_CAP_HITS.labels(endpoint=endpoint).inc()logger.warning("Github: fan-out parent cap reached; older parents in the window skipped",endpoint=endpoint,@@ -1489,6 +1502,7 @@ def github_source(egress_identity: GithubEgressIdentity | None = None,response_name: str | None = None,api_version: str = GITHUB_DEFAULT_API_VERSION,+ reconcile_since: datetime | None = None,) -> SourceResponse:endpoint_config = GITHUB_ENDPOINTS[endpoint]@@ -1566,9 +1580,8 @@ def github_source(# webhook drain would miss rollback/auto_inactive transitions; chase the drain with a# bounded fan-out over recent parents so those rows still arrive from the list API.# should_use_incremental_field is forced on so the fan-out applies the parent recency- # skip when a watermark exists. A webhook schema configures no incremental field, so in- # that case the watermark arrives as None and only the window override and the parent- # cap bound the walk.+ # skip. A webhook schema configures no incremental field, so the previous successful+ # sync's start (reconcile_since) stands in as the watermark.return _chain_webhook_items_with_reconciliation(webhook_items,lambda: get_rows(@@ -1578,19 +1591,15 @@ def github_source(logger=logger,resumable_source_manager=resumable_source_manager,should_use_incremental_field=True,- db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_last_value=db_incremental_field_last_value+ or (reconcile_since - _RECONCILE_SKEW_ALLOWANCE if reconcile_since else None),incremental_field=incremental_field,egress_identity=egress_identity,api_version=api_version,parent_cutoff_override=_now_utc() - timedelta(days=reconcile_days),- # The recency skip bounds the walk on its own once a watermark exists, and every- # parent it admits is known to hold an unseen child, so a count bound would drop- # one for good: the run advances the watermark past it either way.- max_parents=(- None- if isinstance(db_incremental_field_last_value, datetime)- else endpoint_config.max_fan_out_parents- ),+ # Stays on with a watermark so the first run after a long gap stays bounded. A parent+ # past the cap loses its inactive transition until GitHub updates it again.+ max_parents=endpoint_config.max_fan_out_parents,),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex ed9222659b37..130d7e4910ac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -370,7 +370,7 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# rollbacks and auto_inactive transitions, leaving a superseded deployment looking current.# Each sync therefore chases the webhook drain with a bounded reconciliation fan-out over# deployments created in the last 30 days; the updated_at recency skip keeps that to- # parents that actually gained a status since the child watermark.+ # parents that actually gained a status since the previous successful sync started.initial_lookback_days=0,webhook_reconcile_lookback_days=30,# Statuses stop arriving within hours of the deployment, and 500 spans over a day even on adiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.pyindex 354bea59afe1..864484651d8a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py@@ -958,7 +958,6 @@ If automatic creation failed with a permissions error, the fix depends on how yoinputs.s3_folder_name if isinstance(inputs.s3_folder_name, str) and inputs.s3_folder_name else None)response_name = NamingConvention.normalize_identifier(storage_key or inputs.schema_name)-return github_source(personal_access_token=access_token,repository=repository,@@ -970,6 +969,7 @@ If automatic creation failed with a permissions error, the fix depends on how yoif inputs.should_use_incremental_fieldelse None,incremental_field=inputs.incremental_field,+ reconcile_since=inputs.last_synced_at,webhook_source_manager=webhook_source_manager,egress_identity=egress_identity,response_name=response_name,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.pyindex bbc94361470c..e2e5224c00cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py@@ -712,6 +712,7 @@ class TestGithubSource:inputs.schema_metadata = Noneinputs.s3_folder_name = "issues"inputs.should_use_incremental_field = False+ inputs.last_synced_at = datetime.datetime(2026, 9, 8, tzinfo=datetime.UTC)self.source.source_for_pipeline(config, mock.MagicMock(), inputs)@@ -719,6 +720,7 @@ class TestGithubSource:assert kwargs["repository"] == "legacy/repo"assert kwargs["endpoint"] == "issues"assert kwargs["response_name"] == "issues"+ assert kwargs["reconcile_since"] == inputs.last_synced_at@pytest.mark.parametrize("pin,expected",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.pyindex b2cd277ce76c..6ddd00d1513d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py@@ -137,18 +137,16 @@ def test_webhook_enabled_deployment_statuses_reconciles_inactive_statuses() -> N@pytest.mark.parametrize(- "watermark_offset,expected_parents",+ "reconcile_since_offset",[- # No watermark: the recency skip is inert, so the cap is the only bound, and it keeps the- # newest parents.- (None, ["1", "2"]),- # Watermark set: every parent past the skip is known to hold an unseen child, and the run- # advances the watermark past it either way, so capping would drop it permanently.- (timedelta(days=3), ["1", "2", "3", "4"]),+ # First sync: no watermark, so the cap is the only bound and keeps the newest parents.+ None,+ # Every parent updated since the last sync: the cap still bounds the run.+ timedelta(days=3),],)def test_webhook_enabled_deployment_statuses_reconciliation_caps_the_parent_fan_out(- watermark_offset: timedelta | None, expected_parents: list[str]+ reconcile_since_offset: timedelta | None,) -> None:now = datetime(2026, 7, 24, 12, 0, 0, tzinfo=UTC)@@ -190,16 +188,15 @@ def test_webhook_enabled_deployment_statuses_reconciliation_caps_the_parent_fan_endpoint="deployment_statuses",logger=mock.Mock(),resumable_source_manager=_no_resume(),- should_use_incremental_field=True,- db_incremental_field_last_value=None if watermark_offset is None else now - watermark_offset,webhook_source_manager=webhook_source_manager,+ reconcile_since=None if reconcile_since_offset is None else now - reconcile_since_offset,)result = response.items()assert isinstance(result, AsyncIterator)asyncio.run(_collect(result))status_fetches = [url for url in fetch_mock.call_args_list if "/statuses" in url.args[0]]- assert [url.args[0].split("/deployments/")[1].split("/")[0] for url in status_fetches] == expected_parents+ assert [url.args[0].split("/deployments/")[1].split("/")[0] for url in status_fetches] == ["1", "2"]def test_poll_mode_workflow_runs_still_polls() -> None: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.pyindex cf970ae33ad6..1a181041fe16 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@@ -441,7 +441,8 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:if delta_rebuild_pending:await logger.adebug("Ignoring the incremental cursor: a corrupt-delta revive rebuilds the table this run")- if reset_pipeline is not True and not delta_rebuild_pending:+ use_stored_cursors = reset_pipeline is not True and not delta_rebuild_pending+ if use_stored_cursors:processed_incremental_last_value = process_incremental_value(schema.sync_type_config.get("incremental_field_last_value"),schema.sync_type_config.get("incremental_field_type"),@@ -520,6 +521,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:else None,db_incremental_field_last_value_before_lookback=incremental_last_value_before_lookback,history_start=history_start,+ last_synced_at=schema.last_synced_at if use_stored_cursors else None,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.pyindex 560b33ec5cf7..27dcb2098263 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@@ -1,5 +1,6 @@import uuidimport contextlib+import dataclassesfrom datetime import datetimefrom typing import Any, cast@@ -686,6 +687,7 @@ async def test_incremental_lookback_shifts_query_value_not_stored_watermark(_, source_inputs = source.source_for_pipeline.call_args.argsassert source_inputs.db_incremental_field_last_value == expected_last_value+ assert source_inputs.last_synced_at == schema.last_synced_atassert 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@@ -693,6 +695,21 @@ async def test_incremental_lookback_shifts_query_value_not_stored_watermark(assert source_inputs.db_incremental_field_last_value_before_lookback == expected_before_lookback+async def test_reset_run_drops_last_synced_at_with_the_cursor():+ # A reset must re-walk the whole reconcile window, not only what changed since the last sync.+ source = mock.MagicMock(spec=SimpleSource)+ source.parse_config.return_value = {}+ source.source_for_pipeline.return_value = mock.MagicMock()+ schema = _incremental_schema(is_incremental=True, lookback_seconds=3600)+ with _patched_activity_reaching_run(source, schema):+ await import_data_activity_sync(dataclasses.replace(_inputs_no_reset(), reset_pipeline=True))++ _, source_inputs = source.source_for_pipeline.call_args.args+ assert source_inputs.db_incremental_field_last_value is None+ assert source_inputs.last_synced_at is None++@pytest.mark.asyncioasync def test_pending_delta_revive_extracts_full_table_not_incremental_slice():source = mock.MagicMock(spec=SimpleSource)