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-quality): schedule metric SQL checks (#96582)

Thiago Salvatore7ba90f42c8fe
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.md
index 7a069af4ae0d..b2d7a7a887ff 100644
--- a/docs/internal/data-quality-checks.md
+++ b/docs/internal/data-quality-checks.md
@@ -47,3 +47,13 @@ The overview filters readable subject identities in SQL before scanning definiti
Notification recipient checks retain the existing global warehouse-resource policy. A specific object grant alone does not expand notification delivery eligibility. A subject that no longer resolves sends no notification. Background dependency pinning still resolves references individually; batching that cross-product workflow is separate work.
Catalog access is a project permission resource. Notification visibility follows that permission, including after access is revoked.
+
+## Metric schedules
+
+Each metric with checks has one Temporal Schedule in its canonical project. The first check creates an enabled daily schedule after the check transaction commits and starts an initial run. Available intervals are one hour, six hours, twelve hours, one day, and one week. A deterministic offset spreads recurring executions across each interval.
+
+Temporal owns the interval, pause state, and next execution time. The schedule endpoint reads and updates Temporal directly. Paused schedules return `next_run_at: null`. An unavailable schedule service returns HTTP 503; reload the schedule before retrying an update whose outcome is unknown. Last scheduled run information comes from the caller's readable suite history. Manual runs do not change it.
+
+Scheduled 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.
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e681f589c7ae..28fed3eafb23 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6145,6 +6145,7 @@ export type PromptFlag = {
// Should be kept in sync with "posthog/models/activity_logging/activity_log.py"
export enum ActivityScope {
+ DATA_QUALITY_CHECK_SCHEDULE = 'DataQualityCheckSchedule',
ACTION = 'Action',
ALERT_CONFIGURATION = 'AlertConfiguration',
ANNOTATION = 'Annotation',
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 93f748c35d14..a7c430f0ca14 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -111,6 +111,7 @@ ActivityScope = Literal[
"Metric",
"TableCertification",
"DataQualityCheck",
+ "DataQualityCheckSchedule",
"Billing",
"Loop",
"StamphogRepoConfig",
@@ -400,6 +401,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
# Fields that prevent activity signal triggering entirely when only these fields change
signal_exclusions: dict[ActivityScope, list[str]] = {
+ "DataQualityCheckSchedule": ["next_run_at", "last_run_at", "last_suite_run", "updated_at"],
"AlertConfiguration": [
"last_checked_at",
"next_check_at",
@@ -521,6 +523,7 @@ activity_visibility_restrictions: list[dict[str, Any]] = [
]
field_exclusions: dict[AuditableScope, list[str]] = {
+ "DataQualityCheckSchedule": ["subject_type", "subject_uuid", "next_run_at", "last_run_at", "last_suite_run"],
"StamphogRepoConfig": [
# Reverse relation to the repo's review history. The diff would read every pull request row
# on each settings toggle, and none of it is configuration.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 54ff96e6891f..4f97dea3a0d6 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -696,6 +696,7 @@ SPECTACULAR_SETTINGS = {
],
"TileSpacingEnum": ["tight", "condensed", "standard", "relaxed", "wide"],
"DataQualityCheckSeverityEnum": ["error", "warn"],
+ "DataQualityScheduleIntervalEnum": "products.data_quality.backend.facade.enums.schedule_interval_choices",
"CanvasStateScopeEnum": ["user", "shared"],
"CanvasKindEnum": ["freeform", "grid", "component"],
"CanvasPlacementStatusEnum": ["pending", "generating", "live", "failed"],
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index cd8af3c413b2..210b1a670bc1 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -88,7 +88,10 @@ from products.customer_analytics.backend.facade.temporal import (
create_account_track_rule_coordinator_schedule,
create_calendar_sync_coordinator_schedule,
)
-from products.data_quality.backend.facade.temporal import create_cleanup_data_quality_check_runs_schedule
+from products.data_quality.backend.facade.temporal import (
+ create_cleanup_data_quality_check_runs_schedule,
+ create_reconcile_metric_schedules_schedule,
+)
from products.engineering_analytics.backend.facade.temporal import (
create_ci_signals_coordinator_schedule,
create_github_job_logs_coordinator_schedule,
@@ -946,6 +949,7 @@ schedules = [
create_review_hog_finding_outcomes_schedule,
create_ci_signals_coordinator_schedule,
create_cleanup_data_quality_check_runs_schedule,
+ create_reconcile_metric_schedules_schedule,
]
# AI observability summarization and clustering call the cloud-only guard in
diff --git a/products/data_quality/backend/activity_logging.py b/products/data_quality/backend/activity_logging.py
index 5081b7d52718..8e67ba30af64 100644
--- a/products/data_quality/backend/activity_logging.py
+++ b/products/data_quality/backend/activity_logging.py
@@ -4,14 +4,18 @@
trail (create, config change, soft delete). Registered from ``apps.ready()``.
"""
-from typing import Any, Optional, cast
+from typing import TYPE_CHECKING, Any, Optional, cast
from posthog.models import User
-from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity
+from posthog.models.activity_logging.activity_log import AuditableScope, Change, Detail, changes_between, log_activity
+from posthog.models.activity_logging.model_activity import get_was_impersonated
from posthog.models.signals import model_activity_signal, mutable_receiver
from .models import DataQualityCheck
+if TYPE_CHECKING:
+ from .logic.schedules import MetricCheckSchedule
+
@mutable_receiver(model_activity_signal, sender=DataQualityCheck)
def handle_data_quality_check_activity(
@@ -40,3 +44,38 @@ def handle_data_quality_check_activity(
changes=changes_between(cast(AuditableScope, scope), previous=before_update, current=after_update),
),
)
+
+
+def log_metric_schedule_change(
+ team_id: int,
+ metric_id: str,
+ before: "MetricCheckSchedule",
+ after: "MetricCheckSchedule",
+ user: User,
+) -> None:
+ from .logic.subjects import resolve_subject # noqa: PLC0415 — avoids loading the catalog during Django startup
+
+ changes = [
+ Change(
+ type="DataQualityCheckSchedule",
+ field=field,
+ action="changed",
+ before=getattr(before, field),
+ after=getattr(after, field),
+ )
+ for field in ("interval", "enabled")
+ if getattr(before, field) != getattr(after, field)
+ ]
+ if not changes:
+ return
+ subject = resolve_subject(team_id, "metric", metric_id)
+ log_activity(
+ organization_id=None,
+ team_id=team_id,
+ user=user,
+ was_impersonated=get_was_impersonated(),
+ item_id=str(after.id),
+ scope="DataQualityCheckSchedule",
+ activity="updated",
+ detail=Detail(name=f"metric check schedule on {subject.name or metric_id}", changes=changes),
+ )
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index 5d76b28d2703..bdcd2db9ba1f 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -7,6 +7,7 @@ the AST-bearing ``CheckPlan`` stay inside ``logic``, since they are compiler int
data. ORM model classes never cross here either -- ``facade/models.py`` is their one channel.
"""
+from ..activity_logging import log_metric_schedule_change
from ..logic.checks import (
checks_for_subject,
edit_check,
@@ -29,6 +30,7 @@ from ..logic.notifications import notify_materialization_blocked
from ..logic.permissions import authorized_subject_types, restrict_subject_types, writable_subjects
from ..logic.registry import UnknownCheckTypeError, list_check_types
from ..logic.run_records import record_check_run
+from ..logic.schedules import MetricCheckSchedule, ScheduleUnavailableError, get_schedule, set_schedule
from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
from ..logic.subject_access import (
DenialContext,
@@ -51,6 +53,9 @@ from ..logic.triggers import materialization_audit_mode as quality_audit_mode
from .contracts import CheckTypeInfo
__all__ = [
+ "log_metric_schedule_change",
+ "MetricCheckSchedule",
+ "ScheduleUnavailableError",
"CheckConfigError",
"CheckEditConflict",
"CheckStatusRow",
@@ -82,6 +87,7 @@ __all__ = [
"ensure_name_available",
"from_config_entry",
"get_gate_config",
+ "get_schedule",
"list_check_types",
"notify_materialization_blocked",
"quality_audit_mode",
@@ -91,6 +97,7 @@ __all__ = [
"resolve_metric_subjects",
"roll_up_health",
"set_gate_materialization_on_checks",
+ "set_schedule",
"soft_delete_check",
"start_check_suite",
"subject_health",
diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.py
index 4023c5f651f7..afd38931d65a 100644
--- a/products/data_quality/backend/facade/contracts.py
+++ b/products/data_quality/backend/facade/contracts.py
@@ -7,8 +7,11 @@ Frozen, framework-free values other products need. No Django imports.
from dataclasses import dataclass, field
from typing import Any, Literal, TypeGuard
+from posthog.dataclasses import frozen
+
+from .enums import SuiteRunTrigger
+
CHECK_SUITE_WORKFLOW_NAME = "data-quality-run-suite"
-DISPATCH_SCHEDULED_SUITES_WORKFLOW_NAME = "data-quality-dispatch-scheduled-suites"
MATERIALIZATION_GATE_ACTIVITY_NAME = "data-quality-materialization-gate"
@@ -36,3 +39,27 @@ class CheckTypeInfo:
description: str
requires_column: bool
config_schema: dict[str, Any] = field(default_factory=dict)
+
+
+@frozen
+class RunCheckSuiteInputs:
+ """What to run. Exactly one selector is expected; a suite with no matching checks is not an error.
+
+ ``node_ids`` is the materialization path: the DAG workflow knows nodes, not saved queries, and
+ the mapping is resolved inside the prepare activity so the workflow stays deterministic.
+ ``table_ids`` is the source-sync path, keyed on the table so it works with or without a DAG.
+ """
+
+ team_id: int
+ trigger: SuiteRunTrigger
+ saved_query_ids: list[str] = field(default_factory=list)
+ table_ids: list[str] = field(default_factory=list)
+ metric_ids: list[str] = field(default_factory=list)
+ check_ids: list[str] = field(default_factory=list)
+ node_ids: list[str] = field(default_factory=list)
+ suite_run_id: str | None = None
+ schedule_id: str | None = None
+ data_modeling_job_id: str | None = None
+ created_by_id: int | None = None
+ # Audits the staged folder rather than the published table. Needs exactly one saved query.
+ staged_queryable_folder: str | None = None
diff --git a/products/data_quality/backend/facade/enums.py b/products/data_quality/backend/facade/enums.py
index 11ca8060d2c0..af07d8cc5574 100644
--- a/products/data_quality/backend/facade/enums.py
+++ b/products/data_quality/backend/facade/enums.py
@@ -85,6 +85,18 @@ class SubjectType(StrEnum):
METRIC = "metric"
+class ScheduleInterval(StrEnum):
+ ONE_HOUR = "1hour"
+ SIX_HOURS = "6hour"
+ TWELVE_HOURS = "12hour"
+ DAILY = "24hour"
+ WEEKLY = "7day"
+
+
+def schedule_interval_choices() -> list[str]:
+ return [interval.value for interval in ScheduleInterval]
+
+
def subject_type_choices() -> dict[str, str]:
return {kind.value: kind.value for kind in SubjectType}
diff --git a/products/data_quality/backend/facade/temporal.py b/products/data_quality/backend/facade/temporal.py
index 5faea27ef280..95f8bb91e2bd 100644
--- a/products/data_quality/backend/facade/temporal.py
+++ b/products/data_quality/backend/facade/temporal.py
@@ -11,5 +11,6 @@ from ..temporal import (
from ..temporal.contracts import RunCheckSuiteInputs as RunCheckSuiteInputs
from ..temporal.schedule import (
create_cleanup_data_quality_check_runs_schedule as create_cleanup_data_quality_check_runs_schedule,
+ create_reconcile_metric_schedules_schedule as create_reconcile_metric_schedules_schedule,
)
from .contracts import CHECK_SUITE_WORKFLOW_NAME as CHECK_SUITE_WORKFLOW_NAME
diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.py
index 06e4f3c3148f..e1c961eb37aa 100644
--- a/products/data_quality/backend/logic/checks.py
+++ b/products/data_quality/backend/logic/checks.py
@@ -9,6 +9,7 @@ import asyncio
from collections.abc import Callable, Iterable
from dataclasses import asdict
from datetime import UTC, datetime
+from functools import partial
from operator import attrgetter
from typing import Any
from uuid import UUID, uuid4
@@ -38,6 +39,7 @@ from .errors import (
from .exceptions import CheckNameConflict
from .health import CheckStatusRow, roll_up_health
from .registry import get_spec
+from .schedules import provision_metric_schedule
from .serialization import compute_fingerprint
from .spec import CheckConfig
from .subjects import resolve_subject, subject_column_type
@@ -164,6 +166,8 @@ def upsert_check(
**_subject_fk(subject_type, subject_uuid),
**fields,
)
+ if check.subject_type == SubjectType.METRIC and check.metric_id:
+ transaction.on_commit(partial(provision_metric_schedule, check.team_id, str(check.metric_id)))
return check, True
except IntegrityError:
# Check-then-insert race: a concurrent identical request inserted this fingerprint between
diff --git a/products/data_quality/backend/logic/flags.py b/products/data_quality/backend/logic/flags.py
index f3f9b60adc53..fa526c4634d7 100644
--- a/products/data_quality/backend/logic/flags.py
+++ b/products/data_quality/backend/logic/flags.py
@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING
from django.conf import settings
-from posthog.ph_client import feature_enabled_or_false
+import posthoganalytics
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -13,11 +13,15 @@ DATA_QUALITY_CHECKS_FEATURE_FLAG = "data-quality-checks"
def is_data_quality_checks_enabled(team: "Team") -> bool:
"""The `data-quality-checks` flag check, org-keyed. Canonical home for the check -- gate any
data-quality surface (API, information_schema tables, MCP tools, triggers) through here."""
+ return _get_data_quality_checks_flag(team) is True
+
+
+def _get_data_quality_checks_flag(team: "Team") -> bool | None:
# The flag is evaluated against PostHog's own analytics project, which a local or end-to-end
# environment has no membership in, so it would gate the whole product out of both.
if settings.DEBUG or settings.E2E_TESTING:
return True
- return feature_enabled_or_false(
+ return posthoganalytics.feature_enabled(
DATA_QUALITY_CHECKS_FEATURE_FLAG,
str(team.organization_id),
groups={"organization": str(team.organization_id)},
@@ -28,9 +32,13 @@ def is_data_quality_checks_enabled(team: "Team") -> bool:
def is_data_quality_checks_enabled_for_team_id(team_id: int) -> bool:
"""Flag check for callers that only hold a team id (trigger gates, activities)."""
+ return get_data_quality_checks_flag_for_team_id(team_id) is True
+
+
+def get_data_quality_checks_flag_for_team_id(team_id: int) -> bool | None:
from posthog.models.team import Team # noqa: PLC0415 — the app registry is not ready at import time
team = Team.objects.filter(id=team_id).only("id", "organization_id").first()
if team is None:
return False
- return is_data_quality_checks_enabled(team)
+ return _get_data_quality_checks_flag(team)
diff --git a/products/data_quality/backend/logic/metric_schedules.py b/products/data_quality/backend/logic/metric_schedules.py
new file mode 100644
index 000000000000..7b672ce61b88
--- /dev/null
+++ b/products/data_quality/backend/logic/metric_schedules.py
@@ -0,0 +1,141 @@
+from copy import deepcopy
+from datetime import timedelta
+from uuid import NAMESPACE_URL, UUID, uuid5
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleAlreadyRunningError,
+ ScheduleDescription,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+ ScheduleUpdate,
+ ScheduleUpdateInput,
+)
+from temporalio.common import SearchAttributePair, TypedSearchAttributes
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.schedule import a_create_schedule, a_describe_schedule
+from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY, POSTHOG_TEAM_ID_KEY
+
+from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME, RunCheckSuiteInputs
+from ..facade.enums import ScheduleInterval, SuiteRunTrigger
+
+SCHEDULE_TYPE = "data-quality-metric"
+SCHEDULE_PREFIX = f"{SCHEDULE_TYPE}:"
+CATCHUP_WINDOW = timedelta(minutes=15)
+INTERVALS = {
+ ScheduleInterval.ONE_HOUR: timedelta(hours=1),
+ ScheduleInterval.SIX_HOURS: timedelta(hours=6),
+ ScheduleInterval.TWELVE_HOURS: timedelta(hours=12),
+ ScheduleInterval.DAILY: timedelta(days=1),
+ ScheduleInterval.WEEKLY: timedelta(days=7),
+}
+
+
+@frozen
+class MetricScheduleKey:
+ team_id: int
+ metric_id: UUID
+
+ @property
+ def id(self) -> UUID:
+ return uuid5(NAMESPACE_URL, f"{SCHEDULE_PREFIX}{self.team_id}:{self.metric_id}")
+
+ @property
+ def temporal_id(self) -> str:
+ return f"{SCHEDULE_PREFIX}{self.team_id}:{self.metric_id}"
+
+ @classmethod
+ def parse(cls, schedule_id: str) -> "MetricScheduleKey":
+ prefix, team_id, metric_id = schedule_id.split(":")
+ if prefix != SCHEDULE_TYPE:
+ raise ValueError("Unrecognized metric schedule identifier")
+ return cls(team_id=int(team_id), metric_id=UUID(metric_id))
+
+
+def interval_from_label(label: str) -> timedelta:
+ return INTERVALS[ScheduleInterval(label)]
+
+
+def label_from_interval(interval: timedelta) -> ScheduleInterval:
+ for label, duration in INTERVALS.items():
+ if interval == duration:
+ return label
+ raise ValueError("Unsupported metric check interval")
+
+
+class MetricSchedules:
+ def __init__(self, client: Client) -> None:
+ self.client = client
+
+ @staticmethod
+ def spec(key: MetricScheduleKey, interval: str) -> ScheduleSpec:
+ duration = interval_from_label(interval)
+ offset = timedelta(seconds=key.id.int % int(duration.total_seconds()))
+ return ScheduleSpec(intervals=[ScheduleIntervalSpec(every=duration, offset=offset)])
+
+ @classmethod
+ def build(cls, key: MetricScheduleKey, interval: str = ScheduleInterval.DAILY) -> Schedule:
+ return Schedule(
+ action=ScheduleActionStartWorkflow(
+ CHECK_SUITE_WORKFLOW_NAME,
+ RunCheckSuiteInputs(
+ team_id=key.team_id,
+ trigger=SuiteRunTrigger.SCHEDULED,
+ metric_ids=[str(key.metric_id)],
+ schedule_id=key.temporal_id,
+ ),
+ id=key.temporal_id,
+ task_queue=settings.DATA_MODELING_TASK_QUEUE,
+ execution_timeout=timedelta(hours=1),
+ ),
+ spec=cls.spec(key, interval),
+ policy=SchedulePolicy(
+ overlap=ScheduleOverlapPolicy.SKIP, catchup_window=CATCHUP_WINDOW, pause_on_failure=False
+ ),
+ )
+
+ async def ensure(self, key: MetricScheduleKey) -> None:
+ try:
+ await a_create_schedule(
+ self.client,
+ id=key.temporal_id,
+ schedule=self.build(key),
+ trigger_immediately=True,
+ search_attributes=TypedSearchAttributes(
+ [
+ SearchAttributePair(POSTHOG_TEAM_ID_KEY, key.team_id),
+ SearchAttributePair(POSTHOG_SCHEDULE_TYPE_KEY, SCHEDULE_TYPE),
+ ]
+ ),
+ )
+ except ScheduleAlreadyRunningError:
+ return
+
+ async def describe(self, key: MetricScheduleKey) -> ScheduleDescription | None:
+ try:
+ return await a_describe_schedule(self.client, key.temporal_id)
+ except RPCError as error:
+ if error.status == RPCStatusCode.NOT_FOUND:
+ return None
+ raise
+
+ async def update(self, key: MetricScheduleKey, *, interval: str | None = None, enabled: bool | None = None) -> None:
+ spec = self.spec(key, interval) if interval is not None else None
+
+ def updater(inputs: ScheduleUpdateInput) -> ScheduleUpdate:
+ schedule = deepcopy(inputs.description.schedule)
+ if spec is not None:
+ schedule.spec.intervals = spec.intervals
+ if enabled is not None:
+ schedule.state.paused = not enabled
+ return ScheduleUpdate(schedule=schedule)
+
+ await self.client.get_schedule_handle(key.temporal_id).update(updater)
diff --git a/products/data_quality/backend/logic/schedules.py b/products/data_quality/backend/logic/schedules.py
new file mode 100644
index 000000000000..4a222473cb62
--- /dev/null
+++ b/products/data_quality/backend/logic/schedules.py
@@ -0,0 +1,84 @@
+import asyncio
+from datetime import datetime
+from uuid import UUID
+
+import structlog
+from asgiref.sync import async_to_sync, sync_to_async
+
+from posthog.dataclasses import frozen
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.temporal.common.client import async_connect
+
+from ..facade.enums import ScheduleInterval, SubjectType
+from .metric_schedules import MetricScheduleKey, MetricSchedules, label_from_interval
+
+logger = structlog.get_logger(__name__)
+SCHEDULE_REQUEST_TIMEOUT_SECONDS = 10
+
+
+class ScheduleUnavailableError(Exception):
+ pass
+
+
+@frozen
+class MetricCheckSchedule:
+ id: UUID
+ interval: ScheduleInterval
+ enabled: bool
+ next_run_at: datetime | None
+ last_run_at: datetime | None = None
+ last_suite_run: UUID | None = None
+
+
+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)))
+
+
+@async_to_sync
+async def provision_metric_schedule(team_id: int, metric_id: str) -> None:
+ key = await sync_to_async(schedule_key)(team_id, SubjectType.METRIC, metric_id)
+ try:
+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):
+ await MetricSchedules(await async_connect()).ensure(key)
+ except Exception:
+ logger.exception("data_quality_schedule_provision_failed", team_id=key.team_id, metric_id=str(key.metric_id))
+
+
+@async_to_sync
+async def get_schedule(team_id: int, subject_type: str, subject_uuid: str | UUID) -> MetricCheckSchedule | None:
+ key = await sync_to_async(schedule_key)(team_id, subject_type, subject_uuid)
+ try:
+ 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,
+ )
+ except Exception as error:
+ raise ScheduleUnavailableError() from error
+
+
+@async_to_sync
+async def set_schedule(
+ team_id: int,
+ subject_type: str,
+ subject_uuid: str | UUID,
+ *,
+ interval: str | None = None,
+ enabled: bool | None = None,
+) -> None:
+ key = await sync_to_async(schedule_key)(team_id, subject_type, subject_uuid)
+ try:
+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):
+ await MetricSchedules(await async_connect()).update(key, interval=interval, enabled=enabled)
+ except Exception as error:
+ raise ScheduleUnavailableError() from error
diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.py
index 85f69ee775fe..b2b2332851c5 100644
--- a/products/data_quality/backend/presentation/serializers.py
+++ b/products/data_quality/backend/presentation/serializers.py
@@ -14,7 +14,7 @@ from rest_framework.settings import api_settings
from posthog.api.shared import UserBasicSerializer
from ..facade import api
-from ..facade.enums import CheckSeverity, CheckType, CreatedSource, SubjectType
+from ..facade.enums import CheckSeverity, CheckType, CreatedSource, ScheduleInterval, SubjectType
from ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
@@ -250,6 +250,30 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):
return self._location(obj).metric_name
+class DataQualityCheckScheduleUpdateSerializer(serializers.Serializer):
+ interval = serializers.ChoiceField(
+ choices=list(ScheduleInterval), required=False, help_text="How often all enabled checks on the metric run."
+ )
+ enabled = serializers.BooleanField(required=False, help_text="Whether checks run automatically on this schedule.")
+
+
+class DataQualityCheckScheduleSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Schedule identifier.")
+ interval = serializers.ChoiceField(
+ choices=list(ScheduleInterval), read_only=True, help_text="How often the checks run."
+ )
+ enabled = serializers.BooleanField(read_only=True, help_text="Whether the schedule runs automatically.")
+ next_run_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="Next scheduled execution time, if enabled."
+ )
+ last_run_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="Most recent visible scheduled suite execution time."
+ )
+ last_suite_run = serializers.UUIDField(
+ read_only=True, allow_null=True, help_text="Most recent visible scheduled suite."
+ )
+
+
@extend_schema_serializer(component_name="DataQualityCheckRun")
class DataQualityCheckRunSerializer(serializers.ModelSerializer):
status = serializers.CharField(read_only=True, help_text="passed, failed, errored, or skipped.")
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index ab2ad1442623..e96a519b8cb1 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -9,6 +9,7 @@ a suite-run handle to poll.
from collections import defaultdict
from collections.abc import Callable, Sequence
+from dataclasses import replace
from functools import cached_property
from typing import TYPE_CHECKING, ClassVar, cast
from uuid import UUID
@@ -19,7 +20,7 @@ from django.shortcuts import get_object_or_404
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
from rest_framework import mixins, status, viewsets
-from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.exceptions import APIException, NotFound, PermissionDenied
from rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -35,12 +36,14 @@ from posthog.permissions import APIScopePermission, TeamMemberAccessPermission,
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
from ..facade import api
-from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType
+from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType, SuiteRunTrigger
from ..facade.flags import is_data_quality_checks_enabled
from ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
from .serializers import (
CheckTypeSerializer,
DataQualityCheckRunSerializer,
+ DataQualityCheckScheduleSerializer,
+ DataQualityCheckScheduleUpdateSerializer,
DataQualityCheckSerializer,
DataQualityGateConfigSerializer,
DataQualityOverviewCheckSerializer,
@@ -572,10 +575,67 @@ class TableCheckViewSet(_BaseCheckViewSet, AccessControlViewSetMixin):
subject_field = "table"
+class ScheduleUnavailableAPIError(APIException):
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_code = "schedule_unavailable"
+ default_detail = "Could not read or update the check schedule. Reload it and try again."
+
+
class MetricCheckViewSet(_BaseCheckViewSet):
scope_object = "data_catalog"
subject_type = SubjectType.METRIC
subject_field = "metric"
+ QUERY_GATED_ACTIONS = _BaseCheckViewSet.QUERY_GATED_ACTIONS | {"schedule"}
+
+ @extend_schema(methods=["GET"], request=None, responses={200: DataQualityCheckScheduleSerializer})
+ @extend_schema(
+ methods=["PATCH"],
+ request=DataQualityCheckScheduleUpdateSerializer,
+ responses={200: DataQualityCheckScheduleSerializer},
+ )
+ @action(methods=["GET", "PATCH"], detail=False, pagination_class=None)
+ def schedule(self, request: Request, **kwargs) -> Response:
+ if not self._subject_checks().exists():
+ raise NotFound("Add a check to create this metric's schedule.")
+ if request.method == "PATCH":
+ self._require_enabled_check_access()
+ serializer = DataQualityCheckScheduleUpdateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ 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
+ )
+ 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)
+
+ 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(
diff --git a/products/data_quality/backend/temporal/__init__.py b/products/data_quality/backend/temporal/__init__.py
index f854c12f7847..5d38deb0664c 100644
--- a/products/data_quality/backend/temporal/__init__.py
+++ b/products/data_quality/backend/temporal/__init__.py
@@ -13,13 +13,16 @@ from .activities.finalize_check_suite import (
)
from .activities.materialization_gate import materialization_gate_activity
from .activities.prepare_check_suite import prepare_check_suite_activity
+from .activities.reconcile_schedules import reconcile_metric_schedules_activity
from .activities.run_check_batch import run_check_batch_activity
from .workflows.cleanup import CleanupCheckRunsWorkflow
+from .workflows.reconcile_schedules import ReconcileMetricSchedulesWorkflow
from .workflows.run_check_suite import RunCheckSuiteWorkflow
WORKFLOWS: list[type[PostHogWorkflow]] = [
RunCheckSuiteWorkflow,
CleanupCheckRunsWorkflow,
+ ReconcileMetricSchedulesWorkflow,
]
ACTIVITIES: list[Callable[..., Any]] = [
@@ -30,6 +33,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
mark_check_suite_empty_activity,
mark_check_suite_failed_activity,
cleanup_check_runs_activity,
+ reconcile_metric_schedules_activity,
]
__all__ = ["ACTIVITIES", "WORKFLOWS"]
diff --git a/products/data_quality/backend/temporal/activities/prepare_check_suite.py b/products/data_quality/backend/temporal/activities/prepare_check_suite.py
index 4406832c83c8..89e2bc0a1aa0 100644
--- a/products/data_quality/backend/temporal/activities/prepare_check_suite.py
+++ b/products/data_quality/backend/temporal/activities/prepare_check_suite.py
@@ -5,13 +5,15 @@ from django.db import models
from asgiref.sync import sync_to_async
from temporalio import activity
+from posthog.temporal.common.client import async_connect
from posthog.temporal.common.logger import get_logger
from products.data_modeling.backend.facade import api as data_modeling_facade
-from ...facade.enums import SubjectType
+from ...facade.enums import SubjectType, SuiteRunTrigger
from ...logic.checks import live_subject_checks
-from ...logic.flags import is_data_quality_checks_enabled_for_team_id
+from ...logic.flags import get_data_quality_checks_flag_for_team_id
+from ...logic.metric_schedules import MetricScheduleKey, MetricSchedules
from ...models import DataQualityCheck, DataQualitySuiteRun
from ..contracts import PreparedSuite, RunCheckSuiteInputs
@@ -22,11 +24,20 @@ CHECKS_PER_BATCH = 25
@activity.defn
async def prepare_check_suite_activity(inputs: RunCheckSuiteInputs) -> PreparedSuite:
- return await sync_to_async(_prepare)(inputs)
-
-
-def _prepare(inputs: RunCheckSuiteInputs) -> PreparedSuite:
- checks = _select_checks(inputs) if is_data_quality_checks_enabled_for_team_id(inputs.team_id) else []
+ schedule_enabled = True
+ if inputs.trigger == SuiteRunTrigger.SCHEDULED:
+ if not inputs.schedule_id:
+ raise ValueError("Scheduled suites require a schedule identifier")
+ key = MetricScheduleKey.parse(inputs.schedule_id)
+ if key.team_id != inputs.team_id or inputs.metric_ids != [str(key.metric_id)]:
+ raise ValueError("Schedule subject does not match suite inputs")
+ schedule = await MetricSchedules(await async_connect()).describe(key)
+ schedule_enabled = schedule is not None and not schedule.schedule.state.paused
+ return await sync_to_async(_prepare)(inputs, schedule_enabled=schedule_enabled)
+
+
+def _prepare(inputs: RunCheckSuiteInputs, *, schedule_enabled: bool = True) -> PreparedSuite:
+ checks = _select_checks(inputs) if _checks_enabled(inputs.team_id) and schedule_enabled else []
suite_run = _suite_run(inputs)
check_ids = [str(check_id) for check_id in checks]
@@ -35,6 +46,19 @@ def _prepare(inputs: RunCheckSuiteInputs) -> PreparedSuite:
return PreparedSuite(suite_run_id=str(suite_run.id), batches=batches)
+def _checks_enabled(team_id: int) -> bool:
+ """Fail on a flag the lookup could not read, rather than read it as off.
+
+ An off flag is a kill switch and must still stop the suite. An unreadable flag is a transient
+ fault, and treating it as off would consume a scheduled occurrence, stamp a run that validated
+ nothing, and report success. Raising lets the activity retry.
+ """
+ enabled = get_data_quality_checks_flag_for_team_id(team_id)
+ if enabled is None:
+ raise RuntimeError(f"Could not read the data quality checks flag for team {team_id}.")
+ return enabled
+
+
def _suite_run(inputs: RunCheckSuiteInputs) -> DataQualitySuiteRun:
"""Adopt the row the API already created, or make one for a trigger that had nobody to hand it to.
diff --git a/products/data_quality/backend/temporal/activities/reconcile_schedules.py b/products/data_quality/backend/temporal/activities/reconcile_schedules.py
new file mode 100644
index 000000000000..84575e0b5a97
--- /dev/null
+++ b/products/data_quality/backend/temporal/activities/reconcile_schedules.py
@@ -0,0 +1,82 @@
+from collections import defaultdict
+
+from temporalio import activity
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.dataclasses import frozen
+from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.schedule import a_delete_schedule
+from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
+
+from products.data_catalog.backend.facade import api as data_catalog_facade
+
+from ...facade.enums import SubjectType
+from ...logic.metric_schedules import SCHEDULE_PREFIX, SCHEDULE_TYPE, MetricScheduleKey, MetricSchedules
+from ...models import DataQualityCheck
+
+RECONCILE_PAGE_SIZE = 100
+
+
+@frozen
+class ScheduleReconcileCursor:
+ after_check_id: str | None = None
+ cleanup: bool = False
+ next_page_token: bytes | None = None
+ done: bool = False
+
+
+def _check_page(after_check_id: str | None) -> list[DataQualityCheck]:
+ checks = DataQualityCheck.objects.unscoped().filter(subject_type=SubjectType.METRIC, metric__deleted=False)
+ if after_check_id:
+ checks = checks.filter(id__gt=after_check_id)
+ return list(checks.only("id", "team_id", "metric_id").order_by("id")[:RECONCILE_PAGE_SIZE])
+
+
+def _dead_schedules(schedule_ids: list[str]) -> list[str]:
+ by_team: dict[int, list[MetricScheduleKey]] = defaultdict(list)
+ for schedule_id in schedule_ids:
+ if schedule_id.startswith(SCHEDULE_PREFIX):
+ key = MetricScheduleKey.parse(schedule_id)
+ by_team[key.team_id].append(key)
+ dead: list[str] = []
+ for team_id, keys in by_team.items():
+ live = data_catalog_facade.metric_names_for_ids(team_id, [key.metric_id for key in keys])
+ dead.extend(key.temporal_id for key in keys if key.metric_id not in live)
+ return dead
+
+
+async def reconcile_metric_schedules_activity(cursor: ScheduleReconcileCursor) -> ScheduleReconcileCursor:
+ client = await async_connect()
+ 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()
+ return ScheduleReconcileCursor(
+ after_check_id=str(checks[-1].id) if checks else None,
+ cleanup=len(checks) < RECONCILE_PAGE_SIZE,
+ )
+
+ schedules = 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 []]
+ dead = await database_sync_to_async_pool(_dead_schedules)(schedule_ids)
+ for schedule_id in dead:
+ try:
+ await a_delete_schedule(client, schedule_id)
+ except RPCError as error:
+ if error.status != RPCStatusCode.NOT_FOUND:
+ raise
+ activity.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/temporal/contracts.py b/products/data_quality/backend/temporal/contracts.py
index e0ef1c1236d0..7d84773491f0 100644
--- a/products/data_quality/backend/temporal/contracts.py
+++ b/products/data_quality/backend/temporal/contracts.py
@@ -8,30 +8,8 @@ import dataclasses
from posthog.dataclasses import frozen
-from ..facade.enums import SuiteRunStatus, SuiteRunTrigger
-
-
-@frozen
-class RunCheckSuiteInputs:
- """What to run. Exactly one selector is expected; a suite with no matching checks is not an error.
-
- ``node_ids`` is the materialization path: the DAG workflow knows nodes, not saved queries, and
- the mapping is resolved inside the prepare activity so the workflow stays deterministic.
- ``table_ids`` is the source-sync path, keyed on the table so it works with or without a DAG.
- """
-
- team_id: int
- trigger: SuiteRunTrigger
- saved_query_ids: list[str] = dataclasses.field(default_factory=list)
- table_ids: list[str] = dataclasses.field(default_factory=list)
- metric_ids: list[str] = dataclasses.field(default_factory=list)
- check_ids: list[str] = dataclasses.field(default_factory=list)
- node_ids: list[str] = dataclasses.field(default_factory=list)
- suite_run_id: str | None = None
- data_modeling_job_id: str | None = None
- created_by_id: int | None = None
- # Audits the staged folder rather than the published table. Needs exactly one saved query.
- staged_queryable_folder: str | None = None
+from ..facade.contracts import RunCheckSuiteInputs as RunCheckSuiteInputs
+from ..facade.enums import SuiteRunStatus
@frozen
diff --git a/products/data_quality/backend/temporal/schedule.py b/products/data_quality/backend/temporal/schedule.py
index ea4268592add..9182ce30fdfb 100644
--- a/products/data_quality/backend/temporal/schedule.py
+++ b/products/data_quality/backend/temporal/schedule.py
@@ -15,7 +15,29 @@ from temporalio.client import (
from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+from .activities.reconcile_schedules import ScheduleReconcileCursor
+from .workflows.reconcile_schedules import RECONCILE_WORKFLOW_NAME
+
CLEANUP_SCHEDULE_ID = "cleanup-data-quality-check-runs-schedule"
+RECONCILE_SCHEDULE_ID = "reconcile-data-quality-metric-schedules"
+
+
+async def create_reconcile_metric_schedules_schedule(client: Client) -> None:
+ await _upsert(
+ client,
+ RECONCILE_SCHEDULE_ID,
+ Schedule(
+ action=ScheduleActionStartWorkflow(
+ RECONCILE_WORKFLOW_NAME,
+ ScheduleReconcileCursor(),
+ id=RECONCILE_SCHEDULE_ID,
+ task_queue=settings.DATA_MODELING_TASK_QUEUE,
+ execution_timeout=dt.timedelta(hours=1),
+ ),
+ spec=ScheduleSpec(cron_expressions=["*/15 * * * *"]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ ),
+ )
async def create_cleanup_data_quality_check_runs_schedule(client: Client) -> None:
diff --git a/products/data_quality/backend/temporal/workflows/reconcile_schedules.py b/products/data_quality/backend/temporal/workflows/reconcile_schedules.py
new file mode 100644
index 000000000000..6e6d43981e5e
--- /dev/null
+++ b/products/data_quality/backend/temporal/workflows/reconcile_schedules.py
@@ -0,0 +1,30 @@
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from ..activities.reconcile_schedules import ScheduleReconcileCursor, reconcile_metric_schedules_activity
+
+RECONCILE_WORKFLOW_NAME = "data-quality-reconcile-metric-schedules"
+PAGES_PER_WORKFLOW = 100
+
+
[email protected](name=RECONCILE_WORKFLOW_NAME)
+class ReconcileMetricSchedulesWorkflow(PostHogWorkflow):
+ inputs_cls = ScheduleReconcileCursor
+
+ @workflow.run
+ async def run(self, cursor: ScheduleReconcileCursor) -> None:
+ for _ in range(PAGES_PER_WORKFLOW):
+ cursor = await workflow.execute_activity(
+ reconcile_metric_schedules_activity,
+ cursor,
+ start_to_close_timeout=timedelta(minutes=5),
+ heartbeat_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if cursor.done:
+ return
+ workflow.continue_as_new(cursor)
diff --git a/products/data_quality/backend/tests/schedule_helpers.py b/products/data_quality/backend/tests/schedule_helpers.py
new file mode 100644
index 000000000000..eb93fea44ea8
--- /dev/null
+++ b/products/data_quality/backend/tests/schedule_helpers.py
@@ -0,0 +1,52 @@
+from collections.abc import Callable
+from copy import deepcopy
+from datetime import UTC, datetime, timedelta
+
+from unittest.mock import AsyncMock, Mock
+
+from temporalio.client import (
+ Schedule,
+ ScheduleAlreadyRunningError,
+ ScheduleDescription,
+ ScheduleUpdate,
+ ScheduleUpdateInput,
+)
+from temporalio.service import RPCError, RPCStatusCode
+
+
+def schedule_client() -> Mock:
+ client = Mock()
+ schedules: dict[str, Schedule] = {}
+ client.schedules = schedules
+
+ async def create(*, id: str, schedule: Schedule, **kwargs: object) -> None:
+ if id in schedules:
+ raise ScheduleAlreadyRunningError()
+ schedules[id] = deepcopy(schedule)
+
+ def handle(schedule_id: str) -> Mock:
+ async def describe() -> Mock:
+ if schedule_id not in schedules:
+ raise RPCError("Schedule missing", RPCStatusCode.NOT_FOUND, b"")
+ return Mock(
+ spec=ScheduleDescription,
+ schedule=deepcopy(schedules[schedule_id]),
+ info=Mock(next_action_times=[datetime.now(UTC) + timedelta(hours=1)]),
+ )
+
+ async def update(callback: Callable[[ScheduleUpdateInput], ScheduleUpdate]) -> None:
+ result = callback(ScheduleUpdateInput(description=await describe()))
+ schedules[schedule_id] = result.schedule
+
+ async def delete() -> None:
+ schedules.pop(schedule_id, None)
+
+ return Mock(
+ describe=AsyncMock(side_effect=describe),
+ update=AsyncMock(side_effect=update),
+ delete=AsyncMock(side_effect=delete),
+ )
+
+ client.create_schedule = AsyncMock(side_effect=create)
+ client.get_schedule_handle.side_effect = handle
+ return client
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index 94fa5562d9af..6448bf1d27ac 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -31,6 +31,8 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable
if TYPE_CHECKING:
from posthog.models.team import Team
+from .schedule_helpers import schedule_client
+
START_SUITE = "products.data_quality.backend.logic.checks.sync_connect"
FLAG = "products.data_quality.backend.presentation.views.is_data_quality_checks_enabled"
@@ -44,6 +46,10 @@ class TestMetricCheckAPI(APIBaseTest):
definition={"kind": "HogQLQuery", "query": "SELECT 10 AS signups"},
referenced_table_names=[],
)
+ self.temporal = schedule_client()
+ self.enterContext(
+ patch("products.data_quality.backend.logic.schedules.async_connect", AsyncMock(return_value=self.temporal))
+ )
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)
@@ -51,16 +57,18 @@ class TestMetricCheckAPI(APIBaseTest):
self.addCleanup(flag.stop)
def _create(self) -> dict:
- response = self.client.post(
- f"{self.url}/",
- {"check_type": "custom_sql", "config": {"query": "SELECT * FROM {metric} WHERE signups < 100"}},
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ f"{self.url}/",
+ {"check_type": "custom_sql", "config": {"query": "SELECT * FROM {metric} WHERE signups < 100"}},
+ )
assert response.status_code == 201, response.content
return response.json()
@parameterized.expand(
[
("checks_list", "get", "checks/"),
+ ("checks_schedule", "get", "checks/schedule/"),
("checks_health", "get", "checks/health/"),
("checks_run_all", "post", "checks/run_all/"),
("suite_runs_list", "get", "check_suite_runs/"),
@@ -93,10 +101,48 @@ class TestMetricCheckAPI(APIBaseTest):
response = self.client.get(f"{parent}/{identifier}/{action}/")
assert response.status_code == 404, response.content
- def test_metric_check_authoring_and_overview(self) -> None:
+ def test_schedule_change_refuses_queries_the_editor_cannot_run(self) -> None:
+ check = self._create()
+ denied = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="restricted_orders",
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"},
+ )
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check["id"]).update(
+ config={"query": "SELECT * FROM {metric} WHERE EXISTS (SELECT 1 FROM restricted_orders)"},
+ )
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]
+ self.organization.save(update_fields=["available_product_features"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(denied.id),
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
+ cache.clear()
+ with patch(
+ "posthog.hogql.database.database.feature_enabled_or_false",
+ side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",
+ ):
+ response = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"})
+ assert response.status_code == 403, response.content
+ schedule = api.get_schedule(self.team.id, "metric", self.metric.id)
+ assert schedule is not None
+ assert schedule.interval == "24hour"
+
+ def test_metric_check_authoring_schedule_and_overview(self) -> None:
+ assert self.client.get(f"{self.url}/schedule/").status_code == 404
+ assert self.client.patch(f"{self.url}/schedule/", {"enabled": False}).status_code == 404
check = self._create()
assert [entry["check_type"] for entry in self.client.get(f"{self.url}/check_types/").json()] == ["custom_sql"]
assert self.client.get(f"{self.url}/").json()["results"][0]["id"] == check["id"]
+ schedule = self.client.get(f"{self.url}/schedule/").json()
+ assert schedule["interval"] == "24hour"
+ patched = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour", "enabled": False})
+ assert patched.status_code == 200
+ assert patched.json()["interval"] == "6hour"
+ assert patched.json()["enabled"] is False
edited = self.client.patch(
f"{self.url}/{check['id']}/", {"config": {"query": "SELECT * FROM {metric} WHERE signups < 50"}}
)
@@ -108,6 +154,58 @@ class TestMetricCheckAPI(APIBaseTest):
assert row["subject_metric_name"] == "registrations"
assert "definition" not in row and "values" not in row
assert self.client.delete(f"{self.url}/{check['id']}/").status_code == 204
+ assert self.client.get(f"{self.url}/schedule/").status_code == 200
+
+ def test_schedule_service_failure_is_retryable(self) -> None:
+ self._create()
+ with patch("products.data_quality.backend.logic.schedules.async_connect", AsyncMock(side_effect=TimeoutError)):
+ 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
+
+ def test_schedule_history_excludes_manual_suites(self) -> None:
+ self._create()
+ scheduled = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="scheduled", subject_type=SubjectType.METRIC, subject_uuid=self.metric.id
+ )
+ 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()
+ assert schedule["last_suite_run"] == str(scheduled.id)
+
+ def test_schedule_history_hides_a_suite_with_revoked_reference_access(self) -> None:
+ check = self._create()
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="restricted_orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="scheduled", subject_type=SubjectType.METRIC, subject_uuid=self.metric.id
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite,
+ quality_check_id=check["id"],
+ subject_type=SubjectType.METRIC,
+ subject_uuid=self.metric.id,
+ check_type=CheckType.CUSTOM_SQL,
+ status=CheckRunStatus.PASSED,
+ referenced_subjects=[{"subject_type": "view", "subject_uuid": str(view.id)}],
+ )
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]
+ self.organization.save(update_fields=["available_product_features"])
+ assert self.client.get(f"{self.url}/schedule/").json()["last_suite_run"] == str(suite.id)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(view.id),
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
+ cache.clear()
+ schedule = self.client.get(f"{self.url}/schedule/").json()
+ assert schedule["last_suite_run"] is None
+ assert schedule["last_run_at"] is None
def test_a_metric_that_leaves_hogql_still_takes_presentation_edits(self) -> None:
check = self._create()
@@ -149,6 +247,7 @@ class TestMetricCheckAPI(APIBaseTest):
)
cache.clear()
assert self.client.get(f"{self.url}/").status_code == 403
+ assert self.client.get(f"{self.url}/schedule/").status_code == 403
assert self.client.get(f"{self.suites_url}/").status_code == 403
assert self.client.get(f"/api/projects/{self.team.id}/data_quality_checks/").json()["results"] == []
diff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.py
index 9f8df23a7c75..d8db6f2449de 100644
--- a/products/data_quality/backend/tests/test_run_check_suite.py
+++ b/products/data_quality/backend/tests/test_run_check_suite.py
@@ -32,7 +32,7 @@ from products.data_quality.backend.temporal.workflows.run_check_suite import Run
RUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"
ACTIVITY_INFO = "products.data_quality.backend.temporal.activities.prepare_check_suite.activity.info"
PREPARE_FLAG = (
- "products.data_quality.backend.temporal.activities.prepare_check_suite.is_data_quality_checks_enabled_for_team_id"
+ "products.data_quality.backend.temporal.activities.prepare_check_suite.get_data_quality_checks_flag_for_team_id"
)
@@ -70,6 +70,7 @@ class TestCheckSuiteActivities(BaseTest):
return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})
def _prepare(self, **kwargs) -> PreparedSuite:
+ schedule_enabled = kwargs.pop("schedule_enabled", True)
inputs = RunCheckSuiteInputs(
team_id=self.team.id,
trigger=kwargs.pop("trigger", SuiteRunTrigger.MANUAL),
@@ -77,7 +78,7 @@ class TestCheckSuiteActivities(BaseTest):
**kwargs,
)
with patch(ACTIVITY_INFO, return_value=_ActivityInfo()):
- return _prepare(inputs)
+ return _prepare(inputs, schedule_enabled=schedule_enabled)
def test_a_subject_with_no_checks_produces_no_batches(self) -> None:
prepared = self._prepare()
@@ -118,6 +119,27 @@ class TestCheckSuiteActivities(BaseTest):
assert suite_run.subject_type == SubjectType.TABLE
assert suite_run.subject_uuid == table_id
+ def test_scheduled_metric_suite_selects_checks_and_reuses_history_on_retry(self) -> None:
+ metric_id = uuid4()
+ on_metric = self._check(saved_query_id=None, metric_id=metric_id, subject_type=SubjectType.METRIC)
+ self._check()
+
+ prepared = self._prepare(
+ saved_query_ids=[],
+ metric_ids=[str(metric_id)],
+ trigger=SuiteRunTrigger.SCHEDULED,
+ )
+ assert prepared.batches == [[str(on_metric.id)]]
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)
+ assert suite.subject_type == SubjectType.METRIC
+ assert suite.subject_uuid == metric_id
+ retried = self._prepare(
+ saved_query_ids=[],
+ metric_ids=[str(metric_id)],
+ trigger=SuiteRunTrigger.SCHEDULED,
+ )
+ assert retried.suite_run_id == prepared.suite_run_id
+
def test_mixed_metric_and_view_suite_has_no_single_subject(self) -> None:
prepared = self._prepare(metric_ids=[str(uuid4())])
suite = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)
@@ -131,6 +153,32 @@ class TestCheckSuiteActivities(BaseTest):
assert prepared.batches == []
+ def test_a_paused_schedule_prepares_no_batches(self) -> None:
+ metric_id = uuid4()
+ self._check(saved_query_id=None, metric_id=metric_id, subject_type=SubjectType.METRIC)
+
+ prepared = self._prepare(
+ saved_query_ids=[],
+ schedule_enabled=False,
+ metric_ids=[str(metric_id)],
+ trigger=SuiteRunTrigger.SCHEDULED,
+ )
+
+ assert prepared.batches == []
+
+ def test_an_unreadable_flag_fails_instead_of_preparing_an_empty_suite(self) -> None:
+ metric_id = uuid4()
+ self._check(saved_query_id=None, metric_id=metric_id, subject_type=SubjectType.METRIC)
+
+ with patch(PREPARE_FLAG, return_value=None), self.assertRaises(RuntimeError):
+ self._prepare(
+ saved_query_ids=[],
+ metric_ids=[str(metric_id)],
+ trigger=SuiteRunTrigger.SCHEDULED,
+ )
+
+ assert not DataQualitySuiteRun.objects.for_team(self.team.id).exists()
+
def test_a_batch_counts_each_outcome_and_records_a_run_per_check(self) -> None:
passing = self._check()
failing = self._check(column_name="total")
diff --git a/products/data_quality/backend/tests/test_schedules.py b/products/data_quality/backend/tests/test_schedules.py
new file mode 100644
index 000000000000..8e108b46289f
--- /dev/null
+++ b/products/data_quality/backend/tests/test_schedules.py
@@ -0,0 +1,170 @@
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, patch
+
+from asgiref.sync import async_to_sync, sync_to_async
+from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
+from temporalio.testing import ActivityEnvironment
+
+from posthog.models.scoping import team_scope
+from posthog.models.team import Team
+
+from products.data_catalog.backend.facade.api import upsert_metric
+from products.data_quality.backend.facade.enums import SuiteRunTrigger
+from 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.schedules import (
+ get_schedule,
+ provision_metric_schedule,
+ schedule_key,
+ set_schedule,
+)
+from products.data_quality.backend.models import DataQualityCheck
+from products.data_quality.backend.temporal.activities.prepare_check_suite import prepare_check_suite_activity
+from products.data_quality.backend.temporal.activities.reconcile_schedules import (
+ ScheduleReconcileCursor,
+ _check_page,
+ _dead_schedules,
+ reconcile_metric_schedules_activity,
+)
+from products.data_quality.backend.temporal.contracts import PreparedSuite, RunCheckSuiteInputs
+
+from .schedule_helpers import schedule_client
+
+
+class TestSchedules(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(team_scope(self.team.id))
+ self.metric = upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="revenue",
+ description="Revenue",
+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS amount"},
+ )
+ self.temporal = schedule_client()
+ self.enterContext(
+ patch("products.data_quality.backend.logic.schedules.async_connect", AsyncMock(return_value=self.temporal))
+ )
+ self.key = schedule_key(self.team.id, "metric", self.metric.id)
+
+ def _create(self) -> None:
+ upsert_check(
+ team=self.team,
+ user=self.user,
+ subject_type="metric",
+ subject_uuid=str(self.metric.id),
+ check_type="custom_sql",
+ column_name="",
+ config={"query": "SELECT * FROM {metric} WHERE amount < 0"},
+ )
+
+ def test_check_commit_creates_one_schedule_and_repair_preserves_preferences(self) -> None:
+ with self.captureOnCommitCallbacks(execute=False) as callbacks:
+ self._create()
+ self.temporal.create_schedule.assert_not_called()
+ for callback in callbacks:
+ callback()
+ assert len(self.temporal.schedules) == 1
+ set_schedule(self.team.id, "metric", self.metric.id, interval="6hour", enabled=False)
+ provision_metric_schedule(self.team.id, str(self.metric.id))
+ schedule = get_schedule(self.team.id, "metric", self.metric.id)
+ assert schedule is not None
+ assert schedule.interval == "6hour"
+ assert not schedule.enabled
+ assert schedule.next_run_at is None
+ assert len(self.temporal.schedules) == 1
+
+ def test_failed_provision_is_recoverable_from_committed_checks(self) -> None:
+ original_create = self.temporal.create_schedule.side_effect
+ self.temporal.create_schedule.side_effect = RPCError("Unavailable", RPCStatusCode.UNAVAILABLE, b"")
+ with self.captureOnCommitCallbacks(execute=True):
+ self._create()
+ assert not self.temporal.schedules
+ checks = _check_page(None)
+ assert [check.metric_id for check in checks] == [self.metric.id]
+ self.temporal.create_schedule.side_effect = original_create
+ async_to_sync(MetricSchedules(self.temporal).ensure)(self.key)
+ assert get_schedule(self.team.id, "metric", self.metric.id) is not None
+
+ def test_canonical_environment_uses_the_same_schedule(self) -> None:
+ child = Team.objects.create(organization=self.organization, name="child", parent_team=self.team)
+ assert schedule_key(child.id, "metric", self.metric.id) == self.key
+ provision_metric_schedule(self.team.id, str(self.metric.id))
+ provision_metric_schedule(child.id, str(self.metric.id))
+ assert len(self.temporal.schedules) == 1
+
+ def test_cleanup_preserves_live_subjects_and_does_not_trust_another_team(self) -> None:
+ other = Team.objects.create(organization=self.organization)
+ other_key = schedule_key(other.id, "metric", self.metric.id)
+ assert _dead_schedules([self.key.temporal_id, other_key.temporal_id]) == [other_key.temporal_id]
+ self.metric.deleted = True
+ self.metric.save(update_fields=["deleted"])
+ assert _dead_schedules([self.key.temporal_id]) == [self.key.temporal_id]
+
+ def test_repair_pages_past_deleted_and_disabled_checks(self) -> None:
+ self._create()
+ check = DataQualityCheck.objects.for_team(self.team.id).get(metric_id=self.metric.id)
+ check.enabled = False
+ check.deleted = True
+ check.save(update_fields=["enabled", "deleted"])
+ assert [entry.id for entry in _check_page(None)] == [check.id]
+ assert not _check_page(str(check.id))
+ self.metric.deleted = True
+ self.metric.save(update_fields=["deleted"])
+ assert not _check_page(None)
+
+ async def _reconcile(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 (
+ 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",
+ sync_to_async,
+ ),
+ ):
+ cursor = async_to_sync(self._reconcile)()
+ assert cursor.cleanup
+ set_schedule(self.team.id, "metric", self.metric.id, interval="6hour", enabled=False)
+ async_to_sync(self._reconcile)()
+ schedule = get_schedule(self.team.id, "metric", self.metric.id)
+ assert schedule is not None
+ assert not schedule.enabled
+ assert schedule.interval == "6hour"
+
+ async def _prepare_scheduled(self) -> PreparedSuite:
+ return await ActivityEnvironment().run(
+ prepare_check_suite_activity,
+ RunCheckSuiteInputs(
+ team_id=self.team.id,
+ trigger=SuiteRunTrigger.SCHEDULED,
+ metric_ids=[str(self.metric.id)],
+ schedule_id=self.key.temporal_id,
+ ),
+ )
+
+ @parameterized.expand([("enabled", True, True), ("paused", False, True), ("missing", True, False)])
+ def test_scheduled_preparation_checks_temporal_state(self, _name: str, enabled: bool, exists: bool) -> None:
+ self._create()
+ if exists:
+ provision_metric_schedule(self.team.id, str(self.metric.id))
+ set_schedule(self.team.id, "metric", self.metric.id, enabled=enabled)
+ with (
+ patch(
+ "products.data_quality.backend.temporal.activities.prepare_check_suite.async_connect",
+ AsyncMock(return_value=self.temporal),
+ ),
+ patch(
+ "products.data_quality.backend.temporal.activities.prepare_check_suite.get_data_quality_checks_flag_for_team_id",
+ return_value=True,
+ ),
+ ):
+ prepared = async_to_sync(self._prepare_scheduled)()
+ assert bool(prepared.batches) == (enabled and exists)
diff --git a/products/data_quality/backend/tests/test_temporal_schedules.py b/products/data_quality/backend/tests/test_temporal_schedules.py
new file mode 100644
index 000000000000..f5ef2e5a9fc6
--- /dev/null
+++ b/products/data_quality/backend/tests/test_temporal_schedules.py
@@ -0,0 +1,72 @@
+from collections.abc import Callable
+from datetime import timedelta
+from uuid import UUID
+
+from unittest.mock import AsyncMock, Mock
+
+from django.test import SimpleTestCase
+
+from temporalio.client import (
+ ScheduleAlreadyRunningError,
+ ScheduleDescription,
+ ScheduleOverlapPolicy,
+ ScheduleUpdate,
+ ScheduleUpdateInput,
+)
+
+from products.data_quality.backend.logic.metric_schedules import MetricScheduleKey, MetricSchedules
+
+
+class TestTemporalMetricSchedules(SimpleTestCase):
+ def setUp(self) -> None:
+ self.key = MetricScheduleKey(team_id=123, metric_id=UUID("00000000-0000-0000-0000-000000000001"))
+ self.temporal = Mock()
+ self.temporal.create_schedule = AsyncMock()
+ self.handle = Mock(describe=AsyncMock(), update=AsyncMock())
+ self.temporal.get_schedule_handle.return_value = self.handle
+ self.schedules = MetricSchedules(self.temporal)
+
+ async def test_creation_uses_native_cadence_and_execution_policies(self) -> None:
+ await self.schedules.ensure(self.key)
+ schedule = self.temporal.create_schedule.call_args.kwargs["schedule"]
+ assert schedule.spec.intervals[0].every == timedelta(days=1)
+ assert schedule.spec.intervals[0].offset < timedelta(days=1)
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.policy.catchup_window == timedelta(minutes=15)
+ assert not schedule.policy.pause_on_failure
+ assert self.temporal.create_schedule.call_args.kwargs["trigger_immediately"]
+ assert schedule.action.args[0].metric_ids == [str(self.key.metric_id)]
+ assert schedule.action.args[0].team_id == self.key.team_id
+
+ async def test_repeated_creation_preserves_temporal_configuration(self) -> None:
+ self.temporal.create_schedule.side_effect = ScheduleAlreadyRunningError()
+ await self.schedules.ensure(self.key)
+ self.handle.update.assert_not_called()
+
+ async def test_interval_update_preserves_a_concurrent_pause(self) -> None:
+ current = self.schedules.build(self.key)
+ current.state.paused = True
+ current.state.note = "Maintenance"
+ current.spec.jitter = timedelta(seconds=30)
+ self.handle.describe.return_value = Mock(spec=ScheduleDescription, schedule=current)
+
+ async def update(callback: Callable[[ScheduleUpdateInput], ScheduleUpdate]) -> None:
+ result = callback(ScheduleUpdateInput(description=Mock(spec=ScheduleDescription, schedule=current)))
+ assert result.schedule.state.paused
+ assert result.schedule.state.note == "Maintenance"
+ assert result.schedule.spec.jitter == timedelta(seconds=30)
+ assert result.schedule.spec.intervals[0].every == timedelta(hours=6)
+
+ self.handle.update.side_effect = update
+ await self.schedules.update(self.key, interval="6hour")
+
+ async def test_pause_update_preserves_existing_interval(self) -> None:
+ current = self.schedules.build(self.key, interval="6hour")
+
+ async def update(callback: Callable[[ScheduleUpdateInput], ScheduleUpdate]) -> None:
+ result = callback(ScheduleUpdateInput(description=Mock(spec=ScheduleDescription, schedule=current)))
+ assert result.schedule.state.paused
+ assert result.schedule.spec.intervals[0].every == timedelta(hours=6)
+
+ self.handle.update.side_effect = update
+ await self.schedules.update(self.key, enabled=False)
diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.ts
index 1388971ad8fe..6ac0543caffc 100644
--- a/products/data_quality/frontend/generated/api.schemas.ts
+++ b/products/data_quality/frontend/generated/api.schemas.ts
@@ -482,6 +482,67 @@ export interface DataQualitySubjectHealthApi {
checks_failing: number
}
+/**
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day
+ */
+export type DataQualityScheduleIntervalEnumApi =
+ (typeof DataQualityScheduleIntervalEnumApi)[keyof typeof DataQualityScheduleIntervalEnumApi]
+
+export const DataQualityScheduleIntervalEnumApi = {
+ '1hour': '1hour',
+ '6hour': '6hour',
+ '12hour': '12hour',
+ '24hour': '24hour',
+ '7day': '7day',
+} as const
+
+export interface DataQualityCheckScheduleApi {
+ /** Schedule identifier. */
+ readonly id: string
+ /** How often the checks run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ readonly interval: DataQualityScheduleIntervalEnumApi
+ /** Whether the schedule runs automatically. */
+ readonly enabled: boolean
+ /**
+ * Next scheduled execution time, if enabled.
+ * @nullable
+ */
+ readonly next_run_at: string | null
+ /**
+ * Most recent visible scheduled suite execution time.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ /**
+ * Most recent visible scheduled suite.
+ * @nullable
+ */
+ readonly last_suite_run: string | null
+}
+
+export interface PatchedDataQualityCheckScheduleUpdateApi {
+ /** How often all enabled checks on the metric run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ interval?: DataQualityScheduleIntervalEnumApi
+ /** Whether checks run automatically on this schedule. */
+ enabled?: boolean
+}
+
/**
* Type-specific configuration, validated against the check type's JSON schema.
*/
diff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.ts
index 7e3e6540b7b1..7d21b6f78204 100644
--- a/products/data_quality/frontend/generated/api.ts
+++ b/products/data_quality/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
DataCatalogMetricsChecksListParams,
DataQualityCheckApi,
DataQualityCheckRunApi,
+ DataQualityCheckScheduleApi,
DataQualityCheckTypeApi,
DataQualityChecksListParams,
DataQualityRunRequestApi,
@@ -23,6 +24,7 @@ import type {
PaginatedDataQualityOverviewCheckListApi,
PaginatedDataQualitySuiteRunListApi,
PatchedDataQualityCheckApi,
+ PatchedDataQualityCheckScheduleUpdateApi,
WarehouseSavedQueriesCheckSuiteRunsListParams,
WarehouseSavedQueriesChecksListParams,
WarehouseTablesCheckSuiteRunsListParams,
@@ -362,6 +364,51 @@ export const dataCatalogMetricsChecksRunAllCreate = async (
})
}
+export const getDataCatalogMetricsChecksScheduleRetrieveUrl = (projectId: string, metricId: string) => {
+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/schedule/`
+}
+
+/**
+ * CRUD for one subject's checks, plus the actions that run them and report on them.
+ */
+export const dataCatalogMetricsChecksScheduleRetrieve = async (
+ projectId: string,
+ metricId: string,
+ options?: RequestInit
+): Promise<DataQualityCheckScheduleApi> => {
+ return apiMutator<DataQualityCheckScheduleApi>(
+ getDataCatalogMetricsChecksScheduleRetrieveUrl(projectId, metricId),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDataCatalogMetricsChecksSchedulePartialUpdateUrl = (projectId: string, metricId: string) => {
+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/schedule/`
+}
+
+/**
+ * CRUD for one subject's checks, plus the actions that run them and report on them.
+ */
+export const dataCatalogMetricsChecksSchedulePartialUpdate = async (
+ projectId: string,
+ metricId: string,
+ patchedDataQualityCheckScheduleUpdateApi?: PatchedDataQualityCheckScheduleUpdateApi,
+ options?: RequestInit
+): Promise<DataQualityCheckScheduleApi> => {
+ return apiMutator<DataQualityCheckScheduleApi>(
+ getDataCatalogMetricsChecksSchedulePartialUpdateUrl(projectId, metricId),
+ {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedDataQualityCheckScheduleUpdateApi),
+ }
+ )
+}
+
export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualityChecksListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.ts
index 26c9096df3d1..63170d34f5bc 100644
--- a/products/data_quality/frontend/generated/api.zod.ts
+++ b/products/data_quality/frontend/generated/api.zod.ts
@@ -238,6 +238,22 @@ export const DataCatalogMetricsChecksPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
+/**
+ * CRUD for one subject's checks, plus the actions that run them and report on them.
+ */
+export const DataCatalogMetricsChecksSchedulePartialUpdateBody = /* @__PURE__ */ zod.object({
+ interval: zod
+ .enum(['1hour', '6hour', '12hour', '24hour', '7day'])
+ .describe(
+ '\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'
+ )
+ .optional()
+ .describe(
+ 'How often all enabled checks on the metric run.\n\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'
+ ),
+ enabled: zod.boolean().optional().describe('Whether checks run automatically on this schedule.'),
+})
+
/**
* Run the named checks now, or every enabled check in the project when none are named. Returns the suite run to poll for the report.
*/
diff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yaml
index 0a68ff18907e..03841f359c40 100644
--- a/products/data_quality/mcp/tools.yaml
+++ b/products/data_quality/mcp/tools.yaml
@@ -48,6 +48,12 @@ tools:
data-catalog-metrics-checks-runs-list:
operation: data_catalog_metrics_checks_runs_list
enabled: false
+ data-catalog-metrics-checks-schedule-partial-update:
+ operation: data_catalog_metrics_checks_schedule_partial_update
+ enabled: false
+ data-catalog-metrics-checks-schedule-retrieve:
+ operation: data_catalog_metrics_checks_schedule_retrieve
+ enabled: false
data-catalog-metrics-checks-update:
operation: data_catalog_metrics_checks_update
enabled: false
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 6d0ef96bbcfd..9e7ec24f58ab 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1396,6 +1396,7 @@ export type ActivityLogListParams = {
* * `Metric` - Metric
* * `TableCertification` - TableCertification
* * `DataQualityCheck` - DataQualityCheck
+ * * `DataQualityCheckSchedule` - DataQualityCheckSchedule
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
@@ -1493,6 +1494,7 @@ export const ActivityLogListScope = {
Metric: 'Metric',
TableCertification: 'TableCertification',
DataQualityCheck: 'DataQualityCheck',
+ DataQualityCheckSchedule: 'DataQualityCheckSchedule',
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
@@ -1577,6 +1579,7 @@ export const ActivityLogListScope = {
* * `Metric` - Metric
* * `TableCertification` - TableCertification
* * `DataQualityCheck` - DataQualityCheck
+ * * `DataQualityCheckSchedule` - DataQualityCheckSchedule
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
@@ -1662,6 +1665,7 @@ export const ActivityLogListScopesItem = {
Metric: 'Metric',
TableCertification: 'TableCertification',
DataQualityCheck: 'DataQualityCheck',
+ DataQualityCheckSchedule: 'DataQualityCheckSchedule',
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 65ebb9259fbc..e326a07baa0e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22902,6 +22902,54 @@ export namespace Schemas {
readonly created_at: string;
}
+ /**
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day
+ */
+ export type DataQualityScheduleIntervalEnum = typeof DataQualityScheduleIntervalEnum[keyof typeof DataQualityScheduleIntervalEnum];
+
+
+ export const DataQualityScheduleIntervalEnum = {
+ '1hour': '1hour',
+ '6hour': '6hour',
+ '12hour': '12hour',
+ '24hour': '24hour',
+ '7day': '7day',
+ } as const;
+
+ export interface DataQualityCheckSchedule {
+ /** Schedule identifier. */
+ readonly id: string;
+ /** How often the checks run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ readonly interval: DataQualityScheduleIntervalEnum;
+ /** Whether the schedule runs automatically. */
+ readonly enabled: boolean;
+ /**
+ * Next scheduled execution time, if enabled.
+ * @nullable
+ */
+ readonly next_run_at: string | null;
+ /**
+ * Most recent visible scheduled suite execution time.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ /**
+ * Most recent visible scheduled suite.
+ * @nullable
+ */
+ readonly last_suite_run: string | null;
+ }
+
/**
* JSON schema the config object is validated against.
*/
@@ -63880,6 +63928,19 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
+ export interface PatchedDataQualityCheckScheduleUpdate {
+ /** How often all enabled checks on the metric run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ interval?: DataQualityScheduleIntervalEnum;
+ /** Whether checks run automatically on this schedule. */
+ enabled?: boolean;
+ }
+
/**
* The team-level materialization gate. Checks always run and warn; this only toggles blocking.
*/
@@ -94342,6 +94403,7 @@ export namespace Schemas {
* * `Metric` - Metric
* * `TableCertification` - TableCertification
* * `DataQualityCheck` - DataQualityCheck
+ * * `DataQualityCheckSchedule` - DataQualityCheckSchedule
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
@@ -94440,6 +94502,7 @@ export namespace Schemas {
Metric: 'Metric',
TableCertification: 'TableCertification',
DataQualityCheck: 'DataQualityCheck',
+ DataQualityCheckSchedule: 'DataQualityCheckSchedule',
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
@@ -94524,6 +94587,7 @@ export namespace Schemas {
* * `Metric` - Metric
* * `TableCertification` - TableCertification
* * `DataQualityCheck` - DataQualityCheck
+ * * `DataQualityCheckSchedule` - DataQualityCheckSchedule
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
@@ -94610,6 +94674,7 @@ export namespace Schemas {
Metric: 'Metric',
TableCertification: 'TableCertification',
DataQualityCheck: 'DataQualityCheck',
+ DataQualityCheckSchedule: 'DataQualityCheckSchedule',
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',