: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-modeling): stop labelling a forced rebuild a first run (#102911)
Thiago Salvatored91099e25d6a
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 1527e7ec6f99..267200cd24bd 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -4,6 +4,7 @@ import asyncioimport dataclassesfrom django.conf import settings+from django.db import transactionimport pyarrow as paimport deltalake@@ -928,6 +929,37 @@ async def _stage_person_property_batch(capture_exception(e)+FAILED_UPDATE_REASON_PREFIX = "incremental update failed: "+++def _failed_update_reason(error: Exception) -> str:+ """Why a rebuild is happening, short enough for ``DataModelingJob.full_refresh_reason``."""+ limit = DataModelingJob._meta.get_field("full_refresh_reason").max_length+ assert limit is not None+ return f"{FAILED_UPDATE_REASON_PREFIX}{error}"[:limit]+++@database_sync_to_async_pool+def _drop_watermark_and_say_why(saved_query: DataWarehouseSavedQuery, job: DataModelingJob, reason: str) -> None:+ """Clear the watermark and record the reason together, so a retry cannot find one without it."""+ with transaction.atomic():+ clear_incremental_state(saved_query)+ job.full_refresh_reason = reason+ job.save()+++def _reason_to_record(job: DataModelingJob, plan: WritePlan) -> str | None:+ """The reason this run rebuilt, keeping the one a failed attempt of the same job wrote."""+ if plan.incremental:+ return None++ recorded = job.full_refresh_reason+ if recorded is not None and recorded.startswith(FAILED_UPDATE_REASON_PREFIX):+ return recorded++ return plan.reason++async def _materialize_fully(objects: MatviewInputObjects,plan: WritePlan,@@ -1100,7 +1132,7 @@ async def _materialize_incrementally(# Every one of these means the table and the query have diverged in a way an upsert can't# reconcile. Dropping the watermark makes the retry rebuild instead of writing rows that# would be wrong, so the failure costs a full refresh rather than silent corruption.- await database_sync_to_async_pool(clear_incremental_state)(objects.saved_query)+ await _drop_watermark_and_say_why(objects.saved_query, objects.job, _failed_update_reason(err))if isinstance(err, SchemaDriftError):await logger.awarning(f"Rebuilding after schema drift: {err}")raise@@ -1204,7 +1236,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializobjects.job.run_mode = (DataModelingJob.RunMode.INCREMENTAL if plan.incremental else DataModelingJob.RunMode.FULL_REFRESH)- objects.job.full_refresh_reason = None if plan.incremental else plan.reason+ objects.job.full_refresh_reason = _reason_to_record(objects.job, plan)await database_sync_to_async_pool(objects.job.save)()person_property_sink = await _build_person_property_sink(diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.pyindex 11a67ac8e500..1546cbec77e7 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py@@ -23,7 +23,10 @@ import deltalakefrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_modeling.activities import MaterializeViewInputs, materialize_view_activityfrom posthog.temporal.data_modeling.activities.incremental_write import IncrementalWriteError-from posthog.temporal.data_modeling.activities.materialize_view import get_aws_storage_options+from posthog.temporal.data_modeling.activities.materialize_view import (+ FAILED_UPDATE_REASON_PREFIX,+ get_aws_storage_options,+)from products.data_modeling.backend.facade.api import get_incremental_state@@ -328,6 +331,40 @@ class TestIncrementalMaterialization:)assert stored == [(DAY1, 10, 1), (DAY2, 20, 200)]+ async def test_a_rebuild_after_a_failed_update_is_not_labelled_a_first_run(+ self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag+ ):+ await _configure(asaved_query)++ with _settings(bucket_name):+ await _run(activity_environment, ateam, anode, ajob, adag, _batch([DAY1], [10]))++ with pytest.raises(IncrementalWriteError):+ await _run(+ activity_environment,+ ateam,+ anode,+ ajob,+ adag,+ _batch([DAY2], [20], value_column="renamed"),+ value_column="renamed",+ )++ await _run(+ activity_environment,+ ateam,+ anode,+ ajob,+ adag,+ _batch([DAY2], [20], value_column="renamed"),+ value_column="renamed",+ )++ await database_sync_to_async(ajob.refresh_from_db)()+ assert ajob.run_mode == "full_refresh"+ assert ajob.full_refresh_reason is not None+ assert ajob.full_refresh_reason.startswith(FAILED_UPDATE_REASON_PREFIX)+async def test_a_definition_change_forces_a_rebuild(self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag):@@ -347,6 +384,9 @@ class TestIncrementalMaterialization:await database_sync_to_async(asaved_query.refresh_from_db)()assert get_incremental_state(asaved_query).last_run_mode == "full_refresh"+ await database_sync_to_async(ajob.refresh_from_db)()+ assert ajob.full_refresh_reason == "definition changed"+async def test_a_zero_row_window_leaves_the_table_and_watermark_alone(self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag):