: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 suspending models on our own failures (#80526)
Jovan Sakovicec1c7dea4fc0
diff --git a/posthog/temporal/data_modeling/activities/get_dag_structure.py b/posthog/temporal/data_modeling/activities/get_dag_structure.pyindex ccf7902c37b0..289243df46dd 100644--- a/posthog/temporal/data_modeling/activities/get_dag_structure.py+++ b/posthog/temporal/data_modeling/activities/get_dag_structure.py@@ -2,35 +2,15 @@ import dataclassesfrom temporalio import activity-from posthog.models import Team-from posthog.ph_client import feature_enabled_or_falsefrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_loggerfrom products.data_modeling.backend.facade.models import DataModelingJobEngine, Edge, Node, NodeType-from .utils import is_node_suspended+from .utils import is_node_suspended, is_suspension_enforcedLOGGER = get_logger(__name__)-SUSPENSION_ENFORCEMENT_FLAG = "data-modeling-suspend-failing-nodes"---def _is_suspension_enforced(team_id: int) -> bool:- try:- team = Team.objects.only("organization_id").get(id=team_id)- return feature_enabled_or_false(- SUSPENSION_ENFORCEMENT_FLAG,- str(team_id),- groups={"organization": str(team.organization_id), "project": str(team_id)},- group_properties={"organization": {"id": str(team.organization_id)}, "project": {"id": str(team_id)}},- only_evaluate_locally=True,- send_feature_flag_events=False,- )- except Exception:- LOGGER.warning("Failed to evaluate suspension enforcement flag; treating as disabled", team_id=team_id)- return False-@dataclasses.dataclassclass GetDAGStructureInputs:@@ -75,7 +55,7 @@ def _get_dag_structure_async(team_id: int, dag_id: str) -> DAG:.filter(team_id=team_id, dag_id=dag_id).exclude(source__type=NodeType.TABLE))- if _is_suspension_enforced(team_id):+ if is_suspension_enforced(team_id):suspended_nodes = {engine.value: [str(n.id) for n in executable_nodes if is_node_suspended(n, engine)]for engine in DataModelingJobEnginediff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.pyindex 77d65c1476c6..f95f914f9184 100644--- a/posthog/temporal/data_modeling/activities/utils.py+++ b/posthog/temporal/data_modeling/activities/utils.py@@ -6,7 +6,11 @@ from django.db import transactionfrom structlog.contextvars import bind_contextvars+from posthog.models import Team+from posthog.ph_client import feature_enabled_or_falsefrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.logger import get_logger+from posthog.temporal.data_modeling.activities.preempt_dag_run import ABANDONED_ERRORfrom products.data_modeling.backend.facade.api import (clear_node_suspension,@@ -30,16 +34,54 @@ __all__ = ["bind_data_modeling_log_context","clear_node_suspension","clear_node_suspension_for_engine",+ "is_externally_aborted","is_node_suspended",+ "is_suspension_enforced","mark_node_suspended","maybe_suspend_node_for_engine","strip_hostname_from_error","update_node_system_properties",]+LOGGER = get_logger(__name__)+# Consecutive failed jobs (per engine) before a node is suspended from future DAG runs.CONSECUTIVE_FAILURES_TO_SUSPEND = 5+SUSPENSION_ENFORCEMENT_FLAG = "data-modeling-suspend-failing-nodes"++# The test before adding a marker is "was the query denied the chance to fail on its own merits",+# NOT "was this our fault" - a query that exhausts memory is one we do want suspended.+EXTERNALLY_ABORTED_MARKERS = (+ "Code: 202", # TOO_MANY_SIMULTANEOUS_QUERIES+ "Cannot connect to host",+ "Connection refused",+ # the trailing colon is load-bearing: it keeps a customer column of the same name out of the match+ "QueueEmpty: ", # no root node to start from, so the graph was refused rather than the query+ "Preempted: ",+ ABANDONED_ERROR,+)+++def is_suspension_enforced(team_id: int) -> bool:+ try:+ team = Team.objects.only("organization_id").get(id=team_id)+ return feature_enabled_or_false(+ SUSPENSION_ENFORCEMENT_FLAG,+ str(team_id),+ groups={"organization": str(team.organization_id), "project": str(team_id)},+ group_properties={"organization": {"id": str(team.organization_id)}, "project": {"id": str(team_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ except Exception:+ LOGGER.warning("Failed to evaluate suspension enforcement flag; treating as disabled", team_id=team_id)+ return False+++def is_externally_aborted(error: str) -> bool:+ return any(marker in error for marker in EXTERNALLY_ABORTED_MARKERS)+def bind_data_modeling_log_context(team_id: int, saved_query_id: UUID | str) -> None:"""Route this activity's log lines to `log_entries` under the saved query's id.@@ -111,10 +153,10 @@ def _count_leading_failures(saved_query_id: UUID, engine: str, *, since: str | N# Otherwise the failures that caused the suspension are still the most recent jobs, and one# new failure re-suspends the node we just resumed.jobs = jobs.filter(created_at__gt=dt.datetime.fromisoformat(since))- statuses = jobs.order_by("-created_at").values_list("status", flat=True)[:CONSECUTIVE_FAILURES_TO_SUSPEND]+ rows = jobs.order_by("-created_at").values_list("status", "error")[:CONSECUTIVE_FAILURES_TO_SUSPEND]count = 0- for status in statuses:- if status != DataModelingJobStatus.FAILED:+ for status, error in rows:+ if status != DataModelingJobStatus.FAILED or is_externally_aborted(error or ""):breakcount += 1return count@@ -144,7 +186,9 @@ def maybe_suspend_node_for_engine()mark_node_suspended(node, engine=engine, reason=reason, job_id=job_id, fingerprint=fingerprint)node.save()- if str(engine) == DataModelingJobEngine.CLICKHOUSE.value:+ # Without enforcement the node keeps materializing every tick, so telling the customer it stopped+ # would be false.+ if str(engine) == DataModelingJobEngine.CLICKHOUSE.value and is_suspension_enforced(team_id):job = DataModelingJob.objects.get(id=job_id)job.error = (f"This model has been suspended after {CONSECUTIVE_FAILURES_TO_SUSPEND} consecutive failed "diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.pyindex 2ac626d01b86..eebd36fcff3b 100644--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py@@ -178,7 +178,7 @@ class TestGetDagStructureActivity:await database_sync_to_async(suspended_node.save)()inputs = GetDAGStructureInputs(team_id=ateam.pk, dag_id=str(adag.id))- with unittest.mock.patch.object(gds, "_is_suspension_enforced", return_value=enforced):+ with unittest.mock.patch.object(gds, "is_suspension_enforced", return_value=enforced):dag = await activity_environment.run(get_dag_structure_activity, inputs)assert dag.suspended_nodes["clickhouse"] == ([str(suspended_node.id)] if enforced else [])diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 65e207f893f9..f3a6e8787ce9 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -462,7 +462,8 @@ class TestShouldPauseScheduleForTimeout:class TestNodeSuspension:- async def test_suspends_for_engine_after_consecutive_failures(self, ateam, anode, asaved_query, adag):+ @pytest.mark.parametrize("enforced", [True, False])+ async def test_suspends_for_engine_after_consecutive_failures(self, ateam, anode, asaved_query, adag, enforced):from posthog.temporal.data_modeling.activities.utils import (CONSECUTIVE_FAILURES_TO_SUSPEND,is_node_suspended,@@ -476,22 +477,167 @@ class TestNodeSuspension:job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")jobs.append(job)+ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.utils.is_suspension_enforced", return_value=enforced+ ):+ suspended = await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason="boom",+ job_id=str(job.id),+ )++ assert suspended is True+ await database_sync_to_async(anode.refresh_from_db)()+ assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is True+ assert is_node_suspended(anode, DataModelingJobEngine.DUCKGRES) is False+ await database_sync_to_async(job.refresh_from_db)()+ assert ("has been suspended" in job.error) is enforced++ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.+ for j in jobs:+ await database_sync_to_async(j.delete)()++ @pytest.mark.parametrize(+ "aborted_error",+ [+ "Code: 202. DB::Exception: Too many simultaneous queries",+ "Cannot connect to host ch-offline.example.com:8443",+ "Abandoned: the materialization workflow is no longer running",+ "QueueEmpty: Application error",+ "Preempted: a new DAG run started before this job completed",+ ],+ )+ async def test_externally_aborted_failures_do_not_suspend(self, ateam, anode, asaved_query, adag, aborted_error):+ from posthog.temporal.data_modeling.activities.utils import (+ CONSECUTIVE_FAILURES_TO_SUSPEND,+ is_node_suspended,+ maybe_suspend_node_for_engine,+ )++ jobs = [+ await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error=aborted_error)+ for _ in range(CONSECUTIVE_FAILURES_TO_SUSPEND)+ ]+suspended = await maybe_suspend_node_for_engine(node_id=str(anode.id),team_id=ateam.pk,dag_id=str(adag.id),saved_query_id=asaved_query.id,engine=DataModelingJobEngine.CLICKHOUSE,- reason="boom",- job_id=str(job.id),+ reason=aborted_error,+ job_id=str(jobs[-1].id),+ )++ assert suspended is False+ await database_sync_to_async(anode.refresh_from_db)()+ assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is False++ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.+ for job in jobs:+ await database_sync_to_async(job.delete)()++ @pytest.mark.parametrize("identifier", ["Preempted", "QueueEmpty"])+ async def test_suspends_when_a_customer_identifier_spells_an_abort_marker(+ self, ateam, anode, asaved_query, adag, identifier+ ):+ from posthog.temporal.data_modeling.activities.utils import (+ CONSECUTIVE_FAILURES_TO_SUSPEND,+ is_node_suspended,+ maybe_suspend_node_for_engine,+ )++ error = f"Code: 47. DB::Exception: Missing columns: '{identifier}' while processing query"+ jobs = [+ await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error=error)+ for _ in range(CONSECUTIVE_FAILURES_TO_SUSPEND)+ ]++ suspended = await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason=error,+ job_id=str(jobs[-1].id),)assert suspended is Trueawait database_sync_to_async(anode.refresh_from_db)()assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is True- assert is_node_suspended(anode, DataModelingJobEngine.DUCKGRES) is False- await database_sync_to_async(job.refresh_from_db)()- assert "has been suspended" in job.error++ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.+ for job in jobs:+ await database_sync_to_async(job.delete)()++ @pytest.mark.parametrize(+ "memory_error",+ [+ "ClickHouseMemoryLimitExceededError: Code: 241. DB::Exception: Memory limit (for query) exceeded",+ "ClickHouseMemoryLimitExceededError: Code: 241. DB::Exception: (total) memory limit exceeded",+ "ClickHouseMemoryLimitExceededError: Code: 241. DB::Exception: Query memory limit exceeded",+ ],+ )+ async def test_suspends_when_the_query_exhausts_memory(self, ateam, anode, asaved_query, adag, memory_error):+ from posthog.temporal.data_modeling.activities.utils import (+ CONSECUTIVE_FAILURES_TO_SUSPEND,+ is_node_suspended,+ maybe_suspend_node_for_engine,+ )++ jobs = [+ await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error=memory_error)+ for _ in range(CONSECUTIVE_FAILURES_TO_SUSPEND)+ ]++ suspended = await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason=memory_error,+ job_id=str(jobs[-1].id),+ )++ assert suspended is True+ await database_sync_to_async(anode.refresh_from_db)()+ assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is True++ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.+ for job in jobs:+ await database_sync_to_async(job.delete)()++ async def test_infrastructure_failure_breaks_a_customer_streak(self, ateam, anode, asaved_query, adag):+ from posthog.temporal.data_modeling.activities.utils import is_node_suspended, maybe_suspend_node_for_engine++ jobs = [await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom") for _ in range(4)]+ jobs.append(+ await _make_job(+ ateam, asaved_query, DataModelingJob.Status.FAILED, error="Code: 202. Too many simultaneous queries"+ )+ )+ job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")+ jobs.append(job)++ suspended = await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason="boom",+ job_id=str(job.id),+ )++ assert suspended is False+ await database_sync_to_async(anode.refresh_from_db)()+ assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is False# DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.for j in jobs: