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(data-modeling): alert when the warehouse object reads rollup misses a day (#114080)

Thiago Salvatore6912f6c70811
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index a0cd9d2806a2..a209c2b4f606 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -78,6 +78,7 @@ defs = dagster.Definitions(
deletes.run_deletes_after_manual_trigger,
data_deletion_requests.data_deletion_request_pickup_sensor,
data_deletion_requests.verify_queued_deletion_requests,
+ warehouse_object_reads_daily.warehouse_object_reads_daily_overdue_sensor,
],
loggers=loggers,
resources=resources,
diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.py
index 0214dfa44df2..7d3b1b9e8d94 100644
--- a/posthog/dags/slack_alerts.py
+++ b/posthog/dags/slack_alerts.py
@@ -73,7 +73,7 @@ SLACK_BLOCK_REJECTION_ERRORS = frozenset(
)
-def send_slack_alert(context, client, channel: str, blocks: list, fallback_text: str) -> None:
+def send_slack_alert(context, client, channel: str, blocks: list, fallback_text: str) -> bool:
"""Post an alert, falling back to a plain-text message if the rich blocks are rejected.
A block-formatting or size error (e.g. an oversized error field exceeding Slack's 3000-char
@@ -84,24 +84,26 @@ def send_slack_alert(context, client, channel: str, blocks: list, fallback_text:
try:
client.chat_postMessage(channel=channel, blocks=blocks, text=fallback_text)
context.log.info(f"Sent Slack notification to {channel}")
- return
+ return True
except SlackApiError as e:
error_code = e.response.get("error") if e.response is not None else None
if error_code not in SLACK_BLOCK_REJECTION_ERRORS:
# The message may have posted (rate limit, transient read error, ...) — don't duplicate it.
context.log.exception(f"Failed to send Slack notification to {channel}: {str(e)}")
- return
+ return False
context.log.warning(f"Slack rejected blocks ({error_code}) for {channel}, retrying text-only")
except Exception as e:
# Non-API failure: the outcome is ambiguous, so log and stop rather than risk a duplicate.
context.log.exception(f"Failed to send Slack notification to {channel}: {str(e)}")
- return
+ return False
try:
client.chat_postMessage(channel=channel, text=fallback_text)
context.log.info(f"Sent text-only Slack fallback to {channel}")
+ return True
except Exception as e:
context.log.exception(f"Failed to send text-only Slack fallback to {channel}: {str(e)}")
+ return False
# A manually materialized or backfilled asset runs under Dagster's implicit `__ASSET_JOB`, whose
diff --git a/posthog/dags/tests/test_warehouse_object_reads_daily.py b/posthog/dags/tests/test_warehouse_object_reads_daily.py
index c47e2f585f63..a294a037a271 100644
--- a/posthog/dags/tests/test_warehouse_object_reads_daily.py
+++ b/posthog/dags/tests/test_warehouse_object_reads_daily.py
@@ -1,15 +1,19 @@
import json
import uuid
from collections.abc import Iterator
-from datetime import date, datetime, time, timedelta
+from datetime import UTC, date, datetime, time, timedelta
from functools import partial
from typing import Any
import pytest
-from unittest.mock import patch
+import time_machine
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
import dagster
from clickhouse_driver import Client
+from parameterized import parameterized
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.cluster import ClickhouseCluster
@@ -19,6 +23,7 @@ from posthog.dags.warehouse_object_reads_daily import (
ROLLUP_START_DATE,
insert_rollup_into_staging,
warehouse_object_reads_daily_job,
+ warehouse_object_reads_daily_overdue_sensor,
warehouse_object_reads_daily_schedule,
)
from posthog.models import Team
@@ -206,17 +211,13 @@ def test_rollup_counts_view_and_table_reads_and_refreshes_and_replaces_its_parti
assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == expected
cluster.any_host(clear_archive).result()
- run_rollup(cluster, day)
- assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == []
+ run_rollup(cluster, day, succeeds=False)
+ assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == expected
@pytest.mark.django_db
-def test_rollup_of_a_day_without_archive_rows_succeeds(cluster: ClickhouseCluster) -> None:
- result = warehouse_object_reads_daily_job.execute_in_process(
- partition_key=ROLLUP_START_DATE, resources={"cluster": cluster}
- )
-
- assert result.success
+def test_rollup_of_a_day_without_archive_rows_fails(cluster: ClickhouseCluster) -> None:
+ run_rollup(cluster, date.fromisoformat(ROLLUP_START_DATE), succeeds=False)
def test_schedule_runs_after_the_archive_day_closes() -> None:
@@ -239,3 +240,41 @@ def test_rollup_fails_before_touching_staging_while_another_run_executes(cluster
assert not result.success
assert other_run.run_id in str(result.all_events)
recreate_staging_table.assert_not_called()
+
+
+ [
+ ("before_the_deadline", time(hour=9, minute=59), False, False, 0),
+ ("published_day", time(hour=10), True, False, 0),
+ ("missing_day", time(hour=10), False, False, 1),
+ ("missing_day_slack_down", time(hour=10), False, True, 2),
+ ]
+)
+@override_settings(CLOUD_DEPLOYMENT="US", DAGSTER_DOMAIN="dagster.example.com")
+def test_overdue_sensor_alerts_once_when_yesterday_is_not_published(
+ _name: str, check_time: time, published: bool, slack_down: bool, expected_posts: int
+) -> None:
+ today = date(2026, 10, 8)
+ instance = dagster.DagsterInstance.ephemeral()
+ if published:
+ instance.create_run_for_job(
+ job_def=warehouse_object_reads_daily_job,
+ status=dagster.DagsterRunStatus.SUCCESS,
+ tags={"dagster/partition": (today - timedelta(days=1)).isoformat()},
+ )
+ slack = MagicMock()
+ if slack_down:
+ slack.get_client.return_value.chat_postMessage.side_effect = ConnectionError
+
+ with time_machine.travel(datetime.combine(today, check_time, tzinfo=UTC), tick=False):
+ context = dagster.build_sensor_context(instance=instance, resources={"slack": slack})
+ warehouse_object_reads_daily_overdue_sensor(context)
+ warehouse_object_reads_daily_overdue_sensor(
+ dagster.build_sensor_context(instance=instance, cursor=context.cursor, resources={"slack": slack})
+ )
+
+ posts = slack.get_client.return_value.chat_postMessage.call_args_list
+ assert len(posts) == expected_posts
+ if expected_posts:
+ assert posts[0].kwargs["channel"] == "#alerts-data-modeling"
+ assert "2026-10-07" in posts[0].kwargs["text"]
diff --git a/posthog/dags/warehouse_object_reads_daily.py b/posthog/dags/warehouse_object_reads_daily.py
index 1130396f4b46..b46268df8550 100644
--- a/posthog/dags/warehouse_object_reads_daily.py
+++ b/posthog/dags/warehouse_object_reads_daily.py
@@ -3,6 +3,7 @@ from datetime import UTC, date, datetime, time, timedelta
from django.conf import settings
import dagster
+import dagster_slack
from clickhouse_driver import Client
from posthog.clickhouse.client.connection import NodeRole
@@ -19,6 +20,7 @@ from posthog.clickhouse.warehouse_object_reads import (
from posthog.dags.common import JobOwners, settings_with_log_comment
from posthog.dags.common.common import EXECUTING_RUN_STATUSES, describe_runs
from posthog.dags.common.resources import SatelliteClickhouseClusterResource
+from posthog.dags.slack_alerts import notification_channel_per_team, send_slack_alert
from products.web_analytics.dags.web_preaggregated_utils import (
get_partitions,
@@ -38,6 +40,8 @@ MAX_THREADS = 8
ROLLUP_NODE_ROLE = NodeRole.AUX
ROLLUP_START_DATE = "2026-09-17"
SCHEDULE_HOUR_UTC = 7
+OVERDUE_AFTER_UTC = time(hour=10)
+OVERDUE_CHECK_INTERVAL_SECONDS = 60 * 60
CONCURRENCY_TAG = {"warehouse_object_reads_backfill_concurrency": "warehouse_object_reads_v1"}
MAX_RUNTIME_SECONDS = 60 * 60
STUCK_RUN_AGE = timedelta(hours=3)
@@ -238,17 +242,9 @@ def publish_day(context: dagster.OpExecutionContext, cluster: ClickhouseCluster,
description=f"The archive has {source_rows} reads for {day}, but staging is empty. "
"The published day was kept. Run the day again."
)
- drop_day_partition(cluster, day)
-
-
-def drop_day_partition(cluster: ClickhouseCluster, day: date) -> None:
- cluster.any_host_by_roles(
- lambda client: client.execute(
- f"ALTER TABLE {SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE} DROP PARTITION ID %(partition_id)s",
- {"partition_id": day.strftime(PARTITION_ID_FORMAT)},
- ),
- [ROLLUP_NODE_ROLE],
- ).result()
+ raise dagster.Failure(
+ description=f"The archive has no reads for {day}. Query tagging may be broken. The published day was kept."
+ )
@dagster.op
@@ -290,5 +286,49 @@ warehouse_object_reads_daily_schedule = dagster.build_schedule_from_partitioned_
warehouse_object_reads_daily_job,
hour_of_day=SCHEDULE_HOUR_UTC,
minute_of_hour=0,
- default_status=dagster.DefaultScheduleStatus.STOPPED,
+ default_status=dagster.DefaultScheduleStatus.RUNNING,
)
+
+
+def has_published_day(instance: dagster.DagsterInstance, day: date) -> bool:
+ return bool(
+ instance.get_run_records(
+ dagster.RunsFilter(
+ job_name=warehouse_object_reads_daily_job.name,
+ statuses=[dagster.DagsterRunStatus.SUCCESS],
+ tags={"dagster/partition": day.isoformat()},
+ ),
+ limit=1,
+ )
+ )
+
+
+ minimum_interval_seconds=OVERDUE_CHECK_INTERVAL_SECONDS,
+ default_status=dagster.DefaultSensorStatus.RUNNING,
+)
+def warehouse_object_reads_daily_overdue_sensor(
+ context: dagster.SensorEvaluationContext, slack: dagster_slack.SlackResource
+) -> dagster.SkipReason | None:
+ now = datetime.now(UTC)
+ if now.time() < OVERDUE_AFTER_UTC:
+ return dagster.SkipReason(f"The rollup is not overdue before {OVERDUE_AFTER_UTC} UTC.")
+ day = now.date() - timedelta(days=1)
+ if context.cursor == day.isoformat():
+ return dagster.SkipReason(f"Already alerted that {day} is missing.")
+ if has_published_day(context.instance, day):
+ return dagster.SkipReason(f"{day} is published.")
+ if not settings.CLOUD_DEPLOYMENT:
+ return dagster.SkipReason(f"{day} is missing, but alerts only go out in cloud deployments.")
+
+ job_url = f"https://{settings.DAGSTER_DOMAIN}/locations/clickhouse/jobs/{warehouse_object_reads_daily_job.name}"
+ message = (
+ f":hourglass: `{warehouse_object_reads_daily_job.name}` has no successful run for {day} "
+ f"by {OVERDUE_AFTER_UTC:%H:%M} UTC. Check that its schedule is running and that no run is stuck in the queue: "
+ f"<{job_url}|View in Dagster>\nEnvironment: {settings.CLOUD_DEPLOYMENT}"
+ )
+ blocks = [{"type": "section", "text": {"type": "mrkdwn", "text": message}}]
+ channel = notification_channel_per_team[JobOwners.TEAM_DATA_MODELING.value]
+ if send_slack_alert(context, slack.get_client(), channel, blocks, message):
+ context.update_cursor(day.isoformat())
+ return None