: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): retry delta kernel read errors after a delay (#114684)
Jovan Sakovic3fa9f61b2dbc
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 5ba6b54d1cab..69b14dad29b0 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -1,6 +1,7 @@import uuidimport typingimport asyncio+import datetime as dtimport dataclassesfrom django.conf import settings@@ -13,6 +14,7 @@ import pyarrow.parquet as pqfrom structlog.contextvars import bind_contextvarsfrom structlog.types import FilteringBoundLoggerfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings, LimitContext@@ -193,6 +195,11 @@ def _reject_duplicate_output_columns(columns: list[_DescribedColumn]) -> None:CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000DELTA_TABLE_RETENTION_HOURS = 24+# An upstream Delta table's log can be mid-rewrite, so the default backoff exhausts every attempt+# before the rewrite lands.+DELTA_KERNEL_ERROR_MARKER = "DELTA_KERNEL_ERROR"+DELTA_KERNEL_ERROR_RETRY_DELAY = dt.timedelta(minutes=2)+# Above this many files, the per-run compaction is worth its full-table rewrite. Below it, skipping# keeps an incremental run's cost proportional to the rows it changed rather than the table's size.INCREMENTAL_COMPACT_FILE_THRESHOLD = 200@@ -1321,6 +1328,14 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ)published = Truereturn result+ except ClickHouseError as error:+ if not published:+ await cdp_sink.discard()+ if DELTA_KERNEL_ERROR_MARKER in str(error):+ raise ApplicationError(+ str(error), type=type(error).__name__, next_retry_delay=DELTA_KERNEL_ERROR_RETRY_DELAY+ ) from error+ raiseexcept (Exception, asyncio.CancelledError):if not published:await cdp_sink.discard()diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 48d746269105..dbd1023048b9 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -17,6 +17,7 @@ import httpximport pyarrow as paimport deltalakeimport pyarrow.parquet as pq+from temporalio.exceptions import ApplicationErrorfrom posthog.hogql.resolver import ResolverFactory@@ -1769,6 +1770,62 @@ class TestMaterializeViewActivity:with pytest.raises(RuntimeError, match="boom"):await activity_environment.run(materialize_view_activity, inputs)+ @pytest.mark.parametrize(+ "clickhouse_message,expects_delayed_retry",+ [+ (+ "Code: 742. DB::Exception: Received DeltaLake kernel error GenericError: Generic delta kernel "+ "error: No files in log segment (in snapshot). (DELTA_KERNEL_ERROR)",+ True,+ ),+ ("Code: 241. DB::Exception: Memory limit (total) exceeded. (MEMORY_LIMIT_EXCEEDED)", False),+ ],+ )+ async def test_delta_kernel_read_error_retries_after_a_delay(+ self,+ activity_environment,+ ateam,+ anode,+ ajob,+ bucket_name,+ adag,+ clickhouse_message,+ expects_delayed_retry,+ ):+ def mock_hogql_table(*args, **kwargs):+ raise ClickHouseError(clickhouse_message)++ with (+ override_settings(+ BUCKET_URL=f"s3://{bucket_name}",+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.hogql_table", mock_hogql_table+ ),+ ):+ inputs = MaterializeViewInputs(+ team_id=ateam.pk,+ dag_id=str(adag.id),+ node_id=str(anode.id),+ job_id=str(ajob.id),+ )+ with pytest.raises(Exception) as raised:+ await activity_environment.run(materialize_view_activity, inputs)++ error = raised.value+ assert clickhouse_message in str(error)+ if expects_delayed_retry:+ assert isinstance(error, ApplicationError)+ assert error.type == "ClickHouseError"+ assert not error.non_retryable+ assert error.next_retry_delay is not None+ assert error.next_retry_delay >= dt.timedelta(minutes=1)+ else:+ assert type(error) is ClickHouseError+class _EmptyArrowClient:describe_body = b"id\tInt64\n"