: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-sources): stop retrying a gladly report that was never served (#105444)
posthog[bot]f840fa3b1249
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 256a424fe2c0..33fe86d92042 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@@ -142,6 +142,8 @@ class SourceInputs: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] = None+ # Sync history survives cursor resets and table deletion.+ schema_has_ever_synced: bool = Falseenabled_columns: Optional[list[str]] = Nonerow_filters: Optional[list[ValidatedRowFilter]] = None# The schema's stored primary key and the key a full probe last proved unique. A source thatdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.pyindex 7edad3f9f3eb..c517dbb7d38b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py@@ -63,6 +63,16 @@ class GladlyReportUnavailableError(Exception):f"Gladly returned no report for metricSet={metric_set}: the response body is not a CSV report. "f"First line: {header!r:.300}")+ self.header = header+++class GladlyReportNotAvailableForAccountError(Exception):+ def __init__(self, metric_set: str, header: list[str]) -> None:+ super().__init__(+ f"Gladly report unavailable for this account: metricSet={metric_set} returned an error body "+ f"instead of a CSV on every attempt, and this table has never completed a sync. "+ f"First line: {header!r:.300}"+ )def _header_is_an_error_line(fieldnames: Sequence[str]) -> bool:@@ -278,6 +288,7 @@ def get_rows(should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,domain: str = DEFAULT_DOMAIN,+ schema_has_ever_synced: bool = False,) -> Iterator[list[dict[str, Any]]]:config = GLADLY_ENDPOINTS[endpoint]session = _get_session(agent_email, api_token)@@ -293,6 +304,7 @@ def get_rows(resumable_source_manager=resumable_source_manager,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,+ schema_has_ever_synced=schema_has_ever_synced,)return@@ -386,6 +398,7 @@ def _report_rows(resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,+ schema_has_ever_synced: bool = False,) -> Iterator[list[dict[str, Any]]]:@retry(retry=retry_if_exception_type((GladlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),@@ -459,25 +472,35 @@ def _report_rows(raise GladlyReportHeaderError(metric_set, missing, present)return reader+ report_never_served = not schema_has_ever_synced and (+ resume_config is None or resume_config.last_report_window_end is None+ )+is_first_request = Truewhile window_start <= today:window_end = min(window_start + timedelta(days=config.report_window_days - 1), today)if not is_first_request:time.sleep(REPORT_REQUEST_INTERVAL_SECONDS)is_first_request = False- reader = open_report(- {- "metricSet": metric_set,- # Explicit UTC keeps window boundaries and rendered timestamps- # stable even if the organization's default timezone changes.- "timezone": "UTC",- # endAt is inclusive: the report covers through the end of that day.- "startAt": window_start.isoformat(),- "endAt": window_end.isoformat(),- },- window_start,- window_end,- )+ try:+ reader = open_report(+ {+ "metricSet": metric_set,+ # Explicit UTC keeps window boundaries and rendered timestamps+ # stable even if the organization's default timezone changes.+ "timezone": "UTC",+ # endAt is inclusive: the report covers through the end of that day.+ "startAt": window_start.isoformat(),+ "endAt": window_end.isoformat(),+ },+ window_start,+ window_end,+ )+ except GladlyReportUnavailableError as e:+ if report_never_served:+ raise GladlyReportNotAvailableForAccountError(metric_set, e.header) from e+ raise+ report_never_served = Falsecolumns = {name: _normalize_report_column(name) for name in reader.fieldnames or []}row_count = 0@@ -522,6 +545,7 @@ def gladly_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,domain: str = DEFAULT_DOMAIN,+ schema_has_ever_synced: bool = False,) -> SourceResponse:config = GLADLY_ENDPOINTS[endpoint]@@ -537,6 +561,7 @@ def gladly_source(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,domain=domain,+ schema_has_ever_synced=schema_has_ever_synced,),primary_keys=[config.primary_key],partition_count=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.pyindex 8a18c2252d18..5b0bc347ebdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py@@ -75,6 +75,12 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):"account. Ask Gladly support to check the report is available for your account. If ""Gladly confirms it is, contact PostHog support."),+ "Gladly report unavailable for this account": (+ "Gladly returned an error every time PostHog asked for the report this table syncs "+ "from, and the table has never synced. Ask Gladly support to make the report "+ "available for your account, then re-enable this table. If Gladly confirms it is "+ "available, contact PostHog support."+ ),}def get_retryable_errors(self) -> set[str]:@@ -210,4 +216,5 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myorif inputs.should_use_incremental_fieldelse None,domain=config.domain,+ schema_has_ever_synced=inputs.schema_has_ever_synced,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.pyindex 95f451b096da..ece2d82c6f95 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -13,6 +13,7 @@ import requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (CHUNK_SIZE,GladlyReportHeaderError,+ GladlyReportNotAvailableForAccountError,GladlyReportUnavailableError,GladlyResumeConfig,GladlyRetryableError,@@ -719,6 +720,51 @@ class TestGetReportRows:assert mock_session.return_value.post.call_count == 5manager.save_state.assert_not_called()+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)+ @pytest.mark.parametrize(+ "schema_has_ever_synced, expected_error",+ [+ (False, GladlyReportNotAvailableForAccountError),+ (True, GladlyReportUnavailableError),+ ],+ ids=["never_served", "reset_run_after_a_successful_sync"],+ )+ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_an_error_body_stops_the_sync_only_when_gladly_never_served_the_report(+ self, mock_session, _sleep, schema_has_ever_synced, expected_error+ ):+ mock_session.return_value.post.side_effect = [_csv_response("Unexpected error occurred") for _ in range(5)]++ manager = _make_manager()+ with pytest.raises(expected_error):+ list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "contact_timestamps",+ mock.MagicMock(),+ manager,+ schema_has_ever_synced=schema_has_ever_synced,+ )+ )++ manager.save_state.assert_not_called()++ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)+ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_an_error_body_after_a_window_landed_stays_retryable(self, mock_session, _sleep):+ mock_session.return_value.post.side_effect = [+ _csv_response("Timestamp,Contact ID\n2024-03-14T09:00:00.000Z,ct-1\n"),+ *[_csv_response("Unexpected error occurred") for _ in range(5)],+ ]++ manager = _make_manager()+ with pytest.raises(GladlyReportUnavailableError, match="Gladly returned no report"):+ list(get_rows("myorg", "[email protected]", "token", "contact_timestamps", mock.MagicMock(), manager))+@time_machine.travel("2024-03-15T10:00:00Z", tick=False)@mock.patch("time.sleep")@mock.patch(f"{_MODULE}.make_tracked_session")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.pyindex 667d59967d23..35d2dbe778ff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py@@ -122,3 +122,16 @@ class TestGladlySource:assert "Gladly returned no report" in retryableassert set(exhausted) <= retryableassert not any("Gladly returned no report" in key for key in self.source.get_non_retryable_errors())++ def test_a_report_gladly_never_served_stops_the_sync_instead_of_retrying(self):+ observed_error = (+ "Gladly report unavailable for this account: metricSet=ContactTimestampsReport returned "+ "an error body instead of a CSV on every attempt, and this table has never completed a "+ "sync. First line: ['Unexpected error occurred']"+ )+ message = self.source.get_non_retryable_errors()["Gladly report unavailable for this account"]++ assert any(key in observed_error for key in self.source.get_non_retryable_errors())+ assert not any(key in observed_error for key in self.source.get_retryable_errors())+ assert message is not None+ assert "gladly support" in message.lower()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 46f04345f6ef..1453442e8a6d 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@@ -149,6 +149,13 @@ def _get_external_data_schema(schema_id: uuid.UUID, team_id: int) -> ExternalDat)+@database_sync_to_async_pool+def _has_completed_schema_job(schema_id: uuid.UUID, team_id: int) -> bool:+ return ExternalDataJob.objects.filter(+ schema_id=schema_id, team_id=team_id, status=ExternalDataJob.Status.COMPLETED+ ).exists()++# An allow-list, not a deny-list: every sync type here leaves one row per key, and the reader# streams the table with no dedupe state. Append keeps a row per sync and CDC keeps change# history, so either would fan the child out once per duplicate. Webhook qualifies because its@@ -526,6 +533,8 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger: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,+ schema_has_ever_synced=schema.last_synced_at is not None+ or await _has_completed_schema_job(inputs.schema_id, inputs.team_id),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 b411a6e7b14e..77b9e7499c49 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@@ -153,6 +153,32 @@ class TestGetModelsPrefetchesSource(BaseTest):models.job.folder_path()+class TestSchemaSyncHistory(BaseTest):+ @parameterized.expand(+ [+ (ExternalDataJob.Status.COMPLETED, True, True, True),+ (ExternalDataJob.Status.FAILED, True, True, False),+ (ExternalDataJob.Status.RUNNING, True, True, False),+ (ExternalDataJob.Status.COMPLETED, False, True, False),+ (ExternalDataJob.Status.COMPLETED, True, False, False),+ ]+ )+ def test_only_a_completed_job_for_this_team_and_schema_counts(+ self, status: str, same_schema: bool, same_team: bool, expected: bool+ ) -> None:+ source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=self.team, source_type="Gladly"+ )+ schema = ExternalDataSchema.objects.create(name="contact_timestamps", team=self.team, source=source)+ ExternalDataJob.objects.create(team=self.team, pipeline=source, schema=schema, status=status)++ has_completed_job = cast(Any, module._has_completed_schema_job).func(+ schema.id if same_schema else uuid.uuid4(), self.team.pk if same_team else self.team.pk + 1+ )++ assert has_completed_job is expected++@pytest.mark.asyncioasync def test_non_retryable_setup_error_routes_through_handler():# A MongoDB mongodb+srv:// URI resolves DNS in the MongoClient constructor, so a deleted@@ -918,18 +944,32 @@ async def test_incremental_lookback_shifts_query_value_not_stored_watermark(@pytest.mark.asyncio-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.+ "last_synced_at,has_completed_job,expected_has_ever_synced",+ [+ pytest.param(None, False, False, id="never_synced"),+ pytest.param(None, True, True, id="deleted_table"),+ pytest.param(datetime(2026, 6, 14), False, True, id="successful_sync"),+ ],+)+async def test_reset_run_drops_cursors_but_preserves_sync_history(+ last_synced_at: datetime | None, has_completed_job: bool, expected_has_ever_synced: bool+) -> None: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):+ schema.last_synced_at = last_synced_at+ with (+ _patched_activity_reaching_run(source, schema),+ mock.patch.object(module, "_has_completed_schema_job", new=mock.AsyncMock(return_value=has_completed_job)),+ ):await import_data_activity_sync(dataclasses.replace(_inputs_no_reset(), reset_pipeline=True))_, source_inputs = source.source_for_pipeline.call_args.argsassert source_inputs.db_incremental_field_last_value is Noneassert source_inputs.last_synced_at is None+ assert source_inputs.schema_has_ever_synced is expected_has_ever_synced@pytest.mark.asyncio@@ -938,6 +978,7 @@ async def test_pending_delta_revive_extracts_full_table_not_incremental_slice():source.parse_config.return_value = {}source.source_for_pipeline.return_value = mock.MagicMock()schema = _incremental_schema(is_incremental=True, lookback_seconds=3600)+ schema.last_synced_at = datetime(2026, 6, 14)schema.incremental_field_earliest_value = "2026-01-01T00:00:00"# The model reads this marker out of the persisted config through a property. Set both, because# the mock cannot run the property, and the config carries the shape a real revive leaves behind.@@ -957,6 +998,8 @@ async def test_pending_delta_revive_extracts_full_table_not_incremental_slice():# replaces the whole table with the rows after the watermark.assert source_inputs.db_incremental_field_last_value is Noneassert source_inputs.db_incremental_field_earliest_value is None+ assert source_inputs.last_synced_at is None+ assert source_inputs.schema_has_ever_synced is True# The stored watermark stays put, so a completed rebuild advances it from the rows it read.assert schema.sync_type_config["incremental_field_last_value"] == "2026-06-14T15:33:31.802833"