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.

chore(data-modeling): add a command to clear unearned suspensions (#81213)

Jovan Sakovic304ad1788357
diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.py
index f95f914f9184..b880fee56a9b 100644
--- a/posthog/temporal/data_modeling/activities/utils.py
+++ b/posthog/temporal/data_modeling/activities/utils.py
@@ -34,6 +34,7 @@ __all__ = [
"bind_data_modeling_log_context",
"clear_node_suspension",
"clear_node_suspension_for_engine",
+ "count_leading_failures",
"is_externally_aborted",
"is_node_suspended",
"is_suspension_enforced",
@@ -143,7 +144,7 @@ def update_node_system_properties(
node.properties = properties
-def _count_leading_failures(saved_query_id: UUID, engine: str, *, since: str | None = None) -> int:
+def count_leading_failures(saved_query_id: UUID, engine: str, *, since: str | None = None) -> int:
jobs = DataModelingJob.objects.filter(saved_query_id=saved_query_id, engine=str(engine)).exclude(
# a skipped node never ran, so it is evidence of neither health nor failure. Counting it
# either way lets an upstream outage decide whether a broken node ever gets suspended.
@@ -179,7 +180,7 @@ def maybe_suspend_node_for_engine(
if is_node_suspended(node, engine):
return False
since = suspension_reset_at(node, engine)
- if _count_leading_failures(saved_query_id, engine, since=since) < CONSECUTIVE_FAILURES_TO_SUSPEND:
+ if count_leading_failures(saved_query_id, engine, since=since) < CONSECUTIVE_FAILURES_TO_SUSPEND:
return False
fingerprint = query_fingerprint(
DataWarehouseSavedQuery.objects.filter(id=saved_query_id).values_list("query", flat=True).first()
diff --git a/products/data_modeling/backend/logic/node_suspension.py b/products/data_modeling/backend/logic/node_suspension.py
index bddd11af56a4..c07c3e547b94 100644
--- a/products/data_modeling/backend/logic/node_suspension.py
+++ b/products/data_modeling/backend/logic/node_suspension.py
@@ -104,11 +104,25 @@ def _persist_change(node: Node, change: Callable[[Node], bool]) -> bool:
return True
-def resume_nodes(nodes: Iterable[Node], *, by: str, engine: str | None = None) -> int:
- """Returns how many of the nodes were actually suspended, not how many were passed in."""
- return sum(
- _persist_change(node, lambda locked: clear_node_suspension(locked, engine=engine, by=by)) for node in nodes
- )
+def resume_nodes(
+ nodes: Iterable[Node],
+ *,
+ by: str,
+ engine: str | None = None,
+ only_if: Callable[[Node], bool] | None = None,
+) -> int:
+ """Returns how many of the nodes were actually suspended, not how many were passed in.
+
+ `only_if` runs against the locked row, so a caller that decided to resume from an earlier read
+ can re-test that decision against state nothing else can change while the check runs.
+ """
+
+ def change(locked: Node) -> bool:
+ if only_if is not None and not only_if(locked):
+ return False
+ return clear_node_suspension(locked, engine=engine, by=by)
+
+ return sum(_persist_change(node, change) for node in nodes)
def suspension_state_for_saved_query(saved_query: "DataWarehouseSavedQuery") -> dict[str, dict]:
diff --git a/products/data_modeling/backend/management/commands/clear_unearned_node_suspensions.py b/products/data_modeling/backend/management/commands/clear_unearned_node_suspensions.py
new file mode 100644
index 000000000000..d900218c57cf
--- /dev/null
+++ b/products/data_modeling/backend/management/commands/clear_unearned_node_suspensions.py
@@ -0,0 +1,116 @@
+"""Clear suspension markers that the current counter would not produce.
+
+A node is suspended after five consecutive failed materializations. The counter used to count
+failures where the query never got to run - a busy or unreachable cluster, a preempted run - so
+some nodes carry a marker they never earned. Enforcement is flag-gated, which is what makes this
+worth a command rather than a wait: the markers are latent today and freeze those models all at
+once when the flag widens.
+
+Rather than judging a marker by its recorded reason, this re-runs the real counter over each one
+and clears whatever it no longer reaches five on. Region-agnostic - run it once per region.
+
+ python manage.py clear_unearned_node_suspensions # dry-run, every team
+ python manage.py clear_unearned_node_suspensions --apply
+ python manage.py clear_unearned_node_suspensions --team-id 2 --apply
+"""
+
+from collections.abc import Iterator
+from dataclasses import dataclass
+from typing import Any
+from uuid import UUID
+
+from django.core.management.base import BaseCommand, CommandParser
+
+from posthog.temporal.data_modeling.activities.utils import (
+ CONSECUTIVE_FAILURES_TO_SUSPEND,
+ count_leading_failures,
+ is_externally_aborted,
+)
+
+from products.data_modeling.backend.logic.node_suspension import resume_nodes, suspension_reset_at, suspension_state
+from products.data_modeling.backend.models.node import Node
+
+RESUMED_BY = "suspension_recheck"
+
+
+@dataclass(frozen=True, kw_only=True)
+class Marker:
+ node: Node
+ saved_query_id: UUID
+ engine: str
+ reason: str
+ failures: int
+
+ @property
+ def earned(self) -> bool:
+ return self.failures >= CONSECUTIVE_FAILURES_TO_SUSPEND
+
+ @property
+ def blamed_on_an_abort(self) -> bool:
+ return is_externally_aborted(self.reason)
+
+ def still_unearned(self, node: Node) -> bool:
+ """The sweep counts every marker before it clears any, and a model keeps failing while that
+ runs, so the verdict is re-taken against the row we are about to write."""
+ return (
+ count_leading_failures(self.saved_query_id, self.engine, since=suspension_reset_at(node, self.engine))
+ < CONSECUTIVE_FAILURES_TO_SUSPEND
+ )
+
+
+class Command(BaseCommand):
+ help = "Clear data modeling suspension markers the current failure counter would not produce"
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, default=None, help="Limit to one team")
+ parser.add_argument("--apply", action="store_true", default=False, help="Clear them (default: report only)")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int | None = options["team_id"]
+ apply: bool = options["apply"]
+
+ markers = list(self._markers(team_id))
+ unearned = [marker for marker in markers if not marker.earned]
+
+ for marker in unearned:
+ self.stdout.write(
+ f"team={marker.node.team_id} node={marker.node.id} engine={marker.engine} "
+ f"failures={marker.failures}/{CONSECUTIVE_FAILURES_TO_SUSPEND} "
+ f"blamed_on_an_abort={'yes' if marker.blamed_on_an_abort else 'no'}"
+ )
+
+ teams = len({marker.node.team_id for marker in markers})
+ blamed = sum(1 for marker in unearned if marker.blamed_on_an_abort)
+ self.stdout.write(f"Checked {len(markers)} marker(s) across {teams} team(s).")
+ self.stdout.write(f" unearned: {len(unearned)} ({blamed} blamed on a run that never executed)")
+ self.stdout.write(f" earned: {len(markers) - len(unearned)}")
+
+ if not apply:
+ self.stdout.write("Dry run. Re-run with --apply to clear the unearned ones.")
+ return
+
+ # one call per marker, because clearing every engine of a node would free markers its other
+ # engines did earn
+ cleared = sum(
+ resume_nodes([marker.node], by=RESUMED_BY, engine=marker.engine, only_if=marker.still_unearned)
+ for marker in unearned
+ )
+ self.stdout.write(f"Cleared {cleared} marker(s).")
+
+ def _markers(self, team_id: int | None) -> Iterator[Marker]:
+ nodes = Node.objects.filter(properties__system__has_key="suspended", saved_query__isnull=False)
+ if team_id is not None:
+ nodes = nodes.filter(team_id=team_id)
+
+ for node in nodes.iterator():
+ saved_query_id = node.saved_query_id
+ if saved_query_id is None:
+ continue # the queryset already excludes these; this is what narrows the type
+ for engine, entry in suspension_state(node).items():
+ yield Marker(
+ node=node,
+ saved_query_id=saved_query_id,
+ engine=engine,
+ reason=entry.get("reason") or "",
+ failures=count_leading_failures(saved_query_id, engine, since=suspension_reset_at(node, engine)),
+ )
diff --git a/products/data_modeling/backend/test/test_clear_unearned_node_suspensions.py b/products/data_modeling/backend/test/test_clear_unearned_node_suspensions.py
new file mode 100644
index 000000000000..2f61c8ac2a12
--- /dev/null
+++ b/products/data_modeling/backend/test/test_clear_unearned_node_suspensions.py
@@ -0,0 +1,124 @@
+from io import StringIO
+from uuid import uuid4
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from django.core.management import call_command
+
+from products.data_modeling.backend.logic.node_suspension import (
+ is_node_suspended,
+ mark_node_suspended,
+ suspension_reset_at,
+)
+from products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dag
+from products.data_modeling.backend.management.commands import clear_unearned_node_suspensions as command_module
+from products.data_modeling.backend.models.data_modeling_job import (
+ DataModelingJob,
+ DataModelingJobEngine,
+ DataModelingJobStatus,
+)
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.node import Node
+
+CUSTOMER_ERROR = "Code: 47. DB::Exception: Unknown expression identifier 'foo'"
+ABORT_ERROR = "Preempted: a new DAG run started before this job completed"
+
+
+class TestClearUnearnedNodeSuspensions(BaseTest):
+ def _suspended_node(self, *, errors: list[str], engine: str = DataModelingJobEngine.CLICKHOUSE) -> Node:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=f"model_{uuid4().hex[:8]}",
+ team=self.team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ )
+ node = sync_saved_query_to_dag(saved_query)
+ assert node is not None
+ self._record_failures(saved_query, errors, engine=engine)
+ mark_node_suspended(node, engine=engine, reason=errors[-1], job_id=str(uuid4()))
+ node.save()
+ return node
+
+ def _record_failures(
+ self,
+ saved_query: DataWarehouseSavedQuery,
+ errors: list[str],
+ *,
+ engine: str = DataModelingJobEngine.CLICKHOUSE,
+ ) -> None:
+ # oldest first, so the last error given is the newest job the counter reads
+ for error in errors:
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ engine=engine,
+ status=DataModelingJobStatus.FAILED,
+ error=error,
+ )
+
+ def test_clears_a_marker_the_counter_no_longer_reaches(self):
+ # an aborted run sits inside the window, so only three failures are the query's own
+ node = self._suspended_node(
+ errors=[CUSTOMER_ERROR, ABORT_ERROR, CUSTOMER_ERROR, CUSTOMER_ERROR, CUSTOMER_ERROR]
+ )
+
+ call_command("clear_unearned_node_suspensions", "--apply", stdout=StringIO())
+
+ node.refresh_from_db()
+ assert not is_node_suspended(node, DataModelingJobEngine.CLICKHOUSE)
+ # without the watermark the same old failures re-suspend it on the next run
+ assert suspension_reset_at(node, DataModelingJobEngine.CLICKHOUSE) is not None
+
+ def test_keeps_a_marker_five_genuine_failures_still_earn(self):
+ node = self._suspended_node(errors=[CUSTOMER_ERROR] * 5)
+
+ call_command("clear_unearned_node_suspensions", "--apply", stdout=StringIO())
+
+ node.refresh_from_db()
+ assert is_node_suspended(node, DataModelingJobEngine.CLICKHOUSE)
+
+ def test_dry_run_leaves_the_marker_alone(self):
+ node = self._suspended_node(errors=[CUSTOMER_ERROR, ABORT_ERROR, CUSTOMER_ERROR])
+
+ call_command("clear_unearned_node_suspensions", stdout=StringIO())
+
+ node.refresh_from_db()
+ assert is_node_suspended(node, DataModelingJobEngine.CLICKHOUSE)
+
+ def test_clears_only_the_engine_that_no_longer_earns_it(self):
+ node = self._suspended_node(errors=[CUSTOMER_ERROR] * 5)
+ saved_query = node.saved_query
+ assert saved_query is not None
+ self._record_failures(
+ saved_query, [CUSTOMER_ERROR, ABORT_ERROR, CUSTOMER_ERROR], engine=DataModelingJobEngine.DUCKGRES
+ )
+ mark_node_suspended(node, engine=DataModelingJobEngine.DUCKGRES, reason=CUSTOMER_ERROR, job_id=str(uuid4()))
+ node.save()
+
+ call_command("clear_unearned_node_suspensions", "--apply", stdout=StringIO())
+
+ node.refresh_from_db()
+ assert is_node_suspended(node, DataModelingJobEngine.CLICKHOUSE)
+ assert not is_node_suspended(node, DataModelingJobEngine.DUCKGRES)
+
+ def test_keeps_a_marker_the_model_earns_while_the_sweep_runs(self):
+ node = self._suspended_node(
+ errors=[CUSTOMER_ERROR, ABORT_ERROR, CUSTOMER_ERROR, CUSTOMER_ERROR, CUSTOMER_ERROR]
+ )
+ saved_query = node.saved_query
+ assert saved_query is not None
+ resume = command_module.resume_nodes
+
+ def fail_twice_more_then_resume(*args, **kwargs):
+ # stands in for the materializations that keep running while a whole-region sweep walks
+ # its list: by the time this marker comes up for clearing, the streak is genuine
+ self._record_failures(saved_query, [CUSTOMER_ERROR, CUSTOMER_ERROR])
+ return resume(*args, **kwargs)
+
+ with mock.patch.object(command_module, "resume_nodes", fail_twice_more_then_resume):
+ call_command("clear_unearned_node_suspensions", "--apply", stdout=StringIO())
+
+ node.refresh_from_db()
+ assert is_node_suspended(node, DataModelingJobEngine.CLICKHOUSE)