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(warehouse-sources): auto-recover safe numeric column widenings (#82459)

estefania6eff90b50e08
diff --git a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py
index 26bab033d4db..04fd67999c63 100644
--- a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py
+++ b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py
@@ -1,4 +1,7 @@
+import datetime as dt
+
from django.db.models import Q
+from django.utils import timezone
from posthog.dags.common.owners import JobOwners
from posthog.models.health_issue import HealthIssue
@@ -8,6 +11,32 @@ from posthog.temporal.health_checks.models import HealthCheckResult
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+# A schema carrying a fresh column_type_widened marker is scheduled to reset and re-sync itself on
+# the next scheduled run (see auto_widen_resync), so its failure is about to clear on its own and
+# alerting the user would be noise. A marker still present past this window means the recovery
+# keeps getting blocked (billing limits, paused schedule), which is worth alerting on after all.
+AUTO_WIDEN_MARKER_MUTE_WINDOW = dt.timedelta(hours=48)
+
+
+def _pending_auto_widen_resync(schema: ExternalDataSchema) -> bool:
+ marker = schema.column_type_widened
+ if marker is None:
+ return False
+ # Mute only the widening failure itself (same prefix the v3 consumer substring-matches): an
+ # unrelated failure landing while the marker is fresh still deserves an immediate alert.
+ if "Source column type changed" not in (schema.latest_error or ""):
+ return False
+ detected_at_raw = marker.get("detected_at")
+ if not isinstance(detected_at_raw, str):
+ return False
+ try:
+ detected_at = dt.datetime.fromisoformat(detected_at_raw)
+ except ValueError:
+ return False
+ if detected_at.tzinfo is None:
+ return False
+ return timezone.now() - detected_at < AUTO_WIDEN_MARKER_MUTE_WINDOW
+
class ExternalDataFailureCheck(HealthCheck):
name = "external_data_failure"
@@ -62,6 +91,8 @@ class ExternalDataFailureCheck(HealthCheck):
)
for schema in failed_schemas:
+ if _pending_auto_widen_resync(schema):
+ continue
error = schema.latest_error or ""
issues.setdefault(schema.team_id, []).append(
HealthCheckResult(
diff --git a/products/data_warehouse/backend/tests/test_external_data_failure_check.py b/products/data_warehouse/backend/tests/test_external_data_failure_check.py
new file mode 100644
index 000000000000..1476ed7e05cc
--- /dev/null
+++ b/products/data_warehouse/backend/tests/test_external_data_failure_check.py
@@ -0,0 +1,58 @@
+import uuid
+import datetime as dt
+
+from posthog.test.base import BaseTest
+
+from products.data_warehouse.backend.temporal.health_checks.external_data_failure import ExternalDataFailureCheck
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+
+class TestExternalDataFailureCheck(BaseTest):
+ def _create_failed_schema(
+ self, sync_type_config: dict | None = None, latest_error: str | None = None
+ ) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=self.team, source_type="Postgres"
+ )
+ return ExternalDataSchema.objects.create(
+ name="orders",
+ team=self.team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error=latest_error
+ or "Source column type changed: 'total_cost' has values that no longer fit its stored type",
+ sync_type_config=sync_type_config or {},
+ )
+
+ def _detected_schema_ids(self) -> set[str]:
+ issues = ExternalDataFailureCheck().detect([self.team.id])
+ return {result.payload["pipeline_id"] for result in issues.get(self.team.id, [])}
+
+ def test_failed_schema_is_reported(self) -> None:
+ schema = self._create_failed_schema()
+ assert self._detected_schema_ids() == {str(schema.id)}
+
+ def test_pending_auto_widen_resync_is_muted(self) -> None:
+ fresh = (dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)).isoformat()
+ self._create_failed_schema(
+ sync_type_config={"column_type_widened": {"column": "total_cost", "detected_at": fresh}}
+ )
+ assert self._detected_schema_ids() == set()
+
+ def test_unrelated_failure_with_fresh_marker_still_alarms(self) -> None:
+ fresh = (dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)).isoformat()
+ schema = self._create_failed_schema(
+ sync_type_config={"column_type_widened": {"column": "total_cost", "detected_at": fresh}},
+ latest_error="Couldn't connect to the source database",
+ )
+ assert self._detected_schema_ids() == {str(schema.id)}
+
+ def test_stale_auto_widen_marker_still_alarms(self) -> None:
+ # A marker older than the mute window means the automatic reset keeps getting blocked
+ # (billing limits, paused schedule), so the failure must surface after all.
+ stale = (dt.datetime.now(dt.UTC) - dt.timedelta(days=3)).isoformat()
+ schema = self._create_failed_schema(
+ sync_type_config={"column_type_widened": {"column": "total_cost", "detected_at": stale}}
+ )
+ assert self._detected_schema_ids() == {str(schema.id)}
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 8fb8942c5e97..3aa84224004e 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -723,6 +723,21 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config["delta_revive_required"] = info
self._save_sync_type_config()
+ @property
+ def column_type_widened(self) -> dict[str, Any] | None:
+ """Set by the v3 load consumer when a failed sync was classified as a safe numeric
+ column-type widening and `reset_pipeline` was stamped alongside it, so the next scheduled
+ sync resets and fully re-syncs the table (see `auto_widen_resync`). Read by the
+ external-data health check to mute a failure that is about to self-heal; consumed by
+ `update_sync_type_config_for_reset_pipeline` when any reset (automatic or manual) runs.
+ Shape: {"column": str, "stored_type": str, "incoming_type": str, "detected_at": iso8601 str}.
+ """
+ if self.sync_type_config:
+ marker = self.sync_type_config.get("column_type_widened", None)
+ if isinstance(marker, dict):
+ return marker
+ return None
+
@property
def coarsen_requested(self) -> dict[str, Any] | None:
"""Set by `stage_warehouse_coarsening` to nominate this table for the coarsening rewrite.
@@ -811,6 +826,10 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
def update_sync_type_config_for_reset_pipeline(self) -> None:
self.sync_type_config.pop("reset_pipeline", None)
+ # Any reset resolves a pending safe-widening marker; the re-created table adopts the new
+ # type. column_type_widened_last_reset_at is deliberately kept so the auto-resync cooldown
+ # survives the reset it timestamps.
+ self.sync_type_config.pop("column_type_widened", None)
self.sync_type_config.pop("incremental_field_last_value", None)
self.sync_type_config.pop("incremental_field_earliest_value", None)
self.sync_type_config.pop("incremental_staged", None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 20876617ffbb..cbe9eeb75dd8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -393,14 +393,17 @@ async def handle_reset_or_full_refresh(
# cleared; the incremental watermark and initial_sync_complete are kept since nothing
# was wiped.
await logger.adebug("Skipping table reset for webhook-only schema; resuming webhook ingestion")
+ # column_type_widened rides along with reset_pipeline (see auto_widen_resync); since this
+ # branch consumes the reset without wiping, drop the marker too so it can't linger forever.
await database_sync_to_async_pool(update_sync_type_config_keys)(
- schema.id, schema.team_id, removes=["reset_pipeline"]
+ schema.id, schema.team_id, removes=["reset_pipeline", "column_type_widened"]
)
- # Also drop it from the in-memory config: a later watermark save (update_incremental_field_values
+ # Also drop them from the in-memory config: a later watermark save (update_incremental_field_values
# / V3 staging) persists this same schema's sync_type_config, which would otherwise write
# reset_pipeline back and leave every subsequent run treated as a reset.
if schema.sync_type_config:
schema.sync_type_config.pop("reset_pipeline", None)
+ schema.sync_type_config.pop("column_type_widened", None)
elif reset_pipeline and not should_resume:
await logger.adebug("Deleting existing table due to reset_pipeline being set")
await delta_table_ref.reset_table()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index fa5ee5f8f0d6..2208d917db3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -95,9 +95,45 @@ class SchemaColumnTypeChangedException(Exception):
`integer` → `bigint`) after the Delta table was already created with the narrower type.
delta-rs cannot widen an existing column in place, so retrying is futile — the table must
be reset and fully re-synced to adopt the new type.
+
+ ``column_name`` / ``stored_type`` / ``incoming_type`` are populated only where a clean
+ stored-to-incoming type pair exists (the cast failure in ``evolve_pyarrow_schema``). The
+ value-driven raises (decimal overflow, nullability drift) leave them ``None``, which keeps
+ those cases out of automatic widening recovery by construction (see
+ ``auto_widen_resync.maybe_schedule_auto_widen_resync``).
"""
- pass
+ def __init__(
+ self,
+ message: str,
+ *,
+ column_name: str | None = None,
+ stored_type: pa.DataType | None = None,
+ incoming_type: pa.DataType | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.column_name = column_name
+ self.stored_type = stored_type
+ self.incoming_type = incoming_type
+
+
+def is_safe_numeric_widening(stored_type: pa.DataType, incoming_type: pa.DataType) -> bool:
+ """Whether a stored-to-incoming column type change is mechanically recoverable by a reset
+ and full re-sync, with no human judgement needed.
+
+ "Safe" means both sides are plain numeric types, so a re-sync deterministically adopts the
+ source's new type, which is the exact outcome the manual "Reset" remedy produces. That deliberately
+ includes transitions that aren't strict range widenings (int8 → uint8) and int64 → float64
+ (lossy above 2^53): the source already emits values of the new type either way, so an
+ automatic reset can never lose anything the manual reset would have kept. Transitions
+ involving non-numeric types (string, bool, decimal, temporal, nested) need human judgement
+ and stay manual.
+ """
+ return (
+ (pa.types.is_integer(stored_type) or pa.types.is_floating(stored_type))
+ and (pa.types.is_integer(incoming_type) or pa.types.is_floating(incoming_type))
+ and stored_type != incoming_type
+ )
def normalize_column_name(column_name: str) -> str:
@@ -341,7 +377,10 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Sche
raise SchemaColumnTypeChangedException(
f"Source column type changed: '{delta_field.name}' has values that no longer "
f"fit its stored type {delta_field.type} (incoming data is now "
- f"{incoming_column.type}). Reset and fully re-sync this table to adopt the new type."
+ f"{incoming_column.type}). Reset and fully re-sync this table to adopt the new type.",
+ column_name=delta_field.name,
+ stored_type=delta_field.type,
+ incoming_type=incoming_column.type,
) from e
incoming_table = incoming_table.set_column(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py
new file mode 100644
index 000000000000..ef9a1cd540bc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py
@@ -0,0 +1,236 @@
+"""Automatic reset-and-resync for safe numeric column-type widenings.
+
+delta-rs cannot widen a column in place, so the only remedy for a source column widened upstream is
+a reset and full re-sync. Without automation that failure is permanent until a human clicks "Reset":
+the v3 load consumer fails the run but never pauses the schema, so the same doomed sync repeats on
+every schedule. When the failed transition is a safe numeric widening (see
+``is_safe_numeric_widening``), ``maybe_schedule_auto_widen_resync`` stamps ``reset_pipeline`` on the
+schema so the next scheduled sync performs exactly the reset the manual button would, plus a
+``column_type_widened`` marker for observability, the reset cooldown, and health-check muting.
+
+The stamp must happen at failure time and the reset on the *next* run, never mid-run: the
+incremental watermark and the source's extraction query are resolved at the top of
+``import_data_sync`` before the pipeline runs, so wiping the table inside the failing run would
+rebuild it from only the rows past the old watermark.
+
+Gated per schema by the ``data-warehouse-auto-widen-resync`` flag (fail closed). Killing the flag
+stops new stamps; a reset already stamped still runs, since ``reset_pipeline`` is the same
+mechanism manual resets use and cannot be gated at consumption.
+"""
+
+import datetime as dt
+from typing import TYPE_CHECKING, Any
+
+import structlog
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.utils import get_machine_id
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ SchemaColumnTypeChangedException,
+ is_safe_numeric_widening,
+)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+logger = structlog.get_logger(__name__)
+
+WAREHOUSE_AUTO_WIDEN_RESYNC_FLAG = "data-warehouse-auto-widen-resync"
+
+# At most one automatic reset per schema per window; a second widening inside it falls back to the
+# manual reset flow. Guards against a source that flip-flops types re-reading its entire table on
+# every scheduled sync.
+AUTO_WIDEN_RESYNC_COOLDOWN = dt.timedelta(days=7)
+
+COLUMN_TYPE_WIDENED_KEY = "column_type_widened"
+# Kept separately from the marker (and never popped by the reset) so the cooldown survives the
+# reset that consumes the marker.
+COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY = "column_type_widened_last_reset_at"
+
+
+def is_auto_widen_resync_enabled(team_id: int, schema_id: str, source_type: str | None = None) -> bool:
+ """Evaluate the per-schema auto-widen-resync rollout flag.
+
+ ``schema_id`` / ``team_id`` / ``source_type`` are passed as person properties so the flag can be
+ released to a single table first (release condition ``schema_id = <id>``) before ramping by team /
+ org / source. Mirrors ``is_deltalite_write_enabled``. This flag is the only control (no env
+ switch), so recovery can be ramped or killed from the flag UI without a deploy. Any evaluation
+ failure returns False (fail closed): a flags-service blip must never accidentally switch it on.
+ """
+ from posthog.models import Team # noqa: PLC0415 to keep the Django model off this pipeline module's import path
+
+ try:
+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)
+ except Team.DoesNotExist:
+ return False
+
+ person_properties: dict[str, str] = {"schema_id": str(schema_id), "team_id": str(team_id)}
+ if source_type is not None:
+ person_properties["source_type"] = source_type
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_AUTO_WIDEN_RESYNC_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team_id)},
+ person_properties=person_properties,
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team_id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return False
+
+
+def maybe_schedule_auto_widen_resync(
+ schema: "ExternalDataSchema", job: "ExternalDataJob", error: SchemaColumnTypeChangedException
+) -> str | None:
+ """Schedule an automatic reset-and-resync for a safe numeric widening failure.
+
+ Returns the customer-facing message the failed run should surface instead of the manual-reset
+ instruction when the resync was scheduled, and None otherwise (unsafe transition, flag off,
+ cooldown active, CDC streaming or webhook schema, or any internal failure). Best-effort by contract: this
+ runs inside the load consumer's failure path, so it must never raise; the original error is
+ re-raised by the caller either way.
+ """
+ try:
+ return _schedule_auto_widen_resync(schema, job, error)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception(
+ "auto_widen_resync_scheduling_failed",
+ external_data_schema_id=str(schema.id),
+ team_id=schema.team_id,
+ )
+ return None
+
+
+def _schedule_auto_widen_resync(
+ schema: "ExternalDataSchema", job: "ExternalDataJob", error: SchemaColumnTypeChangedException
+) -> str | None:
+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 to keep the Django model off this pipeline module's import path
+ update_sync_type_config_keys,
+ )
+
+ column = error.column_name
+ stored_type = error.stored_type
+ incoming_type = error.incoming_type
+ if column is None or stored_type is None or incoming_type is None:
+ return None
+ if not is_safe_numeric_widening(stored_type, incoming_type):
+ return None
+ # A streaming-mode CDC schema has its per-schema schedule paused (CDCExtractionWorkflow owns
+ # it), so a stamped reset would never run; leave it to the manual repair flow.
+ if schema.is_cdc and schema.cdc_mode == "streaming":
+ return None
+ # A webhook-only resource consumes reset_pipeline without wiping the table (its rows can't be
+ # rebuilt from a poll; see handle_reset_or_full_refresh), so a stamp would promise a re-sync
+ # that never happens. Whether the resource is webhook-only isn't knowable here, so skip every
+ # webhook-mode schema conservatively.
+ if schema.is_webhook:
+ return None
+
+ source_type = schema.source.source_type if schema.source else None
+ if not is_auto_widen_resync_enabled(schema.team_id, str(schema.id), source_type=source_type):
+ return None
+
+ now = dt.datetime.now(dt.UTC)
+ stamped = False
+
+ def _stamp_if_out_of_cooldown(config: dict[str, Any]) -> None:
+ nonlocal stamped
+ if _within_cooldown(config, now):
+ return
+ config["reset_pipeline"] = True
+ config[COLUMN_TYPE_WIDENED_KEY] = {
+ "column": column,
+ "stored_type": str(stored_type),
+ "incoming_type": str(incoming_type),
+ "detected_at": now.isoformat(),
+ }
+ config[COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY] = now.isoformat()
+ stamped = True
+
+ # The cooldown check must read the freshest config, so it runs inside the row lock: two load
+ # consumers failing batches of the same schema concurrently would otherwise both pass a
+ # read-then-write check.
+ schema.sync_type_config = update_sync_type_config_keys(schema.id, schema.team_id, mutate=_stamp_if_out_of_cooldown)
+
+ outcome = "scheduled" if stamped else "cooldown_blocked"
+ _capture_auto_widen_resync(
+ schema,
+ job,
+ column=column,
+ stored_type=str(stored_type),
+ incoming_type=str(incoming_type),
+ outcome=outcome,
+ )
+ logger.info(
+ "auto_widen_resync_" + outcome,
+ external_data_schema_id=str(schema.id),
+ team_id=schema.team_id,
+ column=column,
+ stored_type=str(stored_type),
+ incoming_type=str(incoming_type),
+ )
+
+ if not stamped:
+ return None
+ # Keep the "Source column type changed" prefix: the consumer's non-retryable and
+ # expected-user-error classification substring-matches it.
+ return (
+ f"Source column type changed: '{column}' has values that no longer fit its stored type "
+ f"{stored_type} (incoming data is now {incoming_type}). This table will be reset and fully "
+ f"re-synced automatically at the next scheduled sync. No action is needed."
+ )
+
+
+def _within_cooldown(config: dict[str, Any], now: dt.datetime) -> bool:
+ last_reset_raw = config.get(COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY)
+ if not isinstance(last_reset_raw, str):
+ return False
+ try:
+ last_reset = dt.datetime.fromisoformat(last_reset_raw)
+ except ValueError:
+ return False
+ return now - last_reset < AUTO_WIDEN_RESYNC_COOLDOWN
+
+
+def _capture_auto_widen_resync(
+ schema: "ExternalDataSchema",
+ job: "ExternalDataJob",
+ *,
+ column: str,
+ stored_type: str,
+ incoming_type: str,
+ outcome: str,
+) -> None:
+ """Emit a `warehouse_auto_widen_resync` event so automatic recoveries are observable (how many
+ are scheduled vs blocked by the cooldown, and which transitions occur). Best-effort: it must
+ never block the failure path."""
+ try:
+ posthoganalytics.capture(
+ distinct_id=get_machine_id(),
+ event="warehouse_auto_widen_resync",
+ properties={
+ "team_id": schema.team_id,
+ "schema_id": str(schema.id),
+ "source_id": str(schema.source_id),
+ "resource_name": schema.name,
+ "job_id": str(job.id),
+ "column": column,
+ "stored_type": stored_type,
+ "incoming_type": incoming_type,
+ "outcome": outcome,
+ },
+ )
+ except Exception as e:
+ capture_exception(e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_auto_widen_resync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_auto_widen_resync.py
new file mode 100644
index 000000000000..8575f2da0af3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_auto_widen_resync.py
@@ -0,0 +1,152 @@
+import uuid
+import datetime as dt
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+import pyarrow as pa
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import auto_widen_resync
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ SchemaColumnTypeChangedException,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.auto_widen_resync import (
+ COLUMN_TYPE_WIDENED_KEY,
+ COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY,
+ maybe_schedule_auto_widen_resync,
+)
+
+_STORED_INT64 = pa.int64()
+_INCOMING_FLOAT64 = pa.float64()
+
+
+def _widening_error(
+ column_name: str | None = "total_cost",
+ stored_type: pa.DataType | None = _STORED_INT64,
+ incoming_type: pa.DataType | None = _INCOMING_FLOAT64,
+) -> SchemaColumnTypeChangedException:
+ return SchemaColumnTypeChangedException(
+ "Source column type changed: 'total_cost' has values that no longer fit its stored type int64 "
+ "(incoming data is now double). Reset and fully re-sync this table to adopt the new type.",
+ column_name=column_name,
+ stored_type=stored_type,
+ incoming_type=incoming_type,
+ )
+
+
+class TestMaybeScheduleAutoWidenResync(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=self.team, source_type="Postgres"
+ )
+ self.schema = ExternalDataSchema.objects.create(
+ name="orders", team=self.team, source=self.source, sync_type_config={}
+ )
+ self.job = ExternalDataJob.objects.create(
+ team=self.team, pipeline=self.source, schema=self.schema, status=ExternalDataJob.Status.RUNNING
+ )
+ capture_patcher = patch.object(auto_widen_resync.posthoganalytics, "capture")
+ self.capture_mock = capture_patcher.start()
+ self.addCleanup(capture_patcher.stop)
+
+ def _call(self, error: SchemaColumnTypeChangedException, flag_enabled: bool = True) -> str | None:
+ with patch.object(auto_widen_resync, "is_auto_widen_resync_enabled", return_value=flag_enabled):
+ return maybe_schedule_auto_widen_resync(self.schema, self.job, error)
+
+ def _persisted_config(self) -> dict[str, Any]:
+ self.schema.refresh_from_db()
+ return self.schema.sync_type_config or {}
+
+ def test_safe_widening_stamps_reset_and_marker(self) -> None:
+ message = self._call(_widening_error())
+
+ assert message is not None
+ assert message.startswith("Source column type changed")
+ assert "No action is needed" in message
+
+ config = self._persisted_config()
+ assert config["reset_pipeline"] is True
+ marker = config[COLUMN_TYPE_WIDENED_KEY]
+ assert marker["column"] == "total_cost"
+ assert marker["stored_type"] == "int64"
+ assert marker["incoming_type"] == "double"
+ assert dt.datetime.fromisoformat(marker["detected_at"]).tzinfo is not None
+ assert config[COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY] == marker["detected_at"]
+
+ def test_flag_off_leaves_schema_untouched(self) -> None:
+ assert self._call(_widening_error(), flag_enabled=False) is None
+ assert self._persisted_config() == {}
+
+ def test_unsafe_transitions_do_not_stamp(self) -> None:
+ for error in (
+ _widening_error(column_name=None, stored_type=None, incoming_type=None),
+ _widening_error(incoming_type=pa.string()),
+ _widening_error(stored_type=pa.decimal128(10, 2)),
+ ):
+ assert self._call(error) is None
+ assert self._persisted_config() == {}
+
+ def test_cooldown_blocks_second_stamp(self) -> None:
+ recent = (dt.datetime.now(dt.UTC) - dt.timedelta(days=1)).isoformat()
+ self.schema.sync_type_config = {COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY: recent}
+ self.schema.save()
+
+ assert self._call(_widening_error()) is None
+
+ config = self._persisted_config()
+ assert "reset_pipeline" not in config
+ assert COLUMN_TYPE_WIDENED_KEY not in config
+
+ def test_cooldown_expired_allows_stamp(self) -> None:
+ old = (dt.datetime.now(dt.UTC) - dt.timedelta(days=8)).isoformat()
+ self.schema.sync_type_config = {COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY: old}
+ self.schema.save()
+
+ assert self._call(_widening_error()) is not None
+
+ config = self._persisted_config()
+ assert config["reset_pipeline"] is True
+ assert config[COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY] != old
+
+ def test_cdc_streaming_schema_is_skipped(self) -> None:
+ self.schema.sync_type = ExternalDataSchema.SyncType.CDC
+ self.schema.sync_type_config = {"cdc_mode": "streaming"}
+ self.schema.save()
+
+ assert self._call(_widening_error()) is None
+ assert self._persisted_config() == {"cdc_mode": "streaming"}
+
+ def test_webhook_schema_is_skipped(self) -> None:
+ self.schema.sync_type = ExternalDataSchema.SyncType.WEBHOOK
+ self.schema.save()
+
+ assert self._call(_widening_error()) is None
+ assert self._persisted_config() == {}
+
+ def test_internal_failure_returns_none_instead_of_raising(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",
+ side_effect=RuntimeError("db down"),
+ ):
+ assert self._call(_widening_error()) is None
+
+ def test_reset_consumes_marker_and_keeps_cooldown(self) -> None:
+ stamped_at = dt.datetime.now(dt.UTC).isoformat()
+ self.schema.sync_type_config = {
+ "reset_pipeline": True,
+ COLUMN_TYPE_WIDENED_KEY: {"column": "total_cost", "detected_at": stamped_at},
+ COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY: stamped_at,
+ }
+ self.schema.save()
+
+ self.schema.update_sync_type_config_for_reset_pipeline()
+
+ config = self._persisted_config()
+ assert "reset_pipeline" not in config
+ assert COLUMN_TYPE_WIDENED_KEY not in config
+ assert config[COLUMN_TYPE_WIDENED_LAST_RESET_AT_KEY] == stamped_at
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 0f326aa5f0e6..80a68f1435c2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
apply_enabled_columns_projection,
conditional_lru_cache_async,
evolve_pyarrow_schema,
+ is_safe_numeric_widening,
merge_observed_columns_into_schema_metadata,
normalize_table_column_names,
observe_and_project_table,
@@ -784,9 +785,43 @@ def test_evolve_pyarrow_schema_integer_overflow_raises_actionable_error(
pa.schema([pa.field("id", pa.int64(), nullable=False), pa.field("val", delta_type, nullable=True)])
)
- with pytest.raises(SchemaColumnTypeChangedException, match="Source column type changed"):
+ with pytest.raises(SchemaColumnTypeChangedException, match="Source column type changed") as excinfo:
evolve_pyarrow_schema(arrow_table, delta_schema)
+ # The structured fields drive automatic widening recovery (auto_widen_resync); dropping them
+ # silently disables it.
+ assert excinfo.value.column_name == "val"
+ assert excinfo.value.stored_type == delta_type
+ assert excinfo.value.incoming_type == incoming_type
+
+
+ "stored_type, incoming_type, expected",
+ [
+ (pa.int32(), pa.int64(), True),
+ (pa.int16(), pa.int64(), True),
+ (pa.int64(), pa.float64(), True),
+ (pa.int8(), pa.uint8(), True),
+ (pa.uint8(), pa.int16(), True),
+ (pa.uint32(), pa.uint64(), True),
+ (pa.float32(), pa.float64(), True),
+ (pa.float64(), pa.int64(), True),
+ (pa.int64(), pa.int64(), False),
+ (pa.float64(), pa.float64(), False),
+ (pa.int64(), pa.string(), False),
+ (pa.float64(), pa.string(), False),
+ (pa.string(), pa.int64(), False),
+ (pa.int64(), pa.decimal128(10, 2), False),
+ (pa.decimal128(10, 2), pa.float64(), False),
+ (pa.bool_(), pa.int64(), False),
+ (pa.int64(), pa.bool_(), False),
+ (pa.timestamp("us"), pa.int64(), False),
+ (pa.int64(), pa.binary(), False),
+ ],
+)
+def test_is_safe_numeric_widening(stored_type: pa.DataType, incoming_type: pa.DataType, expected: bool):
+ assert is_safe_numeric_widening(stored_type, incoming_type) is expected
+
def test_evolve_pyarrow_schema_integer_narrowing_within_range_is_preserved():
"""A wider incoming integer column whose values still fit the stored narrower type is
@@ -914,9 +949,15 @@ def test_raise_on_nullability_drift_null_in_non_nullable_column_raises():
]
delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))
- with pytest.raises(SchemaColumnTypeChangedException, match="now contains nulls"):
+ with pytest.raises(SchemaColumnTypeChangedException, match="now contains nulls") as excinfo:
raise_on_nullability_drift(pa_table, delta_schema)
+ # Nullability drift must stay a manual reset: leaving the structured fields unset keeps it out
+ # of automatic widening recovery (auto_widen_resync) by construction.
+ assert excinfo.value.column_name is None
+ assert excinfo.value.stored_type is None
+ assert excinfo.value.incoming_type is None
+
@pytest.mark.parametrize(
"delta_fields, batch_columns",
@@ -1591,9 +1632,15 @@ def test_align_incoming_decimals_to_delta_raises_when_integer_overflows():
delta_fields: list[pa.Field] = [pa.field("id", pa.int64()), pa.field("amount", pa.decimal128(38, 32))]
delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))
- with pytest.raises(SchemaColumnTypeChangedException):
+ with pytest.raises(SchemaColumnTypeChangedException) as excinfo:
align_incoming_decimals_to_delta(arrow_table, delta_schema)
+ # Decimal overflow must stay a manual reset: leaving the structured fields unset keeps it out
+ # of automatic widening recovery (auto_widen_resync) by construction.
+ assert excinfo.value.column_name is None
+ assert excinfo.value.stored_type is None
+ assert excinfo.value.incoming_type is None
+
@pytest.mark.parametrize(
"mode,partition_count,partition_size,partition_format,expected",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 05ba4739ecc6..4d358a4defd1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -38,9 +38,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.l
supports_partial_data_loading,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ SchemaColumnTypeChangedException,
evolve_pyarrow_schema,
pyarrow_schema_from_arrow_exportable,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.auto_widen_resync import (
+ maybe_schedule_auto_widen_resync,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.scd2 import Scd2DeltaWriter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
@@ -817,7 +821,17 @@ def _process_message_reported(
)
if existing_delta_table is not None:
- pa_table = evolve_pyarrow_schema(pa_table, existing_delta_table.schema())
+ try:
+ pa_table = evolve_pyarrow_schema(pa_table, existing_delta_table.schema())
+ except SchemaColumnTypeChangedException as e:
+ # A safe numeric widening is mechanically recoverable: stamp reset_pipeline so the
+ # next scheduled sync resets and re-syncs the table, and reword the failure so
+ # latest_error stops telling the customer to reset manually. Unsafe transitions
+ # (and everything with the flag off) re-raise unchanged.
+ amended_message = maybe_schedule_auto_widen_resync(schema=schema, job=job, error=e)
+ if amended_message is not None:
+ e.args = (amended_message,)
+ raise
if verify_ownership is not None:
verify_ownership()