: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(data-warehouse): stop stripe syncs failing on mispersisted incremental fields (#71039)
Tom Owersfa068c43b00e
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 579308a7bed3..647705dbb074 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -2366,6 +2366,18 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"message": f"incremental_field_lookback_seconds must be an integer between 0 and 5184000 (60 days) for schema '{schema_name}'."},)+ # Canonicalize the incremental field against what the source declares for this+ # endpoint: discovery surfaces both a display `label` and the underlying `field`+ # (e.g. Stripe's label "created_at" -> field "created"), and API callers regularly+ # send the label — which then fails every sync with a missing-column error. Match on+ # either and persist the declared field + its real field_type.+ if incremental_field is not None and source_schema is not None:+ for declared in source_schema.incremental_fields:+ if incremental_field in (declared["field"], declared["label"]):+ incremental_field = declared["field"]+ incremental_field_type = str(declared["field_type"])+ break+sync_type_config = {"incremental_field": incremental_field,"incremental_field_type": incremental_field_type,diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex 3a942b2dd286..510d21253414 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -178,6 +178,39 @@ class TestExternalDataSource(APIBaseTest):len(STRIPE_ENDPOINTS),)+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_create_canonicalizes_incremental_field_label_to_declared_field(self, _mock_validate):+ # Discovery surfaces Stripe's incremental field as label "created_at" / field "created";+ # callers regularly send the label, which used to be persisted verbatim and then fail+ # every sync with a missing-column error at cursor extraction.+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Stripe",+ "created_via": "web",+ "payload": {+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},+ "schemas": [+ {+ "name": STRIPE_CUSTOMER_RESOURCE_NAME,+ "should_sync": True,+ "sync_type": "append",+ "incremental_field": "created_at",+ "incremental_field_type": "datetime",+ },+ ],+ },+ },+ )++ self.assertEqual(response.status_code, 201)+ schema = ExternalDataSchema.objects.get(source_id=response.json()["id"], name=STRIPE_CUSTOMER_RESOURCE_NAME)+ self.assertEqual(schema.sync_type_config["incremental_field"], "created")+ self.assertEqual(schema.sync_type_config["incremental_field_type"], "integer")+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",return_value=(True, None),diff --git a/products/warehouse_sources/backend/migrations/0070_fix_stripe_incremental_fields.py b/products/warehouse_sources/backend/migrations/0070_fix_stripe_incremental_fields.pynew file mode 100644index 000000000000..dd1d036ac3c4--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0070_fix_stripe_incremental_fields.py@@ -0,0 +1,48 @@+from django.db import migrations++# Stripe schemas ended up with broken `sync_type_config.incremental_field` values two ways:+# - API callers persisted the discovery display label "created_at" instead of the real field+# "created" (every Stripe resource except InvoiceItem declares label=created_at, field=created),+# - migration 0794 blanket-set "created" on all Stripe append schemas, including InvoiceItem whose+# only incremental field is "date".+# Both make every sync fail with a missing-column error at cursor extraction. Rewrite the config to+# the field the source actually declares; drop a stashed cursor value that can't serve as an epoch+# cursor under the corrected integer type so the next sync starts a clean pass.++INVOICE_ITEM_RESOURCE_NAME = "InvoiceItem"+++def _fix(schema, field: str) -> None:+ schema.sync_type_config["incremental_field"] = field+ schema.sync_type_config["incremental_field_type"] = "integer"+ last_value = schema.sync_type_config.get("incremental_field_last_value")+ if last_value is not None and not isinstance(last_value, int | float):+ schema.sync_type_config["incremental_field_last_value"] = None+ schema.save(update_fields=["sync_type_config"])+++def forwards(apps, schema_editor):+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ # One row per configured Stripe table (thousands, not events-scale) — a per-row loop is fine.+ schemas = ExternalDataSchema.objects.filter(+ source__source_type="Stripe",+ deleted=False,+ sync_type_config__incremental_field__in=["created_at", "created"],+ ).iterator()++ for schema in schemas:+ incremental_field = schema.sync_type_config.get("incremental_field")+ if schema.name == INVOICE_ITEM_RESOURCE_NAME:+ _fix(schema, "date")+ elif incremental_field == "created_at":+ _fix(schema, "created")+ # `created` on any other resource is the declared field — leave it alone.+++class Migration(migrations.Migration):+ dependencies = [("warehouse_sources", "0069_alter_externaldatasource_created_via")]++ operations = [+ migrations.RunPython(forwards, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex f033efc583de..59c4e606ad61 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0069_alter_externaldatasource_created_via+0070_fix_stripe_incremental_fieldsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 79a739d6cb94..be865e3a2e60 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@@ -116,6 +116,13 @@ Any_Source_Errors: dict[str, str | None] = {# misconfigured or wrong host/URL on the customer's side. Match the stable alert name, not the# volatile `_ssl.c:NNNN` suffix or per-request host."SSLV3_ALERT_HANDSHAKE_FAILURE": "Could not complete a secure (TLS) connection to the source's server — the handshake was rejected. Please check the configured host/URL is correct and that the server supports a compatible TLS version.",+ # Raised by `get_incremental_field_value` when the configured incremental field isn't a column+ # in the extracted rows (e.g. a display label persisted instead of the real field name). The+ # config is wrong, so every retry replays the same failure — pause and tell the user to fix it.+ "was not found in the data returned by the source": (+ "The incremental field configured for this table doesn't exist in the data the source returns. "+ "Edit the table's sync method, pick a valid incremental field, then re-enable the sync."+ ),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex f87ac6754531..a816b1edd8c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py@@ -45,6 +45,23 @@ async def update_job_row_count(job_id: str, count: int, logger: FilteringBoundLo)()+class IncrementalFieldMissingFromDataError(Exception):+ """The configured incremental field isn't a column in the extracted rows.++ A config error (e.g. a display label like "created_at" persisted instead of the real field+ "created", or a field the endpoint simply doesn't return) — retrying can never fix it, so the+ message is registered in ``Any_Source_Errors`` to pause the schema with user guidance instead+ of failing every scheduled sync with a raw pyarrow KeyError.+ """++ def __init__(self, field_name: str, table: pa.Table) -> None:+ super().__init__(+ f'Incremental field "{field_name}" was not found in the data returned by the source. '+ f"Edit the table's sync method and pick a valid incremental field. "+ f"Available columns: {', '.join(sorted(table.column_names)[:50])}"+ )++def get_incremental_field_value(schema: ExternalDataSchema | None, table: pa.Table, aggregate: Literal["max"] | Literal["min"] = "max") -> Any:@@ -55,7 +72,11 @@ def get_incremental_field_value(if incremental_field_name is None:return None- column = table[normalize_column_name(incremental_field_name)]+ normalized_field_name = normalize_column_name(incremental_field_name)+ if normalized_field_name not in table.column_names:+ raise IncrementalFieldMissingFromDataError(incremental_field_name, table)++ column = table[normalized_field_name]processed_column = pa.array([process_incremental_value(val, schema.incremental_field_type) for val in column.to_pylist()])diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.pyindex d175c0e7e7e5..546bb54b5f01 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py@@ -3,10 +3,16 @@ import uuidimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+import pyarrow as pafrom parameterized import parameterizedfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import run_post_load_operations+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (+ IncrementalFieldMissingFromDataError,+ get_incremental_field_value,+ run_post_load_operations,+)_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load"_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"@@ -183,3 +189,31 @@ class TestRunPostLoadDeltaMaintenance:mock_capture.assert_called_once()prepare_s3.assert_awaited_once()+++class TestGetIncrementalFieldValue:+ def _schema(self, incremental_field: str) -> MagicMock:+ schema = MagicMock()+ schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL+ schema.sync_type_config = {"incremental_field": incremental_field, "incremental_field_type": "integer"}+ schema.incremental_field_type = "integer"+ return schema++ def test_returns_max_of_configured_column(self):+ table = pa.table({"id": ["a", "b"], "created": [10, 20]})+ assert get_incremental_field_value(self._schema("created"), table) == 20++ def test_missing_column_raises_actionable_error_matched_by_non_retryable_map(self):+ # A label like "created_at" persisted instead of the real field must fail with guidance+ # (not a raw pyarrow KeyError), and the message must keep matching the Any_Source_Errors+ # substring so the schema is paused instead of retrying the same failure forever.+ table = pa.table({"id": ["a"], "created": [10]})++ with pytest.raises(IncrementalFieldMissingFromDataError) as exc_info:+ get_incremental_field_value(self._schema("created_at"), table)++ message = str(exc_info.value)+ assert '"created_at"' in message+ assert "created" in message # available columns are listed for self-service fixing+ matching_keys = [key for key in Any_Source_Errors if key in message]+ assert matching_keys, "exception message must stay matched by an Any_Source_Errors entry"