: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-quality): streamline metric schedule reconciliation (#96584)
Thiago Salvatorec361886002ac
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.mdindex d9926d1e6d05..17a688d66c19 100644--- a/docs/internal/data-quality-checks.md+++ b/docs/internal/data-quality-checks.md@@ -56,6 +56,6 @@ Temporal owns the interval, pause state, and next execution time. The schedule eScheduled executions skip an occurrence when the previous scheduled workflow is still running. Temporal catches up missed occurrences within 15 minutes and does not pause a schedule after a failed run. Manual runs keep their existing behavior. A scheduled activity rechecks schedule existence and pause state before selecting current enabled checks. An executing check can finish after the schedule is paused. Feature flags, subject existence, and execution permissions are checked in activities.-A reconciler runs every 15 minutes, processing bounded pages of checks and product-filtered Temporal schedules. It repairs missing schedules without changing existing intervals or pause states, and deletes schedules whose metrics no longer exist. Deleting or disabling all checks retains the metric's schedule preferences and executes no check queries. Deleted metrics stop producing check queries immediately, even if schedule cleanup needs a retry.+A reconciler runs every 15 minutes, processing bounded pages of checks and product-filtered Temporal schedules. It performs up to 10 independent repairs or deletions at a time within a page, then advances only after the whole page succeeds. It repairs missing schedules without changing existing intervals or pause states, and deletes schedules whose metrics no longer exist. Deleting or disabling all checks retains the metric's schedule preferences and executes no check queries. Deleted metrics stop producing check queries immediately, even if schedule cleanup needs a retry.In the metric Tests tab, a failed schedule edit refreshes the persisted state and offers Reload before another edit. Schedule controls stay disabled while a request is pending or its outcome is uncertain.diff --git a/playwright/e2e/data-quality-overview.spec.ts b/playwright/e2e/data-quality-overview.spec.tsindex 245c1505d08b..26149fc16204 100644--- a/playwright/e2e/data-quality-overview.spec.ts+++ b/playwright/e2e/data-quality-overview.spec.ts@@ -11,7 +11,7 @@ const CHECK_NAME = 'orders_has_rows'const SUBJECT_NAME = 'orders_e2e'test('edits and deletes a check from Data Ops', async ({ page, playwrightSetup }) => {- const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true })+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })const auth = {headers: {Authorization: `Bearer ${workspace.personal_api_key}`,diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex bdcd2db9ba1f..59179ef4fe6e 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -30,7 +30,14 @@ from ..logic.notifications import notify_materialization_blockedfrom ..logic.permissions import authorized_subject_types, restrict_subject_types, writable_subjectsfrom ..logic.registry import UnknownCheckTypeError, list_check_typesfrom ..logic.run_records import record_check_run-from ..logic.schedules import MetricCheckSchedule, ScheduleUnavailableError, get_schedule, set_schedule+from ..logic.schedule_service import get_schedule_with_history, schedule_with_history, update_schedule+from ..logic.schedules import (+ MetricCheckSchedule,+ ScheduleUnavailableError,+ ScheduleUpdateResult,+ get_schedule,+ set_schedule,+)from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entryfrom ..logic.subject_access import (DenialContext,@@ -56,6 +63,7 @@ __all__ = ["log_metric_schedule_change","MetricCheckSchedule","ScheduleUnavailableError",+ "ScheduleUpdateResult","CheckConfigError","CheckEditConflict","CheckStatusRow",@@ -88,6 +96,7 @@ __all__ = ["from_config_entry","get_gate_config","get_schedule",+ "get_schedule_with_history","list_check_types","notify_materialization_blocked","quality_audit_mode",@@ -98,6 +107,7 @@ __all__ = ["roll_up_health","set_gate_materialization_on_checks","set_schedule",+ "schedule_with_history","soft_delete_check","start_check_suite","subject_health",@@ -105,6 +115,7 @@ __all__ = ["suites_backing_unreadable_runs_q","to_config_entry","unreadable_suites_q",+ "update_schedule","upsert_check","validate_check","visible_checks",diff --git a/products/data_quality/backend/logic/schedule_service.py b/products/data_quality/backend/logic/schedule_service.pynew file mode 100644index 000000000000..e6834c51c572--- /dev/null+++ b/products/data_quality/backend/logic/schedule_service.py@@ -0,0 +1,72 @@+from __future__ import annotations++from dataclasses import replace+from typing import TYPE_CHECKING+from uuid import UUID++from ..activity_logging import log_metric_schedule_change+from ..facade.enums import SuiteRunTrigger+from ..models import DataQualitySuiteRun+from .schedules import MetricCheckSchedule, get_schedule, update_schedule_with_snapshots+from .subject_access import suites_backing_unreadable_runs_q, unreadable_suites_q++if TYPE_CHECKING:+ from posthog.models import User++ from ..facade.enums import SubjectType+ from .subject_access import DenialContext+++def schedule_with_history(+ team_id: int,+ subject_type: SubjectType,+ subject_uuid: str | UUID,+ schedule: MetricCheckSchedule,+ authorization_context: DenialContext | None = None,+) -> MetricCheckSchedule:+ suites = DataQualitySuiteRun.objects.for_team(team_id).filter(+ subject_type=subject_type,+ subject_uuid=subject_uuid,+ trigger=SuiteRunTrigger.SCHEDULED,+ )+ if authorization_context is not None:+ suites = suites.exclude(unreadable_suites_q(authorization_context)).exclude(+ suites_backing_unreadable_runs_q(team_id, authorization_context)+ )+ last_suite = suites.order_by("-started_at", "-id").first()+ if last_suite is None:+ return schedule+ return replace(schedule, last_run_at=last_suite.started_at, last_suite_run=last_suite.id)+++def get_schedule_with_history(+ team_id: int,+ subject_type: SubjectType,+ subject_uuid: str | UUID,+ authorization_context: DenialContext | None = None,+) -> MetricCheckSchedule | None:+ schedule = get_schedule(team_id, subject_type, subject_uuid)+ if schedule is None:+ return None+ return schedule_with_history(team_id, subject_type, subject_uuid, schedule, authorization_context)+++def update_schedule(+ team_id: int,+ subject_type: SubjectType,+ subject_uuid: str | UUID,+ *,+ user: User,+ authorization_context: DenialContext | None = None,+ interval: str | None = None,+ enabled: bool | None = None,+) -> MetricCheckSchedule:+ result = update_schedule_with_snapshots(+ team_id,+ subject_type,+ subject_uuid,+ interval=interval,+ enabled=enabled,+ )+ log_metric_schedule_change(team_id, str(subject_uuid), result.before, result.after, user)+ return schedule_with_history(team_id, subject_type, subject_uuid, result.after, authorization_context)diff --git a/products/data_quality/backend/logic/schedules.py b/products/data_quality/backend/logic/schedules.pyindex 4a222473cb62..0e1cc87f8230 100644--- a/products/data_quality/backend/logic/schedules.py+++ b/products/data_quality/backend/logic/schedules.py@@ -4,6 +4,7 @@ from uuid import UUIDimport structlogfrom asgiref.sync import async_to_sync, sync_to_async+from temporalio.client import ScheduleDescriptionfrom posthog.dataclasses import frozenfrom posthog.models.scoping.manager import resolve_effective_team_id@@ -30,12 +31,62 @@ class MetricCheckSchedule:last_suite_run: UUID | None = None+@frozen+class ScheduleUpdateResult:+ before: MetricCheckSchedule+ after: MetricCheckSchedule++def schedule_key(team_id: int, subject_type: str, subject_uuid: str | UUID) -> MetricScheduleKey:if subject_type != SubjectType.METRIC:raise ValueError("Only metrics support recurring check schedules")return MetricScheduleKey(team_id=resolve_effective_team_id(team_id), metric_id=UUID(str(subject_uuid)))+def schedule_snapshot(key: MetricScheduleKey, description: ScheduleDescription) -> MetricCheckSchedule:+ schedule = description.schedule+ upcoming = description.info.next_action_times+ return MetricCheckSchedule(+ id=key.id,+ interval=label_from_interval(schedule.spec.intervals[0].every),+ enabled=not schedule.state.paused,+ next_run_at=upcoming[0] if upcoming and not schedule.state.paused else None,+ )+++async def _describe_schedule(schedules: MetricSchedules, key: MetricScheduleKey) -> MetricCheckSchedule | None:+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):+ description = await schedules.describe(key)+ return schedule_snapshot(key, description) if description is not None else None+++async def _update_schedule_with_snapshots(+ team_id: int,+ subject_type: str,+ subject_uuid: str | UUID,+ *,+ interval: str | None = None,+ enabled: bool | None = None,+) -> ScheduleUpdateResult:+ key = await sync_to_async(schedule_key)(team_id, subject_type, subject_uuid)+ try:+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):+ schedules = MetricSchedules(await async_connect())+ before = await _describe_schedule(schedules, key)+ if before is None:+ raise ScheduleUnavailableError()+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):+ await schedules.update(key, interval=interval, enabled=enabled)+ after = await _describe_schedule(schedules, key)+ if after is None:+ raise ScheduleUnavailableError()+ return ScheduleUpdateResult(before=before, after=after)+ except ScheduleUnavailableError:+ raise+ except Exception as error:+ raise ScheduleUnavailableError() from error++@async_to_syncasync def provision_metric_schedule(team_id: int, metric_id: str) -> None:key = await sync_to_async(schedule_key)(team_id, SubjectType.METRIC, metric_id)@@ -52,17 +103,7 @@ async def get_schedule(team_id: int, subject_type: str, subject_uuid: str | UUIDtry:async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):description = await MetricSchedules(await async_connect()).describe(key)- if description is None:- return None- schedule = description.schedule- interval = label_from_interval(schedule.spec.intervals[0].every)- upcoming = description.info.next_action_times- return MetricCheckSchedule(- id=key.id,- interval=interval,- enabled=not schedule.state.paused,- next_run_at=upcoming[0] if upcoming and not schedule.state.paused else None,- )+ return schedule_snapshot(key, description) if description is not None else Noneexcept Exception as error:raise ScheduleUnavailableError() from error@@ -82,3 +123,21 @@ async def set_schedule(await MetricSchedules(await async_connect()).update(key, interval=interval, enabled=enabled)except Exception as error:raise ScheduleUnavailableError() from error+++@async_to_sync+async def update_schedule_with_snapshots(+ team_id: int,+ subject_type: str,+ subject_uuid: str | UUID,+ *,+ interval: str | None = None,+ enabled: bool | None = None,+) -> ScheduleUpdateResult:+ return await _update_schedule_with_snapshots(+ team_id,+ subject_type,+ subject_uuid,+ interval=interval,+ enabled=enabled,+ )diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex e96a519b8cb1..d718284b0ac0 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -9,7 +9,6 @@ a suite-run handle to poll.from collections import defaultdictfrom collections.abc import Callable, Sequence-from dataclasses import replacefrom functools import cached_propertyfrom typing import TYPE_CHECKING, ClassVar, castfrom uuid import UUID@@ -36,7 +35,7 @@ from posthog.permissions import APIScopePermission, TeamMemberAccessPermission,from products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom ..facade import api-from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType, SuiteRunTrigger+from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectTypefrom ..facade.flags import is_data_quality_checks_enabledfrom ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .serializers import (@@ -597,46 +596,35 @@ class MetricCheckViewSet(_BaseCheckViewSet):def schedule(self, request: Request, **kwargs) -> Response:if not self._subject_checks().exists():raise NotFound("Add a check to create this metric's schedule.")+ authorization_context = self._denial_context() if self._can_be_object_denied() else Noneif request.method == "PATCH":self._require_enabled_check_access()serializer = DataQualityCheckScheduleUpdateSerializer(data=request.data)serializer.is_valid(raise_exception=True)+ schedule: api.MetricCheckSchedule | Nonetry:- before = api.get_schedule(self.team_id, self.subject_type, self.subject_uuid)- if before is None:- raise api.ScheduleUnavailableError()if request.method == "PATCH":- api.set_schedule(self.team_id, self.subject_type, self.subject_uuid, **serializer.validated_data)- schedule = (- api.get_schedule(self.team_id, self.subject_type, self.subject_uuid)- if request.method == "PATCH"- else before- )+ schedule = api.update_schedule(+ self.team_id,+ self.subject_type,+ self.subject_uuid,+ user=cast(User, request.user),+ authorization_context=authorization_context,+ **serializer.validated_data,+ )+ else:+ schedule = api.get_schedule_with_history(+ self.team_id, self.subject_type, self.subject_uuid, authorization_context+ )if schedule is None:raise api.ScheduleUnavailableError()except api.ScheduleUnavailableError as error:raise ScheduleUnavailableAPIError() from error- if request.method == "PATCH":- api.log_metric_schedule_change(self.team_id, self.subject_uuid, before, schedule, cast(User, request.user))- return Response(DataQualityCheckScheduleSerializer(self._with_schedule_history(schedule)).data)+ return Response(DataQualityCheckScheduleSerializer(schedule).data)def _subject_checks(self) -> QuerySet[DataQualityCheck]:return DataQualityCheck.objects.for_team(self.team_id).filter(metric_id=self.subject_uuid)- def _with_schedule_history(self, schedule: api.MetricCheckSchedule) -> api.MetricCheckSchedule:- suites = DataQualitySuiteRun.objects.for_team(self.team_id).filter(- subject_type=self.subject_type, subject_uuid=self.subject_uuid, trigger=SuiteRunTrigger.SCHEDULED- )- if self._can_be_object_denied():- context = self._denial_context()- suites = suites.exclude(api.unreadable_suites_q(context)).exclude(- api.suites_backing_unreadable_runs_q(self.team_id, context)- )- last_suite = suites.order_by("-started_at", "-id").first()- if last_suite is None:- return schedule- return replace(schedule, last_run_at=last_suite.started_at, last_suite_run=last_suite.id)-class _BaseSuiteRunViewSet(_SubjectScopedViewSet,diff --git a/products/data_quality/backend/temporal/activities/reconcile_schedules.py b/products/data_quality/backend/temporal/activities/reconcile_schedules.pyindex 84575e0b5a97..ffd2d2e54afe 100644--- a/products/data_quality/backend/temporal/activities/reconcile_schedules.py+++ b/products/data_quality/backend/temporal/activities/reconcile_schedules.py@@ -1,6 +1,8 @@+import asynciofrom collections import defaultdictfrom temporalio import activity+from temporalio.client import Clientfrom temporalio.service import RPCError, RPCStatusCodefrom posthog.dataclasses import frozen@@ -16,6 +18,7 @@ from ...logic.metric_schedules import SCHEDULE_PREFIX, SCHEDULE_TYPE, MetricSchefrom ...models import DataQualityCheckRECONCILE_PAGE_SIZE = 100+RECONCILE_CONCURRENCY_LIMIT = 10@frozen@@ -49,34 +52,52 @@ def _dead_schedules(schedule_ids: list[str]) -> list[str]:@activity.defnasync def reconcile_metric_schedules_activity(cursor: ScheduleReconcileCursor) -> ScheduleReconcileCursor:client = await async_connect()+ metric_schedules = MetricSchedules(client)+ semaphore = asyncio.Semaphore(RECONCILE_CONCURRENCY_LIMIT)if not cursor.cleanup:checks = await database_sync_to_async_pool(_check_page)(cursor.after_check_id)- keys = {- MetricScheduleKey(team_id=check.team_id, metric_id=check.metric_id) for check in checks if check.metric_id- }- for key in keys:- await MetricSchedules(client).ensure(key)- activity.heartbeat()+ keys = list(+ dict.fromkeys(+ MetricScheduleKey(team_id=check.team_id, metric_id=check.metric_id)+ for check in checks+ if check.metric_id+ )+ )+ async with asyncio.TaskGroup() as tasks:+ for key in keys:+ tasks.create_task(_ensure_schedule(metric_schedules, key, semaphore))return ScheduleReconcileCursor(after_check_id=str(checks[-1].id) if checks else None,cleanup=len(checks) < RECONCILE_PAGE_SIZE,)- schedules = await client.list_schedules(+ schedule_page = await client.list_schedules(query=f'{POSTHOG_SCHEDULE_TYPE_KEY.name} = "{SCHEDULE_TYPE}"',page_size=RECONCILE_PAGE_SIZE,next_page_token=cursor.next_page_token,)- await schedules.fetch_next_page()- schedule_ids = [schedule.id for schedule in schedules.current_page or []]+ await schedule_page.fetch_next_page()+ schedule_ids = [schedule.id for schedule in schedule_page.current_page or []]dead = await database_sync_to_async_pool(_dead_schedules)(schedule_ids)- for schedule_id in dead:+ async with asyncio.TaskGroup() as tasks:+ for schedule_id in dead:+ tasks.create_task(_delete_schedule(client, schedule_id, semaphore))+ return ScheduleReconcileCursor(+ cleanup=True, next_page_token=schedule_page.next_page_token, done=schedule_page.next_page_token is None+ )+++async def _ensure_schedule(schedules: MetricSchedules, key: MetricScheduleKey, semaphore: asyncio.Semaphore) -> None:+ async with semaphore:+ await schedules.ensure(key)+ activity.heartbeat()+++async def _delete_schedule(client: Client, schedule_id: str, semaphore: asyncio.Semaphore) -> None:+ async with semaphore:try:await a_delete_schedule(client, schedule_id)except RPCError as error:if error.status != RPCStatusCode.NOT_FOUND:raiseactivity.heartbeat()- return ScheduleReconcileCursor(- cleanup=True, next_page_token=schedules.next_page_token, done=schedules.next_page_token is None- )diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 86cf546a3e48..5fbbd7ca455d 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -1,5 +1,5 @@from types import SimpleNamespace-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, castfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -22,6 +22,7 @@ from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade import apifrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectTypefrom products.data_quality.backend.logic import checks as checks_logic+from products.data_quality.backend.logic.metric_schedules import MetricScheduleKey, MetricSchedulesfrom products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.data_quality.backend.presentation.serializers import DataQualitySuiteRunSerializer@@ -48,9 +49,8 @@ class TestMetricCheckAPI(APIBaseTest):referenced_table_names=[],)self.temporal = schedule_client()- self.enterContext(- patch("products.data_quality.backend.logic.schedules.async_connect", AsyncMock(return_value=self.temporal))- )+ self.connect = AsyncMock(return_value=self.temporal)+ self.enterContext(patch("products.data_quality.backend.logic.schedules.async_connect", self.connect))self.url = f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.id}/checks"self.suites_url = f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.id}/check_suite_runs"flag = patch(FLAG, return_value=True)@@ -157,12 +157,66 @@ class TestMetricCheckAPI(APIBaseTest):assert self.client.delete(f"{self.url}/{check['id']}/").status_code == 204assert self.client.get(f"{self.url}/schedule/").status_code == 200- def test_schedule_service_failure_is_retryable(self) -> None:+ def test_schedule_patch_reuses_one_connection_and_records_snapshots(self) -> None:self._create()- with patch("products.data_quality.backend.logic.schedules.async_connect", AsyncMock(side_effect=TimeoutError)):+ self.connect.reset_mock()++ response = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour", "enabled": False})++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["interval"] == "6hour"+ assert response.json()["enabled"] is False+ assert self.connect.await_count == 1+ entry = ActivityLog.objects.get(+ team_id=self.team.id,+ scope="DataQualityCheckSchedule",+ activity="updated",+ )+ assert entry.detail is not None+ assert entry.detail["changes"] == [+ {+ "type": "DataQualityCheckSchedule",+ "field": "interval",+ "action": "changed",+ "before": "24hour",+ "after": "6hour",+ },+ {+ "type": "DataQualityCheckSchedule",+ "field": "enabled",+ "action": "changed",+ "before": True,+ "after": False,+ },+ ]++ @parameterized.expand([("connection",), ("initial_read",), ("update",), ("read_after",)])+ def test_schedule_service_failure_is_retryable(self, phase: str) -> None:+ self._create()+ if phase == "connection":+ failure = patch(+ "products.data_quality.backend.logic.schedules.async_connect", AsyncMock(side_effect=TimeoutError)+ )+ elif phase == "initial_read":+ failure = patch.object(MetricSchedules, "describe", AsyncMock(side_effect=TimeoutError))+ elif phase == "update":+ failure = patch.object(MetricSchedules, "update", AsyncMock(side_effect=TimeoutError))+ else:+ original_describe = MetricSchedules.describe+ calls = 0++ async def missing_after_update(schedules: MetricSchedules, key: MetricScheduleKey) -> object:+ nonlocal calls+ calls += 1+ if calls == 1:+ return await original_describe(schedules, key)+ return None++ failure = patch.object(MetricSchedules, "describe", cast(AsyncMock, missing_after_update))+ with failure:response = self.client.patch(f"{self.url}/schedule/", {"enabled": False})assert response.status_code == 503- assert self.client.get(f"{self.url}/schedule/").json()["enabled"] is True+ assert self.client.get(f"{self.url}/schedule/").json()["enabled"] is (phase != "read_after")def test_schedule_history_excludes_manual_suites(self) -> None:self._create()@@ -172,7 +226,7 @@ class TestMetricCheckAPI(APIBaseTest):DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.METRIC, subject_uuid=self.metric.id)- schedule = self.client.get(f"{self.url}/schedule/").json()+ schedule = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"}).json()assert schedule["last_suite_run"] == str(scheduled.id)def test_schedule_history_hides_a_suite_with_revoked_reference_access(self) -> None:@@ -204,7 +258,7 @@ class TestMetricCheckAPI(APIBaseTest):access_level="none",)cache.clear()- schedule = self.client.get(f"{self.url}/schedule/").json()+ schedule = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"}).json()assert schedule["last_suite_run"] is Noneassert schedule["last_run_at"] is Nonediff --git a/products/data_quality/backend/tests/test_schedules.py b/products/data_quality/backend/tests/test_schedules.pyindex 8e108b46289f..92ad86c8747c 100644--- a/products/data_quality/backend/tests/test_schedules.py+++ b/products/data_quality/backend/tests/test_schedules.py@@ -1,3 +1,7 @@+import asyncio+from types import SimpleNamespace+from uuid import uuid4+from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, patch@@ -12,7 +16,7 @@ from posthog.models.team import Teamfrom products.data_catalog.backend.facade.api import upsert_metricfrom products.data_quality.backend.facade.enums import SuiteRunTriggerfrom products.data_quality.backend.logic.checks import upsert_check-from products.data_quality.backend.logic.metric_schedules import MetricSchedules+from products.data_quality.backend.logic.metric_schedules import MetricScheduleKey, MetricSchedulesfrom products.data_quality.backend.logic.schedules import (get_schedule,provision_metric_schedule,@@ -22,6 +26,7 @@ from products.data_quality.backend.logic.schedules import (from products.data_quality.backend.models import DataQualityCheckfrom products.data_quality.backend.temporal.activities.prepare_check_suite import prepare_check_suite_activityfrom products.data_quality.backend.temporal.activities.reconcile_schedules import (+ RECONCILE_CONCURRENCY_LIMIT,ScheduleReconcileCursor,_check_page,_dead_schedules,@@ -118,6 +123,9 @@ class TestSchedules(BaseTest):async def _reconcile(self) -> ScheduleReconcileCursor:return await ActivityEnvironment().run(reconcile_metric_schedules_activity, ScheduleReconcileCursor())+ async def _reconcile_checks(self) -> ScheduleReconcileCursor:+ return await ActivityEnvironment().run(reconcile_metric_schedules_activity, ScheduleReconcileCursor())+def test_reconciliation_recovers_missing_schedules_without_overwriting_pauses(self) -> None:self._create()with (@@ -139,6 +147,157 @@ class TestSchedules(BaseTest):assert not schedule.enabledassert schedule.interval == "6hour"+ def test_reconciliation_bounds_overlapping_repairs_and_deduplicates_metric_checks(self) -> None:+ metric_ids = [self.metric.id, self.metric.id, *(uuid4() for _ in range(RECONCILE_CONCURRENCY_LIMIT + 1))]+ checks = [SimpleNamespace(id=uuid4(), team_id=self.team.id, metric_id=metric_id) for metric_id in metric_ids]+ started = asyncio.Event()+ release = asyncio.Event()+ active = 0+ maximum_active = 0++ async def ensure(_key: MetricScheduleKey) -> None:+ nonlocal active, maximum_active+ active += 1+ maximum_active = max(maximum_active, active)+ if active == RECONCILE_CONCURRENCY_LIMIT:+ started.set()+ await release.wait()+ active -= 1++ async def page(_after_check_id: str | None) -> list[SimpleNamespace]:+ return checks++ async def run() -> ScheduleReconcileCursor:+ task = asyncio.create_task(self._reconcile_checks())+ await started.wait()+ assert maximum_active == RECONCILE_CONCURRENCY_LIMIT+ release.set()+ return await task++ with (+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.async_connect",+ AsyncMock(return_value=self.temporal),+ ),+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.database_sync_to_async_pool",+ return_value=page,+ ),+ patch.object(MetricSchedules, "ensure", AsyncMock(side_effect=ensure)) as mocked_ensure,+ ):+ cursor = async_to_sync(run)()++ assert cursor.after_check_id == str(checks[-1].id)+ assert mocked_ensure.await_count == len(set(metric_ids))+ assert maximum_active == RECONCILE_CONCURRENCY_LIMIT++ def test_reconciliation_bounds_overlapping_deletions(self) -> None:+ schedule_ids = [f"data-quality-metric:{self.team.id}:{uuid4()}" for _ in range(RECONCILE_CONCURRENCY_LIMIT + 1)]+ schedule_page = SimpleNamespace(+ current_page=[SimpleNamespace(id=schedule_id) for schedule_id in schedule_ids],+ next_page_token=None,+ fetch_next_page=AsyncMock(),+ )+ self.temporal.list_schedules = AsyncMock(return_value=schedule_page)+ started = asyncio.Event()+ release = asyncio.Event()+ active = 0+ maximum_active = 0++ async def delete(_client: object, _schedule_id: str) -> None:+ nonlocal active, maximum_active+ active += 1+ maximum_active = max(maximum_active, active)+ if active == RECONCILE_CONCURRENCY_LIMIT:+ started.set()+ await release.wait()+ active -= 1++ async def dead(_schedule_ids: list[str]) -> list[str]:+ return schedule_ids++ async def run() -> ScheduleReconcileCursor:+ task = asyncio.create_task(+ ActivityEnvironment().run(+ reconcile_metric_schedules_activity,+ ScheduleReconcileCursor(cleanup=True),+ )+ )+ await started.wait()+ assert maximum_active == RECONCILE_CONCURRENCY_LIMIT+ release.set()+ return await task++ with (+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.async_connect",+ AsyncMock(return_value=self.temporal),+ ),+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.database_sync_to_async_pool",+ return_value=dead,+ ),+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.a_delete_schedule",+ AsyncMock(side_effect=delete),+ ) as mocked_delete,+ ):+ cursor = async_to_sync(run)()++ assert cursor.done+ assert mocked_delete.await_count == len(schedule_ids)+ assert maximum_active == RECONCILE_CONCURRENCY_LIMIT++ def test_reconciliation_cancels_failed_page_tasks_and_retries_the_same_cursor(self) -> None:+ metric_ids = [self.metric.id, uuid4(), uuid4()]+ checks = [SimpleNamespace(id=uuid4(), team_id=self.team.id, metric_id=metric_id) for metric_id in metric_ids]+ blocked_task_started = asyncio.Event()+ blocked_task_canceled = asyncio.Event()+ never_release = asyncio.Event()+ completed: list[MetricScheduleKey] = []++ async def fail_after_partial_completion(key: MetricScheduleKey) -> None:+ if key.metric_id == metric_ids[0]:+ completed.append(key)+ return+ if key.metric_id == metric_ids[1]:+ await blocked_task_started.wait()+ raise RuntimeError("Temporal is unavailable")+ blocked_task_started.set()+ try:+ await never_release.wait()+ except asyncio.CancelledError:+ blocked_task_canceled.set()+ raise++ async def page(_after_check_id: str | None) -> list[SimpleNamespace]:+ return checks++ async def retry(key: MetricScheduleKey) -> None:+ completed.append(key)++ with (+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.async_connect",+ AsyncMock(return_value=self.temporal),+ ),+ patch(+ "products.data_quality.backend.temporal.activities.reconcile_schedules.database_sync_to_async_pool",+ return_value=page,+ ),+ patch.object(+ MetricSchedules, "ensure", AsyncMock(side_effect=fail_after_partial_completion)+ ) as mocked_ensure,+ ):+ with self.assertRaises(ExceptionGroup):+ async_to_sync(self._reconcile_checks)()+ assert blocked_task_canceled.is_set()+ mocked_ensure.side_effect = retry+ cursor = async_to_sync(self._reconcile_checks)()++ assert cursor.after_check_id == str(checks[-1].id)+ assert completed.count(MetricScheduleKey(team_id=self.team.id, metric_id=metric_ids[0])) == 2+async def _prepare_scheduled(self) -> PreparedSuite:return await ActivityEnvironment().run(prepare_check_suite_activity,diff --git a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md b/products/data_quality/skills/authoring-data-quality-checks/SKILL.mdindex 87fcc058a4a1..b010313bb249 100644--- a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md+++ b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md@@ -2,8 +2,9 @@name: authoring-data-quality-checksdescription: >Adds and runs data quality checks (dbt-test style assertions) on a project's warehouse tables and- saved-query views: not-null, uniqueness, accepted values, referential integrity, row-count bounds,- freshness, and custom HogQL. Use when asked to test a model, validate a view, check for nulls or+ saved-query views, and HogQL catalog metrics: not-null, uniqueness, accepted values, referential+ integrity, row-count bounds, freshness, and custom HogQL. Metrics support custom SQL checks only.+ Use when asked to test a model, validate a view, check for nulls orduplicates, add data quality checks, find out why a number looks wrong, or judge whether a warehousetable is trustworthy before using it in an analysis. To describe what data *means* (metrics,certifications, joins), see setting-up-data-catalog instead. Trigger terms: data quality, data test,@@ -13,8 +14,8 @@ description: ># Authoring data quality checks-A check is one assertion about one warehouse table or view. It compiles to a count-only HogQL query-and **passes when it finds zero failing rows** — the same semantics as `dbt test`. Failing rows are+A check is one assertion about one warehouse table, view, or HogQL catalog metric. It compiles to a+count-only HogQL query and **passes when it finds zero failing rows**, like `dbt test`. Failing rows arenever stored; only counts and the compiled query are, so to see the offending rows you re-run thestored query yourself.@@ -45,9 +46,8 @@ WHERE table_name = 'orders'Re-creating a byte-identical check is a harmless no-op — checks are keyed by a fingerprint of thesubject, type, column, and config, so an identical create upserts. A _near_-duplicate is notharmless: it doubles the noise for whoever reads the results. If an existing check's assertion is-close but wrong, create the corrected check and delete the old one — the assertion (type, column,-config) is immutable and the subject is fixed by the URL, so an update that tries to change them is-rejected. Update is only for metadata, severity, and ownership.+close but wrong, edit the existing check. Updates preserve its identity and history; the subject+stays fixed by the URL. An edit that duplicates another check's assertion is rejected.## Choosing checks@@ -73,6 +73,34 @@ Call `posthog:data-quality-check-types` for each type's exact config schema rathChecks live on the subject they audit: create them with `data-quality-check-create-on-view`(`saved_query_id` path parameter) or `data-quality-check-create-on-table` (`table_id`).+## Checks on catalog metrics++Only metrics with a saved `HogQLQuery` definition support checks. Markdown, Trends, Funnels, event+series, and metrics without definitions do not. A metric can return any number of rows and columns.++Create a `custom_sql` check with an empty `column_name`. Include `{metric}` exactly once as a relation:++```sql+SELECT *+FROM {metric}+WHERE orders < 100+```++The check queries the owning metric's current saved output. The example assumes that output has an+`orders` column. Every returned row is a failure; zero rows passes. Query `{metric}` directly or+through a subquery. Metric check SQL cannot define CTEs, including nested CTEs and scalar `WITH`+bindings. CTEs and saved parameters inside the metric definition remain supported. Other placeholders+are not accepted in the check.++Use the metric's Tests tab or the nested REST endpoints under+`/api/projects/{project_id}/data_catalog/metrics/{metric_id}/checks/`. The catalog metric detail+endpoint uses the metric name, but nested check endpoints use its UUID. The metric check-type+endpoint offers only Custom SQL. Do not assume the table/view MCP tools accept metric subjects.++Saving validates SQL composition without executing it. Run the check to verify column names and+results. Every run reloads the saved metric: if an edit removes a column used by the check, the next+run errors. Fix the check SQL or restore the expected metric output.+## Severity and triggers**Severity** is a decision about consequences, not about confidence. Use `error` when the failure@@ -80,12 +108,22 @@ means downstream numbers should not be trusted — those failures mark the subjenotify. Use `warn` for things worth surfacing that nobody would act on today. When unsure, `warn` isthe safer default: an `error` check that cries wolf gets everything ignored.-**Triggers** — there is nothing to schedule. A check runs when its subject's data changes: a+**Table and view triggers:** A check runs when its subject's data changes: amaterialized view's checks run as part of its refresh (and, when the team turns the gate on, arefresh whose error-severity checks fail is not published), a source table's checks run after eachcompleted sync, and a plain view's checks run when its DAG runs. Checks on a view outside any DAGonly run on demand.+**Metric schedules:** The first saved check creates an enabled daily schedule for all checks on the+metric. The Tests tab lets you change the interval or turn automatic runs off. Manual runs remain+available. Scheduled checks use the latest definition author's access, falling back to the creator;+manual runs use the initiating user's access. Underlying and additional tables must be readable.++Temporal owns each metric's cadence and pause state. Paused schedules have no next execution time.+Reload after an unavailable schedule response before retrying an edit; the edit may have succeeded.+Automatic runs skip overlaps and catch up missed occurrences only within 15 minutes.+Disabling or deleting every check preserves the schedule preferences. Deleting the metric removes its schedule.+## Verify what you wroteAuthor, run once, read the result. A check nobody has run is a guess.@@ -119,8 +157,9 @@ FROM system.information_schema.data_quality_health- `unknown` / absent — no checks, or none have run. Absence of failures is not evidence of health.For the history behind a verdict, `system.information_schema.data_quality_check_runs` carries recent-executions with `observed_value` recorded on passes too, so you can see when a number started-drifting rather than just that it is wrong now.+executions with status, failing-row count, and errors. For metric checks, the failing-row count+describes the assertion result, not a scalar metric value. Open the failing-row query from the+Tests tab to inspect the current rows that violate the check.## Related