: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
feat(data-quality): check events, persons and groups (#102496)
Thiago Salvatore8751d61fc06a
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.mdindex 7554702ff583..cf2ec6265fcf 100644--- a/docs/internal/data-quality-checks.md+++ b/docs/internal/data-quality-checks.md@@ -1,12 +1,12 @@# Data quality checks-Data quality checks audit warehouse tables, saved views, and catalog metrics. Checks keep their identity and history when their assertion changes.+Data quality checks audit warehouse tables, saved views, catalog metrics, and the PostHog tables `events`, `persons`, and `groups`. Checks keep their identity and history when their assertion changes.## Authorization-Every check is authored, read, run and scheduled through the project-wide `data_quality_checks` and `data_quality_runs` routes, whichever kind of subject it audits. A request names its subject in the body on create, and by check id after that; `subject_type` and `subject_uuid` query parameters narrow a listing, a health rollup, a run history, or a schedule to one subject.+Every check is authored, read, run and scheduled through the project-wide `data_quality_checks` and `data_quality_runs` routes, whichever kind of subject it audits. A request names its subject in the body on create, and by check id after that; `subject_type` and `subject_uuid` query parameters narrow a listing, a health rollup, a run history, or a schedule to one subject. A PostHog table has no database row, so its `subject_uuid` is a fixed id derived from the table name and is the same in every project.-Check and run routes require project membership, query access, and access to the subject. The static check-type catalog needs no access to any subject. Metric checks use catalog permissions. Table and view checks use their respective warehouse object permissions, including explicit object grants and inherited source grants. A resource-wide denial does not discard a more specific grant that the canonical access-control rules permit.+Check and run routes require project membership, query access, and access to the subject. The static check-type catalog needs no access to any subject. Metric checks use catalog permissions. Table and view checks use their respective warehouse object permissions, including explicit object grants and inherited source grants. A PostHog table has no object to grant, so a check on one answers to project query access and the warehouse table resource level. A failing check on a PostHog table notifies members with query access and links to the data quality overview, because these tables have no page of their own. A resource-wide denial does not discard a more specific grant that the canonical access-control rules permit.Reading checks, health, and run history requires viewer access. Creating, editing, deleting, or manually running checks requires editor access to their subject. Referenced subjects require viewer access. These checks apply even when the warehouse query-enforcement feature flag is disabled.@@ -14,22 +14,36 @@ Checks and suites are polymorphic: a catalog-only member can read a teammate's mRestricted callers must have access to both the stored and proposed definitions before PUT or PATCH can save anything, including presentation-only edits. Authorization is repeated if a concurrent edit changes the definition accepted by the transaction. An edit makes three attempts. After three attempts it writes nothing and returns HTTP 400 with the code `concurrent_edit`. An unavailable reference fails closed. An authorized caller can still disable a stale check without revalidating its assertion.-A check that reads more than its own subject executes as a user. A manual run executes as the user who started it, and an automated run executes as the user who last wrote the definition. If neither user is available, the run records an error and executes no SQL.+A check that reads more than its own subject executes as a user, and so does every check on a PostHog table, because property restrictions and warehouse joins on those tables resolve per user. A manual run executes as the user who started it, and an automated run executes as the user who last wrote the definition. If neither user is available, the run records an error and executes no SQL.++A check on a PostHog table names a column the registry lists for that table. A dotted name reaches into a JSON column only, so `properties.$browser` is accepted and `person.properties.email` or a warehouse join is refused at authoring time. The same rule applies to the `to_column` of a relationships check that points at a PostHog table.## Token scopesAll routes below also require `query:read`. Write scopes include read access; read-only scopes do not authorize writes. Token scopes limit access independently of the user's grants, including for organization administrators.-| Subject kind | Read scope | Write scope |-| ---------------- | -------------------------------------------------- | ---------------------------------------------------- |-| Warehouse tables | `warehouse_objects:read` or `warehouse_table:read` | `warehouse_objects:write` or `warehouse_table:write` |-| Warehouse views | `warehouse_objects:read` or `warehouse_view:read` | `warehouse_objects:write` or `warehouse_view:write` |-| Catalog metrics | `data_catalog:read` | `data_catalog:write` |+| Subject kind | Read scope | Write scope |+| ----------------------------------- | -------------------------------------------------- | ---------------------------------------------------- |+| Warehouse tables and PostHog tables | `warehouse_objects:read` or `warehouse_table:read` | `warehouse_objects:write` or `warehouse_table:write` |+| Warehouse views | `warehouse_objects:read` or `warehouse_view:read` | `warehouse_objects:write` or `warehouse_view:write` |+| Catalog metrics | `data_catalog:read` | `data_catalog:write` |The family scope `warehouse_objects` reaches every warehouse kind. A per-kind scope reaches its own kind only, which is what a key minted by the Agent CLI carries. A token may select only the subject kinds its scopes permit. An unnamed manual sweep skips inaccessible checks; an explicitly selected inaccessible check is rejected. Cross-subject references must also fall within the caller's permitted subject types.The table above applies to the REST routes only. The MCP tools declare `query:read` alone, because a tool's scope list must be met in full and the two subject families are authorized independently; a token with no subject family is refused by the route. A raw HogQL query against `system.information_schema.data_quality_*` needs `query:read` and no other scope. The user's own permissions still apply to each row. A token with `query:read` reads metric checks only if its user has catalog access.+## Lookback window++A check may carry `lookback_hours`, which counts only the rows from the last N hours by the subject's own time column.+It is optional.+Without it, a check reads every row the subject holds.+Only the PostHog tables carry a time column today: `events` bounds on `timestamp`, and `persons` and `groups` bound on `created_at`, which is when each was first seen rather than when it last changed.++A `relationships` check bounds each side on its own, with `lookback_hours` for the rows it checks and `to_lookback_hours` for the rows it looks for a match among.+Custom SQL takes no window, because bounding a query the author wrote would mean rewriting it. Put the filter in the query instead.+A window named for a subject or a target that has no time column is rejected when the check is saved.+A query that runs too long is recorded as `errored` with the message the database returned.+## Custom SQLCustom SQL supports direct relations, subqueries, CTEs, and unions. Metric checks bind `{metric}` before enumerating dependencies. Metric checks cannot use CTEs. Query `{metric}` directly or through a subquery. Expandable table expressions whose dependencies cannot be established, including HogQLX sources and table functions, are rejected during authoring and compilation.@@ -50,7 +64,7 @@ Catalog access is a project permission resource. Notification visibility follows## Subject schedules-A subject whose checks run on a recurring schedule has one Temporal Schedule in its canonical project. Metrics are the only such subject today; a table's and a view's checks run when their data changes instead. 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.+A subject whose checks run on a recurring schedule has one Temporal Schedule in its canonical project. Metrics and PostHog tables are those subjects; a warehouse table's and a view's checks run when their data changes instead. A PostHog table is never synced or materialized, so a schedule is the only trigger its checks have. 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.diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 41be89b064d3..656d4c28a6d9 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -1123,7 +1123,7 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[stif context.database is None:return []checks = data_quality.visible_checks(- team_id, checks, data_quality.denial_context(team_id, context.database)+ team_id, checks, data_quality.sql_denial_context(team_id, context.database))return [[@@ -1177,7 +1177,7 @@ def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozenseif _denial_applies(context, denied):if context.database is None:return []- base = data_quality.without_denied_runs(base, data_quality.denial_context(team_id, context.database))+ base = data_quality.without_denied_runs(base, data_quality.sql_denial_context(team_id, context.database))return [[str(run.id),@@ -1228,7 +1228,7 @@ def _data_quality_health(context: "HogQLContext", allowed: Optional[frozenset[stif context.database is None:return []checks = data_quality.visible_checks(- team_id, checks, data_quality.denial_context(team_id, context.database)+ team_id, checks, data_quality.sql_denial_context(team_id, context.database))by_subject: dict[tuple[str, str], list[Any]] = defaultdict(list)for check in checks:@@ -1977,7 +1977,9 @@ class InformationSchemaDataQualityChecksTable(LazyTable):"id": _string_field("id", description="Stable UUID of the check (pass to the run/update/delete tools)."),"name": _string_field("name", nullable=True, description="Optional handle; NULL when addressed by id."),"subject_type": _string_field(- "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ "subject_type",+ description="'table' (synced source), 'view' (saved query), 'metric' (catalog metric), "+ "or 'posthog_table' (events, persons, groups).",),"subject_uuid": _string_field("subject_uuid",@@ -2041,7 +2043,9 @@ class InformationSchemaDataQualityCheckRunsTable(LazyTable):),"suite_run_id": _string_field("suite_run_id", description="UUID of the batch this execution belonged to."),"subject_type": _string_field(- "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ "subject_type",+ description="'table' (synced source), 'view' (saved query), 'metric' (catalog metric), "+ "or 'posthog_table' (events, persons, groups).",),"subject_uuid": _string_field("subject_uuid", description="UUID of the checked table, view, or metric."),"subject_name": _string_field("subject_name", description="Name of the subject at the time of the run."),@@ -2092,12 +2096,15 @@ class InformationSchemaDataQualityHealthTable(LazyTable):)fields: dict[str, FieldOrTable] = {"subject_type": _string_field(- "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ "subject_type",+ description="'table' (synced source), 'view' (saved query), 'metric' (catalog metric), "+ "or 'posthog_table' (events, persons, groups).",),"subject_uuid": _string_field("subject_uuid", description="UUID of the table, view, or metric."),"subject_name": _string_field("subject_name",- description="Name of the table, view, or metric. Only table and view names are queryable in HogQL.",+ description="Name of the table, view, metric, or PostHog table. "+ "Table, view and PostHog table names are queryable in HogQL; a metric name is not.",),"health": _string_field("health", description="'failing', 'erroring', 'warn', 'healthy', or 'unknown'. Worst outcome wins."diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex da1ffc710b1c..c3b797d1a4a5 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -29,7 +29,7 @@ from ..logic.health import CheckStatusRow, roll_up_healthfrom ..logic.navigation import SubjectKey, SubjectLocation, subject_locationsfrom ..logic.notifications import notify_materialization_blockedfrom ..logic.output_schema import metric_output_schema-from ..logic.permissions import authorized_subject_types, restrict_subject_types, writable_subjects+from ..logic.permissions import authorized_subject_types, restrict_subject_types, sql_denial_context, writable_subjectsfrom ..logic.registry import UnknownCheckTypeError, list_check_typesfrom ..logic.run_records import record_check_runfrom ..logic.schedule_service import get_schedule_with_history, schedule_with_history, update_schedule@@ -80,6 +80,7 @@ __all__ = ["UnknownCheckTypeError","authorized_subject_types","restrict_subject_types",+ "sql_denial_context","live_subject_checks","caller_denial_context","can_be_object_denied",diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.pyindex 002f9ebf86fb..db67d1ab0a38 100644--- a/products/data_quality/backend/facade/contracts.py+++ b/products/data_quality/backend/facade/contracts.py@@ -56,6 +56,7 @@ class RunCheckSuiteInputs: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)+ posthog_table_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 = Nonediff --git a/products/data_quality/backend/facade/enums.py b/products/data_quality/backend/facade/enums.pyindex af07d8cc5574..0c448bd27f29 100644--- a/products/data_quality/backend/facade/enums.py+++ b/products/data_quality/backend/facade/enums.py@@ -75,14 +75,15 @@ class SuiteRunTrigger(StrEnum):class SubjectType(StrEnum):"""Kind of catalog object a check targets.- On the check itself the subject is a foreign key (``saved_query``, ``table``, or ``metric``);- run history denormalizes it as loose ``(subject_type, subject_uuid, name)``- tuples so it outlives hard deletes.+ On the check itself the subject is a foreign key (``saved_query``, ``table``, or ``metric``), or+ the name of a PostHog table; run history denormalizes it as loose+ ``(subject_type, subject_uuid, name)`` tuples so it outlives hard deletes."""TABLE = "table"VIEW = "view"METRIC = "metric"+ POSTHOG_TABLE = "posthog_table"class ScheduleInterval(StrEnum):diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex 06308a74f8eb..0eeb82e60ceb 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -28,7 +28,9 @@ from posthog.temporal.common.client import sync_connectfrom ..facade.contracts import CHECK_SUITE_WORKFLOW_NAMEfrom ..facade.enums import SubjectHealth, SubjectStatus, SubjectType, SuiteRunStatus, SuiteRunTriggerfrom ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from . import posthog_tablesfrom .compiler import related_subject_ref+from .contracts import SubjectReffrom .errors import (CheckConfigError,ConcurrentEditError,@@ -40,9 +42,10 @@ from .exceptions import CheckNameConflictfrom .health import CheckStatusRow, roll_up_healthfrom .registry import get_specfrom .schedules import provision_schedule-from .serialization import compute_fingerprint+from .serialization import canonical_config, compute_fingerprintfrom .spec import CheckConfig-from .subjects import resolve_subject, subject_column_type+from .subject_schedules import SCHEDULE_TYPES+from .subjects import posthog_table_column_is_selectable, resolve_subject, subject_column_type_UPSERTABLE_FIELDS = ("name",@@ -80,6 +83,11 @@ def subject_filter(subject_type: str, subject_uuid: str | UUID) -> dict[str, Anyreturn {"saved_query_id": subject_uuid}if subject_type == SubjectType.METRIC:return {"metric_id": subject_uuid}+ if subject_type == SubjectType.POSTHOG_TABLE:+ entry = posthog_tables.by_id(subject_uuid)+ if entry is None:+ raise ValueError(f"Unknown PostHog table: {subject_uuid}")+ return {"posthog_table": entry.name}raise ValueError(f"Unknown check subject type: {subject_type}")@@ -106,17 +114,37 @@ def validate_check(raise SubjectUnresolvableError(f"No {subject_type} with id {subject_uuid} in this project.")if subject.subject_type == SubjectType.METRIC and column_name:raise CheckConfigError("A check on a metric takes no column. Remove the column and save again.")+ if parsed.lookback_hours is not None and not subject.time_column:+ raise CheckConfigError(f"A {subject_type} has no time column, so it cannot take a lookback_hours window.")+ _require_selectable_posthog_column(subject, column_name)spec.referenced_table_names(parsed, subject)# After the subject resolves, so the column type is only looked up for a check that could run.parsed = spec.coerce_to_column(parsed, subject_column_type(team.id, subject_type, subject_uuid, column_name))related = related_subject_ref(check_type, config)- if related and not resolve_subject(team.id, *related).exists:- raise SubjectUnresolvableError(f"The referenced {related[0]} {related[1]} does not exist.")+ if related:+ related_subject = resolve_subject(team.id, *related)+ if not related_subject.exists:+ raise SubjectUnresolvableError(f"The referenced {related[0]} {related[1]} does not exist.")+ # Same rule as the subject's own window above, on the second subject a relationships check+ # reads. ``build`` keeps its own guard, so this is refused at authoring time rather than on+ # every run.+ if getattr(parsed, "to_lookback_hours", None) is not None and not related_subject.time_column:+ raise CheckConfigError(+ f"The referenced {related[0]} has no time column, so it cannot take a to_lookback_hours window."+ )+ _require_selectable_posthog_column(related_subject, getattr(parsed, "to_column", ""))return parsed+def _require_selectable_posthog_column(subject: SubjectRef, column_name: str) -> None:+ if subject.subject_type != SubjectType.POSTHOG_TABLE or not column_name:+ return+ if not posthog_table_column_is_selectable(subject.subject_uuid, column_name):+ raise CheckConfigError(f"{subject.name} has no column named {column_name}. Pick one of its listed columns.")++def upsert_check(*,team: Team,@@ -134,7 +162,7 @@ def upsert_check(# Stored in the same canonical form the fingerprint hashes, so a created check and one edited# into the same definition are indistinguishable afterwards.- canonical = parsed.model_dump(mode="json")+ canonical = canonical_config(parsed)fingerprint = compute_fingerprint(subject_type=subject_type,subject_uuid=str(subject_uuid),@@ -166,7 +194,7 @@ def upsert_check(**subject_filter(subject_type, subject_uuid),**fields,)- if check.subject_type == SubjectType.METRIC and check.metric_id:+ if check.subject_type in SCHEDULE_TYPES:transaction.on_commit(partial(provision_schedule, check.team_id, subject_type, str(check.subject_uuid)))@@ -312,7 +340,7 @@ def _candidate_definition(team: Team, check: DataQualityCheck, requested: dict[scolumn_name,requested.get("config", check.config) or {},)- config = parsed.model_dump(mode="json")+ config = canonical_config(parsed)return _CandidateDefinition(check_type=check_type,column_name=column_name,@@ -356,6 +384,7 @@ def live_subject_checks(checks: QuerySet[DataQualityCheck]) -> QuerySet[DataQualQ(subject_type=SubjectType.METRIC, metric_id__isnull=False)| Q(subject_type=SubjectType.VIEW, saved_query_id__isnull=False)| Q(subject_type=SubjectType.TABLE, table_id__isnull=False)+ | Q(subject_type=SubjectType.POSTHOG_TABLE, posthog_table__in=posthog_tables.names())).exclude(metric__deleted=True).exclude(saved_query__deleted=True)@@ -436,6 +465,7 @@ def start_check_suite(saved_query_ids=subject_uuids if subject_type == SubjectType.VIEW else [],table_ids=subject_uuids if subject_type == SubjectType.TABLE else [],metric_ids=subject_uuids if subject_type == SubjectType.METRIC else [],+ posthog_table_ids=subject_uuids if subject_type == SubjectType.POSTHOG_TABLE else [],check_ids=check_ids or [],suite_run_id=str(suite_run.id),created_by_id=user.id if user else None,diff --git a/products/data_quality/backend/logic/compiler.py b/products/data_quality/backend/logic/compiler.pyindex 06e9c5bc37cd..059790586ca7 100644--- a/products/data_quality/backend/logic/compiler.py+++ b/products/data_quality/backend/logic/compiler.py@@ -15,9 +15,11 @@ from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.printer import print_prepared_ast+from ..facade.enums import CheckTypefrom .contracts import CheckPlan, CompiledCheck, Evaluation, SubjectReffrom .errors import SubjectUnresolvableErrorfrom .registry import get_spec+from .types.common import narrowed_to, window_exprFAILURE_COUNT_ALIAS = "failure_count"OBSERVED_VALUE_ALIAS = "observed_value"@@ -35,7 +37,8 @@ def compile_check(raise SubjectUnresolvableError(f"The {subject.subject_type} {subject.subject_uuid} no longer resolves.")spec = get_spec(check_type)- plan = spec.build(subject, column_name, spec.validate(config, column_name), related_subject)+ parsed = spec.validate(config, column_name)+ plan = _windowed(spec.build(subject, column_name, parsed, related_subject), check_type, subject, parsed)query = _aggregate(plan)return CompiledCheck(query=query,@@ -45,6 +48,20 @@ def compile_check()+def _windowed(plan: CheckPlan, check_type: str, subject: SubjectRef, config: Any) -> CheckPlan:+ """Bound the plan's rows to the subject's lookback window, where it has one."""+ window = window_expr(subject.time_column, getattr(config, "lookback_hours", None))+ if window is None or check_type == CheckType.CUSTOM_SQL:+ return plan+ failing_rows = plan.failing_rows+ diagnostic_rows = plan.diagnostic_rows+ if isinstance(failing_rows, ast.SelectQuery):+ narrowed_to(failing_rows, window)+ if isinstance(diagnostic_rows, ast.SelectQuery):+ narrowed_to(diagnostic_rows, window)+ return plan++def _print(query: "ast.SelectQuery | ast.SelectSetQuery") -> str:# limit_top_select=False: the aggregate is a single row anyway, and the failing-rows form is# stored for a human to re-run, so a synthetic LIMIT would misrepresent what the check examined.diff --git a/products/data_quality/backend/logic/contracts.py b/products/data_quality/backend/logic/contracts.pyindex 0bc9ed0ddc2a..ca99efdc2b82 100644--- a/products/data_quality/backend/logic/contracts.py+++ b/products/data_quality/backend/logic/contracts.py@@ -38,6 +38,8 @@ class SubjectRef:``queryable_name`` is what the compiler puts in the FROM clause; it can differ from the stored``subject_name`` after a rename, which is why the runner writes it back to the check row.++ ``time_column`` is the column a lookback window bounds, or None for a subject that has none."""subject_type: SubjectType@@ -45,6 +47,7 @@ class SubjectRef:name: strqueryable_name: strexists: bool+ time_column: str | None = Nonedefinition_kind: str | None = Nonemetric_definition: "HogQLMetricDefinition | None" = Nonediff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.pyindex 5bf3b12e302d..03eb6a7ee888 100644--- a/products/data_quality/backend/logic/notifications.py+++ b/products/data_quality/backend/logic/notifications.py@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.facade import api as warehouse_facadefrom ..facade.enums import CheckRunStatus, SubjectTypefrom ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from . import posthog_tablesfrom .checks import checks_for_subjectfrom .flags import is_data_quality_checks_enabled_for_team_idfrom .subject_access import (@@ -127,6 +128,10 @@ class _WarehouseSubjectResolver(RecipientsResolver):"data_catalog", "viewer"):return False+ if self._subject_type == SubjectType.POSTHOG_TABLE and not access.check_access_level_for_resource(+ posthog_tables.RESOURCE, "viewer"+ ):+ return Falseif self._object_gate_applies() and not self._has_object_access(access):return Falseif not self._reference_gate_applies():@@ -163,6 +168,14 @@ class _WarehouseSubjectResolver(RecipientsResolver):)+def _source_url(team_id: int, subject_type: str, subject_name: str) -> str:+ if subject_type == SubjectType.METRIC:+ return f"/project/{team_id}/data-catalog/metrics/{quote(subject_name, safe='')}?tab=tests"+ if subject_type == SubjectType.POSTHOG_TABLE:+ return f"/project/{team_id}/models?tab=data-quality"+ return ""++def notify_check_started_failing(check: DataQualityCheck,failed_row_count: int | None,@@ -180,7 +193,8 @@ def notify_check_started_failing(if not subject.exists:return 0is_metric = check.subject_type == SubjectType.METRIC- subject_name = subject.name if is_metric else check.subject_name+ is_posthog_table = check.subject_type == SubjectType.POSTHOG_TABLE+ subject_name = subject.name if is_metric or is_posthog_table else check.subject_nameevent = create_notification(NotificationData(team_id=check.team_id,@@ -195,9 +209,7 @@ def notify_check_started_failing(# members with object-level access to it, plus query access for the count.resource_type="data_catalog" if is_metric else "warehouse_objects",resource_id=str(check.subject_uuid),- source_url=f"/project/{team.id}/data-catalog/metrics/{quote(subject_name, safe='')}?tab=tests"- if is_metric- else "",+ source_url=_source_url(team.id, check.subject_type, subject_name),idempotency_key=idempotency_key,resolver=_WarehouseSubjectResolver(team,diff --git a/products/data_quality/backend/logic/permissions.py b/products/data_quality/backend/logic/permissions.pyindex 0cc1ddb1c0a8..e23adfccd30d 100644--- a/products/data_quality/backend/logic/permissions.py+++ b/products/data_quality/backend/logic/permissions.py@@ -2,11 +2,14 @@ from collections.abc import Collectionfrom dataclasses import replacefrom typing import TYPE_CHECKING, Literal+from posthog.hogql.database.database import Database+from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facadefrom ..facade.enums import SubjectType-from .subject_access import DenialContext, ReadableSubjects+from . import posthog_tables+from .subject_access import DenialContext, ReadableSubjects, denial_contextif TYPE_CHECKING:from posthog.scopes import APIScopeObject@@ -17,6 +20,7 @@ _SUBJECT_RESOURCES: dict[SubjectType, "APIScopeObject"] = {SubjectType.TABLE: "warehouse_table",SubjectType.VIEW: "warehouse_view",SubjectType.METRIC: "data_catalog",+ SubjectType.POSTHOG_TABLE: posthog_tables.RESOURCE,}_WAREHOUSE_FAMILY_SCOPE = "warehouse_objects"@@ -44,7 +48,7 @@ def _scope_reaches(scopes: Collection[str] | None, kind: SubjectType, resource:def _has_subject_access(access: "UserAccessControl", kind: SubjectType, level: Literal["editor", "viewer"]) -> bool:if access.check_access_level_for_resource(_SUBJECT_RESOURCES[kind], level):return True- if access.team is None or kind == SubjectType.METRIC:+ if access.team is None or kind in (SubjectType.METRIC, SubjectType.POSTHOG_TABLE):return Falseif kind == SubjectType.TABLE:return bool(warehouse_facade.allowed_table_ids(access.team.id, access, required_level=level))@@ -71,9 +75,20 @@ def writable_subjects(metric_ids=context.readable.metric_idsif access.check_access_level_for_resource("data_catalog", "editor")else frozenset(),+ posthog_table_ids=context.readable.posthog_table_ids+ if access.check_access_level_for_resource(posthog_tables.RESOURCE, "editor")+ else frozenset(),)+def sql_denial_context(team_id: int, database: Database) -> DenialContext:+ """The denial state a HogQL query runs under, narrowed to the subject kinds its caller may read."""+ context = denial_context(team_id, database)+ access = database.user_access_control+ allowed = authorized_subject_types(access, None) if access is not None else frozenset()+ return restrict_subject_types(context, allowed)++def _scope_allows(scopes: Collection[str] | None, resource: str, write: bool) -> bool:if scopes is None or "*" in scopes or f"{resource}:write" in scopes:return True@@ -95,5 +110,8 @@ def restrict_subject_types(context: DenialContext, allowed: Collection[SubjectTytable_ids=context.readable.table_ids if SubjectType.TABLE in allowed else frozenset(),view_ids=context.readable.view_ids if SubjectType.VIEW in allowed else frozenset(),metric_ids=context.readable.metric_ids if SubjectType.METRIC in allowed else frozenset(),+ posthog_table_ids=context.readable.posthog_table_ids+ if SubjectType.POSTHOG_TABLE in allowed+ else frozenset(),),)diff --git a/products/data_quality/backend/logic/posthog_tables.py b/products/data_quality/backend/logic/posthog_tables.pynew file mode 100644index 000000000000..f697caf3b7d9--- /dev/null+++ b/products/data_quality/backend/logic/posthog_tables.py@@ -0,0 +1,99 @@+"""The PostHog tables a check can be authored on, each with a deterministic id from its name."""++from collections.abc import Callable, Collection+from uuid import NAMESPACE_URL, UUID, uuid5++from posthog.schema import DatabaseSerializedFieldType++from posthog.hogql.database.models import (+ BooleanDatabaseField,+ DatabaseField,+ DateDatabaseField,+ DateTimeDatabaseField,+ ExpressionField,+ FloatDatabaseField,+ IntegerDatabaseField,+ StringArrayDatabaseField,+ StringJSONDatabaseField,+ Table,+)+from posthog.hogql.database.schema.events import EventsTable+from posthog.hogql.database.schema.groups import GroupsTable+from posthog.hogql.database.schema.persons import PersonsTable++from posthog.dataclasses import frozen+from posthog.scopes import APIScopeObject++_SUBJECT_NAMESPACE = "data-quality-posthog-table:"+RESOURCE: APIScopeObject = "warehouse_table"++_FIELD_TYPES: list[tuple[type, DatabaseSerializedFieldType]] = [+ (IntegerDatabaseField, DatabaseSerializedFieldType.INTEGER),+ (FloatDatabaseField, DatabaseSerializedFieldType.FLOAT),+ (StringJSONDatabaseField, DatabaseSerializedFieldType.JSON),+ (StringArrayDatabaseField, DatabaseSerializedFieldType.ARRAY),+ (DateTimeDatabaseField, DatabaseSerializedFieldType.DATETIME),+ (DateDatabaseField, DatabaseSerializedFieldType.DATE),+ (BooleanDatabaseField, DatabaseSerializedFieldType.BOOLEAN),+ (ExpressionField, DatabaseSerializedFieldType.EXPRESSION),+ (DatabaseField, DatabaseSerializedFieldType.STRING),+]+++@frozen+class PostHogTable:+ name: str+ time_column: str+ table_class: Callable[[], Table]++ @property+ def id(self) -> UUID:+ return uuid5(NAMESPACE_URL, f"{_SUBJECT_NAMESPACE}{self.name}")++ @property+ def columns(self) -> dict[str, str]:+ return {+ name: _field_type(field)+ for name, field in self.table_class().fields.items()+ if isinstance(field, DatabaseField) and not field.hidden+ }+++TABLES: tuple[PostHogTable, ...] = (+ PostHogTable(name="events", time_column="timestamp", table_class=EventsTable),+ PostHogTable(name="persons", time_column="created_at", table_class=PersonsTable),+ PostHogTable(name="groups", time_column="created_at", table_class=GroupsTable),+)++_BY_NAME = {table.name: table for table in TABLES}+_BY_ID = {table.id: table for table in TABLES}+++def by_name(name: str) -> PostHogTable | None:+ return _BY_NAME.get(name)+++def by_id(subject_uuid: str | UUID) -> PostHogTable | None:+ try:+ return _BY_ID.get(UUID(str(subject_uuid)))+ except ValueError:+ return None+++def all_ids() -> frozenset[UUID]:+ return frozenset(_BY_ID)+++def names_of(ids: Collection[UUID]) -> list[str]:+ return [entry.name for entry in TABLES if entry.id in ids]+++def names() -> tuple[str, ...]:+ return tuple(_BY_NAME)+++def _field_type(field: object) -> str:+ for field_class, serialized in _FIELD_TYPES:+ if isinstance(field, field_class):+ return serialized.value+ return DatabaseSerializedFieldType.UNKNOWN.valuediff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex 52cfb397a45b..fd0fd5c18811 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Anyfrom django.db import transactionfrom posthog.hogql.context import HogQLContext+from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.query import execute_hogql_queryif TYPE_CHECKING:@@ -129,10 +130,10 @@ def _authorize(check: DataQualityCheck, suite_run: DataQualitySuiteRun) -> _Authauthorize against, returning ``None`` errors the run rather than bypassing the ACL."""if suite_run.trigger == SuiteRunTrigger.MANUAL:- if suite_run.created_by is None and check_type_reads_beyond_subject(check.check_type):+ if suite_run.created_by is None and _needs_a_principal(check):return Nonereturn _Authorization(run_as=suite_run.created_by, bypass=suite_run.created_by is None)- if not check_type_reads_beyond_subject(check.check_type):+ if not _needs_a_principal(check):return _Authorization(run_as=None, bypass=True)principal = check.definition_author or check.created_byif principal is None:@@ -140,6 +141,11 @@ def _authorize(check: DataQualityCheck, suite_run: DataQualitySuiteRun) -> _Authreturn _Authorization(run_as=principal, bypass=False)+def _needs_a_principal(check: DataQualityCheck) -> bool:+ """Whether the run must execute as a user rather than under the service bypass."""+ return check_type_reads_beyond_subject(check.check_type) or check.subject_type == SubjectType.POSTHOG_TABLE++def _staged_database(team: Team,staged: StagedSubjectOverride,@@ -251,15 +257,18 @@ def _execute_compiled(# service-level bypass is only used where there is no actor and the query is constrained to# the check's declared subject, so it can't reach a warehouse object the definition doesn't# already name.+ modifiers = create_default_modifiers_for_team(team)if database is not None:response = execute_hogql_query(query=compiled.query,team=team,query_type=QUERY_TYPE,+ modifiers=modifiers,context=HogQLContext(team_id=team.pk,user=authorization.run_as,database=database,+ modifiers=modifiers,bypass_warehouse_access_control=authorization.bypass,),)@@ -269,6 +278,7 @@ def _execute_compiled(team=team,query_type=QUERY_TYPE,user=authorization.run_as,+ modifiers=modifiers,bypass_warehouse_access_control=authorization.bypass,)return _interpret(compiled, check.config, response.results, response.columns or [])diff --git a/products/data_quality/backend/logic/serialization.py b/products/data_quality/backend/logic/serialization.pyindex f6e1c8593d12..49a5d48a25e3 100644--- a/products/data_quality/backend/logic/serialization.py+++ b/products/data_quality/backend/logic/serialization.py@@ -52,6 +52,24 @@ def from_config_entry(entry: dict[str, Any]) -> dict[str, Any]:return CheckConfigEntry.model_validate(entry).model_dump()+# Every field a check can leave unset because it was added after checks existed. A type that carries+# one dumps it as null, and a null the older row never stored would change its fingerprint.+_LATE_OPTIONAL_FIELDS = ("lookback_hours", "to_lookback_hours")+++def canonical_config(parsed: BaseModel) -> dict[str, Any]:+ """The config as it is stored and hashed.++ An unset lookback window is dropped rather than written as null, so a check authored before the+ window existed keeps the fingerprint it already has.+ """+ canonical = parsed.model_dump(mode="json")+ for name in _LATE_OPTIONAL_FIELDS:+ if canonical.get(name) is None:+ canonical.pop(name, None)+ return canonical++def compute_fingerprint(*,subject_type: str,diff --git a/products/data_quality/backend/logic/spec.py b/products/data_quality/backend/logic/spec.pyindex a71a8935b9ad..f7113ec2bee3 100644--- a/products/data_quality/backend/logic/spec.py+++ b/products/data_quality/backend/logic/spec.py@@ -11,7 +11,7 @@ Adding anomaly detection or unit tests later means adding a spec, not migratingfrom abc import ABC, abstractmethodfrom typing import Any, ClassVar-from pydantic import BaseModel, ConfigDict, ValidationError+from pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom ..facade.enums import CheckType, SubjectTypefrom .contracts import CheckPlan, SubjectRef@@ -23,6 +23,15 @@ class CheckConfig(BaseModel):model_config = ConfigDict(extra="forbid")+ lookback_hours: int | None = Field(+ default=None,+ ge=1,+ description=(+ "Only examine rows from the last N hours, by the subject's time column. Optional, and "+ "only for a subject that has one. Without it the check reads the whole table."+ ),+ )+class NoConfig(CheckConfig):"""For types whose column is the whole configuration."""@@ -39,7 +48,9 @@ class CheckTypeSpec(ABC):config_model: ClassVar[type[CheckConfig]]requires_column: ClassVar[bool]description: ClassVar[str]- subject_types: ClassVar[frozenset[SubjectType]] = frozenset({SubjectType.TABLE, SubjectType.VIEW})+ subject_types: ClassVar[frozenset[SubjectType]] = frozenset(+ {SubjectType.TABLE, SubjectType.VIEW, SubjectType.POSTHOG_TABLE}+ )reads_beyond_subject: ClassVar[bool] = False@propertydiff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex c4a3a1001b39..e14c6dfb581a 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.facade import api as warehouse_facadefrom ..facade.enums import SubjectTypefrom ..models import DataQualityCheck, DataQualityCheckRun+from . import posthog_tablesfrom .checks import latest_run_idsfrom .contracts import SubjectIdentity, SubjectReffrom .exceptions import SubjectAccessUnverifiable@@ -52,7 +53,16 @@ _SUBJECT_UUID_KEY = "subject_uuid"_SYSTEM_SCHEMA = SystemTables().name_RunQS = TypeVar("_RunQS", bound=QuerySet)_CHECK_VISIBILITY_BATCH_SIZE = 200-_CHECK_VISIBILITY_FIELDS = ("id", "subject_type", "table_id", "saved_query_id", "metric_id", "check_type", "config")+_CHECK_VISIBILITY_FIELDS = (+ "id",+ "subject_type",+ "table_id",+ "saved_query_id",+ "metric_id",+ "posthog_table",+ "check_type",+ "config",+)def can_be_object_denied(user_access_control: Optional["UserAccessControl"]) -> bool:@@ -83,6 +93,7 @@ class ReadableSubjects:table_ids: frozenset[UUID]view_ids: frozenset[UUID]metric_ids: frozenset[UUID] = frozenset()+ posthog_table_ids: frozenset[UUID] = frozenset()def contains(self, subject_type: str, subject_uuid: str | UUID | None) -> bool:if subject_uuid is None:@@ -97,6 +108,8 @@ class ReadableSubjects:return identifier in self.view_idsif subject_type == SubjectType.METRIC:return identifier in self.metric_ids+ if subject_type == SubjectType.POSTHOG_TABLE:+ return identifier in self.posthog_table_idsreturn False@@ -223,6 +236,7 @@ def reference_gate(# left out of the lookup and fails closed in ``ReadableSubjects.contains``.if reference.subject_type in referenced and (identifier := _as_uuid(reference.subject_uuid)) is not None:referenced[reference.subject_type].add(identifier)+ matcher = DeniedTableMatcher(system_table_denials(team, user, user_access_control, unentitled=unentitled))return ReferenceGate(readable=ReadableSubjects(table_ids=warehouse_facade.allowed_table_ids(@@ -231,11 +245,20 @@ def reference_gate(view_ids=data_modeling_facade.allowed_saved_query_ids(team.id, user_access_control, ids=referenced[SubjectType.VIEW]),+ posthog_table_ids=readable_posthog_table_ids(user_access_control, matcher),),- matcher=DeniedTableMatcher(system_table_denials(team, user, user_access_control, unentitled=unentitled)),+ matcher=matcher,)+def readable_posthog_table_ids(+ user_access_control: "UserAccessControl", matcher: DeniedTableMatcher+) -> frozenset[UUID]:+ if not user_access_control.check_access_level_for_resource(posthog_tables.RESOURCE, "viewer"):+ return frozenset()+ return frozenset(entry.id for entry in posthog_tables.TABLES if not matcher.matches([entry.name]))++@frozenclass SubjectMetadata:"""The team's live subjects by id. ``table_keys`` is the dotted form a query writes."""@@ -282,6 +305,7 @@ def readable_subjects(for metric in metadata.metricsif can_read_catalog and not matcher.matches(metric.referenced_table_names)),+ posthog_table_ids=frozenset(entry.id for entry in posthog_tables.TABLES if not matcher.matches([entry.name])),)@@ -485,6 +509,10 @@ def readable_check_subjects(Q(subject_type=SubjectType.TABLE, table_id__in=readable.table_ids)| Q(subject_type=SubjectType.VIEW, saved_query_id__in=readable.view_ids)| Q(subject_type=SubjectType.METRIC, metric_id__in=readable.metric_ids)+ | Q(+ subject_type=SubjectType.POSTHOG_TABLE,+ posthog_table__in=posthog_tables.names_of(readable.posthog_table_ids),+ ))@@ -661,6 +689,7 @@ def _readable_subject_q(readable: ReadableSubjects) -> Q:Q(subject_type=SubjectType.TABLE, subject_uuid__in=readable.table_ids)| Q(subject_type=SubjectType.VIEW, subject_uuid__in=readable.view_ids)| Q(subject_type=SubjectType.METRIC, subject_uuid__in=readable.metric_ids)+ | Q(subject_type=SubjectType.POSTHOG_TABLE, subject_uuid__in=readable.posthog_table_ids))@@ -671,6 +700,7 @@ def _readable_identities(readable: ReadableSubjects) -> list[dict[str, str]]:(SubjectType.TABLE, readable.table_ids),(SubjectType.VIEW, readable.view_ids),(SubjectType.METRIC, readable.metric_ids),+ (SubjectType.POSTHOG_TABLE, readable.posthog_table_ids),)for subject_uuid in ids]diff --git a/products/data_quality/backend/logic/subject_schedules.py b/products/data_quality/backend/logic/subject_schedules.pyindex 5631a65fe7ac..0c130032c166 100644--- a/products/data_quality/backend/logic/subject_schedules.py+++ b/products/data_quality/backend/logic/subject_schedules.py@@ -27,7 +27,10 @@ from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY,from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME, RunCheckSuiteInputsfrom ..facade.enums import ScheduleInterval, SubjectType, SuiteRunTrigger-SCHEDULE_TYPES: dict[SubjectType, str] = {SubjectType.METRIC: "data-quality-metric"}+SCHEDULE_TYPES: dict[SubjectType, str] = {+ SubjectType.METRIC: "data-quality-metric",+ SubjectType.POSTHOG_TABLE: "data-quality-posthog-table",+}SCHEDULE_TYPE_SUBJECTS = {schedule_type: kind for kind, schedule_type in SCHEDULE_TYPES.items()}@@ -86,6 +89,13 @@ def suite_inputs(key: SubjectScheduleKey) -> RunCheckSuiteInputs:metric_ids=[str(key.subject_uuid)],schedule_id=key.temporal_id,)+ if key.subject_type is SubjectType.POSTHOG_TABLE:+ return RunCheckSuiteInputs(+ team_id=key.team_id,+ trigger=SuiteRunTrigger.SCHEDULED,+ posthog_table_ids=[str(key.subject_uuid)],+ schedule_id=key.temporal_id,+ )raise ValueError(f"A {key.subject_type} has no recurring check schedule")@@ -93,6 +103,8 @@ def selected_subject_ids(inputs: RunCheckSuiteInputs, subject_type: SubjectType)"""The subjects these inputs name, read out of the selector that kind uses."""if subject_type is SubjectType.METRIC:return inputs.metric_ids+ if subject_type is SubjectType.POSTHOG_TABLE:+ return inputs.posthog_table_idsraise ValueError(f"A {subject_type} has no recurring check schedule")diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.pyindex f7843136bd30..6dedaf6d7875 100644--- a/products/data_quality/backend/logic/subjects.py+++ b/products/data_quality/backend/logic/subjects.py@@ -9,6 +9,8 @@ denormalized name is refreshed on every run so renames self-heal.from collections.abc import Collectionfrom uuid import UUID+from posthog.schema import DatabaseSerializedFieldType+from products.data_catalog.backend.facade import api as data_catalog_facadefrom products.data_catalog.backend.facade.enums import HOGQL_DEFINITION_KINDfrom products.data_modeling.backend.facade import api as data_modeling_facade@@ -17,6 +19,7 @@ from products.warehouse_sources.backend.facade.contracts import WAREHOUSE_OBJECTfrom ..facade.contracts import MetricSubject, SelectableSubjectfrom ..facade.enums import SubjectType+from . import posthog_tablesfrom .contracts import SubjectRef_WAREHOUSE_OBJECT_SUBJECT_TYPES = {@@ -32,9 +35,25 @@ def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -return _resolve_table(team_id, subject_uuid)if kind is SubjectType.METRIC:return _resolve_metric(team_id, subject_uuid)+ if kind is SubjectType.POSTHOG_TABLE:+ return _resolve_posthog_table(subject_uuid)return _resolve_view(team_id, subject_uuid)+def _resolve_posthog_table(subject_uuid: str | UUID) -> SubjectRef:+ entry = posthog_tables.by_id(subject_uuid)+ if entry is None:+ return _missing(SubjectType.POSTHOG_TABLE, subject_uuid)+ return SubjectRef(+ subject_type=SubjectType.POSTHOG_TABLE,+ subject_uuid=str(entry.id),+ name=entry.name,+ queryable_name=entry.name,+ exists=True,+ time_column=entry.time_column,+ )++def unqueryable_table_ids(team_id: int) -> set[UUID]:"""The tables the normal HogQL database leaves out, so no check should name one.@@ -77,6 +96,16 @@ def selectable_subjects(team_id: int, kinds: Collection[SubjectType]) -> list[Se)for saved_query_id, name in data_modeling_facade.all_saved_query_names(team_id).items())+ if SubjectType.POSTHOG_TABLE in kinds:+ subjects.extend(+ SelectableSubject(+ subject_type=SubjectType.POSTHOG_TABLE,+ id=str(entry.id),+ name=entry.name,+ columns=entry.columns,+ )+ for entry in posthog_tables.TABLES+ )if SubjectType.METRIC in kinds:subjects.extend(SelectableSubject(@@ -178,6 +207,9 @@ def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUIkind = SubjectType(subject_type)if kind is SubjectType.METRIC:return None+ if kind is SubjectType.POSTHOG_TABLE:+ entry = posthog_tables.by_id(subject_uuid)+ return entry.columns.get(column_name) if entry else Noneif kind is SubjectType.TABLE:table_id = UUID(str(subject_uuid))columns = warehouse_facade.all_queryable_table_columns(team_id, {table_id}).get(table_id, {})@@ -186,6 +218,18 @@ def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUIreturn columns.get(column_name)+def posthog_table_column_is_selectable(subject_uuid: str | UUID, column_name: str) -> bool:+ """Whether the column is one the registry lists, or a path into one of its JSON columns."""+ entry = posthog_tables.by_id(subject_uuid)+ if entry is None:+ return False+ head, _, tail = column_name.partition(".")+ column_type = entry.columns.get(head)+ if column_type is None:+ return False+ return not tail or column_type == DatabaseSerializedFieldType.JSON.value++def _missing(kind: SubjectType, subject_uuid: str | UUID) -> SubjectRef:return SubjectRef(subject_type=kind,diff --git a/products/data_quality/backend/logic/types/accepted_values.py b/products/data_quality/backend/logic/types/accepted_values.pyindex 9c724487e22c..d347adbde85d 100644--- a/products/data_quality/backend/logic/types/accepted_values.py+++ b/products/data_quality/backend/logic/types/accepted_values.py@@ -107,7 +107,11 @@ class AcceptedValuesSpec(CheckTypeSpec):if not column_type:return configbare = _unwrap_type(column_type)- return AcceptedValuesConfig(values=[_coerce_value(value, bare) for value in config.values])+ # Rebuilt over the whole config, not from the values alone: the model is constructed so the+ # set validator re-runs -- coercion can make two values equal -- and the dump carries the+ # base fields across, so a lookback window survives.+ coerced = {**config.model_dump(), "values": [_coerce_value(value, bare) for value in config.values]}+ return AcceptedValuesConfig(**coerced)def build(self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = Nonediff --git a/products/data_quality/backend/logic/types/common.py b/products/data_quality/backend/logic/types/common.pyindex 227de0642a06..e8a17a2e151e 100644--- a/products/data_quality/backend/logic/types/common.py+++ b/products/data_quality/backend/logic/types/common.py@@ -47,6 +47,29 @@ def subject_source(subject: SubjectRef) -> ast.JoinExpr:return ast.JoinExpr(table=ast.Field(chain=list(subject.queryable_name.split("."))))+def window_expr(time_column: str | None, lookback_hours: int | None) -> ast.Expr | None:+ """Rows newer than the lookback, or None when either half of the window is missing."""+ if not time_column or not lookback_hours:+ return None+ return ast.CompareOperation(+ left=column(time_column),+ op=ast.CompareOperationOp.GtEq,+ right=ast.ArithmeticOperation(+ left=ast.Call(name="now", args=[]),+ op=ast.ArithmeticOperationOp.Sub,+ right=ast.Call(name="toIntervalHour", args=[ast.Constant(value=lookback_hours)]),+ ),+ )+++def narrowed_to(query: ast.SelectQuery, window: ast.Expr | None) -> ast.SelectQuery:+ """The same query, bounded by the window. The table stays bare in FROM so lazy joins still compile."""+ if window is None:+ return query+ query.where = ast.And(exprs=[query.where, window]) if query.where else window+ return query++def column(column_name: str) -> ast.Field:return ast.Field(chain=list(column_name.split(".")))diff --git a/products/data_quality/backend/logic/types/custom_sql.py b/products/data_quality/backend/logic/types/custom_sql.pyindex e8c748208b72..cb2923ac66ae 100644--- a/products/data_quality/backend/logic/types/custom_sql.py+++ b/products/data_quality/backend/logic/types/custom_sql.py@@ -45,6 +45,7 @@ def build_failing_rows(subject: SubjectRef | None, config: "CustomSqlConfig") ->class CustomSqlConfig(CheckConfig):+ lookback_hours: None = Field(default=None, exclude=True, json_schema_extra={"readOnly": True})query: str = Field(min_length=1,description=(@@ -68,7 +69,7 @@ class CustomSqlSpec(CheckTypeSpec):type_name = CheckType.CUSTOM_SQLconfig_model = CustomSqlConfigrequires_column = False- subject_types = frozenset({SubjectType.TABLE, SubjectType.VIEW, SubjectType.METRIC})+ subject_types = frozenset({SubjectType.TABLE, SubjectType.VIEW, SubjectType.METRIC, SubjectType.POSTHOG_TABLE})reads_beyond_subject = Truedescription = "Fails on every row the custom HogQL SELECT returns. Metric checks query the {metric} relation."diff --git a/products/data_quality/backend/logic/types/relationships.py b/products/data_quality/backend/logic/types/relationships.pyindex 91c4ed1ca738..8c1f9c42e2c6 100644--- a/products/data_quality/backend/logic/types/relationships.py+++ b/products/data_quality/backend/logic/types/relationships.py@@ -7,17 +7,25 @@ from posthog.hogql import astfrom ...facade.enums import CheckType, SubjectTypefrom ..contracts import CheckPlan, SubjectRef-from ..errors import SubjectUnresolvableError+from ..errors import CheckConfigError, SubjectUnresolvableErrorfrom ..spec import CheckConfig, CheckTypeSpec-from .common import column, diagnostic_of, one, subject_source+from .common import column, diagnostic_of, narrowed_to, one, subject_source, window_exprclass RelationshipsConfig(CheckConfig):- to_subject_type: Literal[SubjectType.TABLE, SubjectType.VIEW] = Field(- description="Kind of catalog object holding the referenced values."+ to_subject_type: Literal[SubjectType.TABLE, SubjectType.VIEW, SubjectType.POSTHOG_TABLE] = Field(+ description="Kind of object holding the referenced values.")- to_subject_uuid: UUID = Field(description="Id of the table or view holding the referenced values.")+ to_subject_uuid: UUID = Field(description="Id of the table, view or PostHog table holding the referenced values.")to_column: str = Field(min_length=1, description="Column holding the referenced values.")+ to_lookback_hours: int | None = Field(+ default=None,+ ge=1,+ description=(+ "Only look for a match among the referenced subject's rows from the last N hours. "+ "Optional, and only for a referenced subject with a time column."+ ),+ )class RelationshipsSpec(CheckTypeSpec):@@ -40,10 +48,15 @@ class RelationshipsSpec(CheckTypeSpec):raise SubjectUnresolvableError(f"The referenced {config.to_subject_type} {config.to_subject_uuid} no longer resolves.")+ if config.to_lookback_hours is not None and not related.time_column:+ raise CheckConfigError(+ f"The referenced {config.to_subject_type} has no time column, "+ "so it cannot take a to_lookback_hours window."+ )value = column(column_name)- referenced = ast.SelectQuery(- select=[column(config.to_column)],- select_from=subject_source(related),+ referenced = narrowed_to(+ ast.SelectQuery(select=[column(config.to_column)], select_from=subject_source(related)),+ window_expr(related.time_column, config.to_lookback_hours),)failing_rows = ast.SelectQuery(select=[one()],diff --git a/products/data_quality/backend/migrations/0012_posthog_table_subject.py b/products/data_quality/backend/migrations/0012_posthog_table_subject.pynew file mode 100644index 000000000000..0ae4b08b8128--- /dev/null+++ b/products/data_quality/backend/migrations/0012_posthog_table_subject.py@@ -0,0 +1,107 @@+# Generated by Django 5.2.17 on 2026-09-17 16:33++from django.db import migrations, models++from posthog.migration_helpers import AddConstraintNotValid++import products.data_quality.backend.facade.enums+++class Migration(migrations.Migration):+ dependencies = [("data_quality", "0011_metric_subject_index")]++ operations = [+ migrations.AddField(+ model_name="dataqualitycheck",+ name="posthog_table",+ field=models.CharField(+ blank=True,+ default="",+ help_text="Name of the PostHog table this check audits, such as events. "+ "Exclusive with every subject FK.",+ max_length=64,+ ),+ ),+ migrations.AlterField(+ model_name="dataqualitycheck",+ name="subject_type",+ field=models.CharField(+ choices=products.data_quality.backend.facade.enums.subject_type_choices,+ help_text="Kind of object being checked: table, view, metric, or posthog_table. "+ "Kept so orphaned checks stay readable.",+ max_length=32,+ ),+ ),+ migrations.RemoveConstraint(+ model_name="dataqualitycheck",+ name="quality_check_subject_binding",+ ),+ AddConstraintNotValid(+ model_name="dataqualitycheck",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("saved_query__isnull", False),+ ("table__isnull", False),+ _negated=True,+ ),+ models.Q(+ ("metric__isnull", False),+ ("saved_query__isnull", False),+ _negated=True,+ ),+ models.Q(+ ("metric__isnull", False),+ ("table__isnull", False),+ _negated=True,+ ),+ models.Q(+ ("saved_query__isnull", True),+ (+ "subject_type",+ products.data_quality.backend.facade.enums.SubjectType["VIEW"],+ ),+ _connector="OR",+ ),+ models.Q(+ ("table__isnull", True),+ (+ "subject_type",+ products.data_quality.backend.facade.enums.SubjectType["TABLE"],+ ),+ _connector="OR",+ ),+ models.Q(+ ("metric__isnull", True),+ (+ "subject_type",+ products.data_quality.backend.facade.enums.SubjectType["METRIC"],+ ),+ _connector="OR",+ ),+ models.Q(+ ("posthog_table", ""),+ models.Q(+ ("metric__isnull", True),+ ("saved_query__isnull", True),+ (+ "subject_type",+ products.data_quality.backend.facade.enums.SubjectType["POSTHOG_TABLE"],+ ),+ ("table__isnull", True),+ ),+ _connector="OR",+ ),+ models.Q(+ ("posthog_table", ""),+ (+ "subject_type",+ products.data_quality.backend.facade.enums.SubjectType["POSTHOG_TABLE"],+ ),+ _negated=True,+ ),+ ),+ name="quality_check_subject_binding",+ ),+ ),+ ]diff --git a/products/data_quality/backend/migrations/0013_posthog_table_indexes.py b/products/data_quality/backend/migrations/0013_posthog_table_indexes.pynew file mode 100644index 000000000000..9d6337f3b18d--- /dev/null+++ b/products/data_quality/backend/migrations/0013_posthog_table_indexes.py@@ -0,0 +1,42 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently, SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [("data_quality", "0012_posthog_table_subject")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="dataqualitycheck",+ index=models.Index(+ fields=["team", "posthog_table"],+ condition=~models.Q(posthog_table=""),+ name="quality_check_ph_table_idx",+ ),+ ),+ migrations.SeparateDatabaseAndState(+ database_operations=[+ CreateIndexConcurrently(+ index_name="unique_quality_check_fp_posthog_table",+ table_name="data_quality_dataqualitycheck",+ columns="(team_id, posthog_table, fingerprint)",+ unique=True,+ where="WHERE posthog_table <> '' AND (NOT deleted OR deleted IS NULL)",+ ),+ ],+ state_operations=[+ migrations.AddConstraint(+ model_name="dataqualitycheck",+ constraint=models.UniqueConstraint(+ condition=~models.Q(posthog_table="")+ & (models.Q(deleted=False) | models.Q(deleted__isnull=True)),+ fields=("team", "posthog_table", "fingerprint"),+ name="unique_quality_check_fp_posthog_table",+ ),+ ),+ ],+ ),+ ]diff --git a/products/data_quality/backend/migrations/0014_validate_posthog_table_binding.py b/products/data_quality/backend/migrations/0014_validate_posthog_table_binding.pynew file mode 100644index 000000000000..08ff56d891d6--- /dev/null+++ b/products/data_quality/backend/migrations/0014_validate_posthog_table_binding.py@@ -0,0 +1,9 @@+from django.db import migrations++from posthog.migration_helpers import ValidateConstraint+++class Migration(migrations.Migration):+ dependencies = [("data_quality", "0013_posthog_table_indexes")]++ operations = [ValidateConstraint(model_name="dataqualitycheck", name="quality_check_subject_binding")]diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txtindex 9cd67febbe12..6e44e5a4dc7a 100644--- a/products/data_quality/backend/migrations/max_migration.txt+++ b/products/data_quality/backend/migrations/max_migration.txt@@ -1 +1 @@-0011_metric_subject_index+0014_validate_posthog_table_bindingdiff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.pyindex 0cce5af7dabe..a611c11f5bd3 100644--- a/products/data_quality/backend/models/check.py+++ b/products/data_quality/backend/models/check.py@@ -118,7 +118,8 @@ class DataQualityCheck(subject_type = models.CharField(max_length=32,choices=subject_type_choices,- help_text="Kind of catalog object being checked: table, view, or metric. Kept so orphaned checks stay readable.",+ help_text="Kind of object being checked: table, view, metric, or posthog_table. "+ "Kept so orphaned checks stay readable.",)saved_query = models.ForeignKey("data_modeling.DataWarehouseSavedQuery",@@ -148,6 +149,12 @@ class DataQualityCheck(related_name="+",help_text="The data catalog metric this check evaluates. Exclusive with table and saved_query.",)+ posthog_table = models.CharField(+ max_length=64,+ blank=True,+ default="",+ help_text="Name of the PostHog table this check audits, such as events. Exclusive with every subject FK.",+ )subject_name = models.CharField(max_length=400,help_text="Queryable name of the subject, refreshed on every run so renames self-heal.",@@ -232,6 +239,16 @@ class DataQualityCheck(& (models.Q(saved_query__isnull=True) | models.Q(subject_type=SubjectType.VIEW))& (models.Q(table__isnull=True) | models.Q(subject_type=SubjectType.TABLE))& (models.Q(metric__isnull=True) | models.Q(subject_type=SubjectType.METRIC))+ & (+ models.Q(posthog_table="")+ | models.Q(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query__isnull=True,+ table__isnull=True,+ metric__isnull=True,+ )+ )+ & ~models.Q(subject_type=SubjectType.POSTHOG_TABLE, posthog_table="")),),# Partial per FK: orphaned checks (both FKs null) are exempt on purpose, and so are@@ -252,6 +269,11 @@ class DataQualityCheck(condition=models.Q(metric__isnull=False) & ACTIVE,name="unique_quality_check_fp_metric",),+ models.UniqueConstraint(+ fields=["team", "posthog_table", "fingerprint"],+ condition=~models.Q(posthog_table="") & ACTIVE,+ name="unique_quality_check_fp_posthog_table",+ ),# Partial on both counts: a blank name is the "address me by id" case, which many checks# share, and a deleted check keeps its name only as history -- holding the name against a# new check would make a delete irreversible for anyone who wants that name back.@@ -277,11 +299,21 @@ class DataQualityCheck(condition=models.Q(table__isnull=False),name="quality_check_table_idx",),+ models.Index(+ fields=["team", "posthog_table"],+ condition=~models.Q(posthog_table=""),+ name="quality_check_ph_table_idx",+ ),]@propertydef subject_uuid(self) -> "uuid.UUID | None":- """Id of whichever subject FK is set; None once orphaned."""+ """Id of whichever subject this check has; None once orphaned."""+ if self.posthog_table:+ from ..logic.posthog_tables import by_name # noqa: PLC0415 — keeps HogQL off the model import path++ entry = by_name(self.posthog_table)+ return entry.id if entry else Nonereturn self.saved_query_id or self.table_id or self.metric_iddef __str__(self) -> str:diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex b8305b2070c1..5cf378bbd5fa 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -35,9 +35,9 @@ class DataQualitySubjectRefSerializer(serializers.Serializer):subject_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in SubjectType],- help_text="Kind of catalog object: 'table', 'view', or 'metric'.",+ help_text="Kind of object: 'table', 'view', 'metric', or 'posthog_table'.",)- subject_uuid = serializers.UUIDField(help_text="Id of the table, view, or metric.")+ subject_uuid = serializers.UUIDField(help_text="Id of the table, view, metric, or PostHog table.")@extend_schema_serializer(component_name="DataQualitySubject")@@ -46,7 +46,8 @@ class DataQualitySubjectSerializer(serializers.Serializer):subject_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in SubjectType],- help_text="Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.",+ help_text="Kind of object: 'table', 'view', 'metric', or 'posthog_table'. "+ "Pass it back as subject_type when creating a check.",)id = serializers.CharField(help_text="Id of the subject. Pass it back as subject_uuid when creating a check.")name = serializers.CharField(help_text="Queryable name of the subject.")@@ -82,12 +83,12 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):subject_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in SubjectType],read_only=True,- help_text="Kind of catalog object being checked: 'table', 'view', or 'metric'.",+ help_text="Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.",)subject_uuid = serializers.UUIDField(read_only=True,allow_null=True,- help_text="Id of the table, view, or metric being checked. Null once the subject is deleted.",+ help_text="Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.",)check_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in CheckType],@@ -251,9 +252,9 @@ class DataQualityCheckCreateSerializer(DataQualityCheckSerializer):subject_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in SubjectType],- help_text="Kind of catalog object to check: 'table', 'view', or 'metric'.",+ help_text="Kind of object to check: 'table', 'view', 'metric', or 'posthog_table'.",)- subject_uuid = serializers.UUIDField(help_text="Id of the table, view, or metric to check.")+ subject_uuid = serializers.UUIDField(help_text="Id of the table, view, metric, or PostHog table to check.")@extend_schema_serializer(component_name="DataQualityOverviewCheck")@@ -420,8 +421,8 @@ class DataQualitySuiteRunSerializer(serializers.ModelSerializer):)trigger = serializers.CharField(read_only=True, help_text="manual, materialization, source_sync, or scheduled.")subject_type = serializers.SerializerMethodField(- help_text="'table', 'view', or 'metric' when the run targets exactly one subject, including a run of a "- "single check on that subject; null for a run spanning several subjects."+ help_text="'table', 'view', 'metric', or 'posthog_table' when the run targets exactly one subject, "+ "including a run of a single check on that subject; null for a run spanning several subjects.")@extend_schema_field(serializers.CharField(allow_null=True))@@ -455,8 +456,8 @@ class DataQualitySuiteRunSerializer(serializers.ModelSerializer):class SubjectHealthSerializer(serializers.Serializer):"""Per-subject rollup, the same rule the information_schema.data_quality_health table uses."""- subject_type = serializers.CharField(help_text="'table', 'view', or 'metric'.")- subject_uuid = serializers.CharField(help_text="Id of the table, view, or metric.")+ subject_type = serializers.CharField(help_text="'table', 'view', 'metric', or 'posthog_table'.")+ subject_uuid = serializers.CharField(help_text="Id of the table, view, metric, or PostHog table.")health = serializers.CharField(help_text="failing (an error-severity check failed), erroring (a check could not run), ""warn (only warn-severity failures), healthy, or unknown (nothing has run yet)."diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex 28c521ec4deb..9ca3fa21c2c8 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -329,13 +329,13 @@ _SUBJECT_TYPE_PARAMETER = OpenApiParameter(OpenApiTypes.STR,OpenApiParameter.QUERY,enum=[kind.value for kind in SubjectType],- description="Kind of catalog object: 'table', 'view', or 'metric'.",+ description="Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.",)_SUBJECT_UUID_PARAMETER = OpenApiParameter("subject_uuid",OpenApiTypes.UUID,OpenApiParameter.QUERY,- description="Id of the table, view, or metric.",+ description="Id of the table, view, metric, or PostHog table.",)_SUBJECT_PARAMETERS = [_SUBJECT_TYPE_PARAMETER, _SUBJECT_UUID_PARAMETER]# A listing filter can be left out; a lookup cannot answer without a subject at all, so the actionsdiff --git a/products/data_quality/backend/temporal/activities/cleanup.py b/products/data_quality/backend/temporal/activities/cleanup.pyindex eb8b48f3ad58..0d47bbd38acf 100644--- a/products/data_quality/backend/temporal/activities/cleanup.py+++ b/products/data_quality/backend/temporal/activities/cleanup.py@@ -1,5 +1,5 @@from collections import defaultdict-from collections.abc import Iterable+from collections.abc import Collection, Iterablefrom datetime import UTC, datetime, timedeltafrom typing import Anyfrom uuid import UUID@@ -19,6 +19,7 @@ from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facadefrom ...facade.enums import SubjectType, SuiteRunStatus+from ...logic import posthog_tablesfrom ...models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom ..contracts import CleanupOutcome@@ -33,6 +34,8 @@ RETENTION_DELETE_BATCH_SIZE = 1_000# A row created while the sweep is running postdates the snapshot of live subjects its team's pass# took, so it would read as pointing at a subject that does not exist. Spared this round instead.SUBJECT_GRACE_HOURS = 1+# The one column that does not hold a subject id: a check names its PostHog table instead.+_CHECK_POSTHOG_TABLE_FIELD = "posthog_table"_COUNTER_COLUMNS = {"passed": "checks_passed",@@ -123,24 +126,44 @@ def _cleanup() -> CleanupOutcome:return outcome+def _registered_posthog_tables(field: str) -> Collection[Any]:+ """The registry values the column holds: a check binds by name, a run and a suite by id."""+ return posthog_tables.names() if field == _CHECK_POSTHOG_TABLE_FIELD else posthog_tables.all_ids()++@frozenclass _LiveSubjects:- """The warehouse objects a team still has, by id."""+ """The warehouse objects a team still has, by id.++ PostHog tables are not held here: they come from a static registry rather than from the team,+ so every row of that kind is alive as long as its name is still registered.+ """table_ids: frozenset[UUID]view_ids: frozenset[UUID]metric_ids: frozenset[UUID] = frozenset()def alive_q(- self, table_field: str = "subject_uuid", view_field: str = "subject_uuid", metric_field: str = "subject_uuid"+ self,+ table_field: str = "subject_uuid",+ view_field: str = "subject_uuid",+ metric_field: str = "subject_uuid",+ posthog_table_field: str = "subject_uuid",) -> Q:# An explicit predicate per known kind, so a row of a kind this sweep does not know reads as# dead rather than as alive by default. Runs and suites denormalize the subject into one- # column; a check carries it as whichever of its two foreign keys is set.+ # column; a check carries it as whichever of its subject foreign keys or its PostHog table+ # name is set.return (Q(**{"subject_type": SubjectType.TABLE, f"{table_field}__in": self.table_ids})| Q(**{"subject_type": SubjectType.VIEW, f"{view_field}__in": self.view_ids})| Q(**{"subject_type": SubjectType.METRIC, f"{metric_field}__in": self.metric_ids})+ | Q(+ **{+ "subject_type": SubjectType.POSTHOG_TABLE,+ f"{posthog_table_field}__in": _registered_posthog_tables(posthog_table_field),+ }+ ))@@ -182,7 +205,12 @@ def _live_subjects(team_id: int) -> _LiveSubjects:def _delete_dead_checks(team_id: int, live: _LiveSubjects, grace: datetime) -> int:- alive = live.alive_q(table_field="table_id", view_field="saved_query_id", metric_field="metric_id")+ alive = live.alive_q(+ table_field="table_id",+ view_field="saved_query_id",+ metric_field="metric_id",+ posthog_table_field=_CHECK_POSTHOG_TABLE_FIELD,+ )dead = DataQualityCheck.objects.for_team(team_id).filter(created_at__lt=grace).exclude(alive)return _delete_in_batches(dead).get(DataQualityCheck._meta.label, 0)diff --git a/products/data_quality/backend/temporal/activities/prepare_check_suite.py b/products/data_quality/backend/temporal/activities/prepare_check_suite.pyindex 242e6cc01a11..4cc431aaf5ab 100644--- a/products/data_quality/backend/temporal/activities/prepare_check_suite.py+++ b/products/data_quality/backend/temporal/activities/prepare_check_suite.py@@ -11,6 +11,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.data_modeling.backend.facade import api as data_modeling_facadefrom ...facade.enums import SubjectType, SuiteRunTrigger+from ...logic import posthog_tablesfrom ...logic.checks import live_subject_checksfrom ...logic.flags import get_data_quality_checks_flag_for_team_idfrom ...logic.subject_schedules import SubjectScheduleKey, SubjectSchedules, selected_subject_ids@@ -103,6 +104,7 @@ def _single_subject_fields(inputs: RunCheckSuiteInputs) -> dict[str, str]:(SubjectType.VIEW, inputs.saved_query_ids),(SubjectType.TABLE, inputs.table_ids),(SubjectType.METRIC, inputs.metric_ids),+ (SubjectType.POSTHOG_TABLE, inputs.posthog_table_ids),)for subject_uuid in identifiers]@@ -122,13 +124,16 @@ def _select_checks(inputs: RunCheckSuiteInputs) -> list[str]:saved_query_ids = list(inputs.saved_query_ids)if inputs.node_ids:saved_query_ids += data_modeling_facade.get_saved_query_ids_for_nodes(inputs.team_id, inputs.node_ids)- if not saved_query_ids and not inputs.table_ids and not inputs.metric_ids:+ if not saved_query_ids and not inputs.table_ids and not inputs.metric_ids and not inputs.posthog_table_ids:return []subject_filter = models.Q(saved_query_id__in=saved_query_ids)if inputs.table_ids:subject_filter |= models.Q(table_id__in=inputs.table_ids)if inputs.metric_ids:subject_filter |= models.Q(metric_id__in=inputs.metric_ids)+ if inputs.posthog_table_ids:+ names = [entry.name for entry in map(posthog_tables.by_id, inputs.posthog_table_ids) if entry]+ subject_filter |= models.Q(posthog_table__in=names)runnable = runnable.filter(subject_filter)return [str(check_id) for check_id in runnable.values_list("id", flat=True)]diff --git a/products/data_quality/backend/temporal/activities/reconcile_schedules.py b/products/data_quality/backend/temporal/activities/reconcile_schedules.pyindex 1585c8a4c2bf..c631e068f844 100644--- a/products/data_quality/backend/temporal/activities/reconcile_schedules.py+++ b/products/data_quality/backend/temporal/activities/reconcile_schedules.py@@ -36,15 +36,14 @@ SCHEDULE_TYPE_QUERY = " OR ".join(def _check_page(after_check_id: str | None) -> list[DataQualityCheck]:- checks = DataQualityCheck.objects.unscoped().filter(subject_type__in=SCHEDULED_SUBJECT_TYPES, metric__deleted=False)+ checks = DataQualityCheck.objects.unscoped().filter(subject_type__in=SCHEDULED_SUBJECT_TYPES)+ checks = checks.exclude(metric__deleted=True)if after_check_id:checks = checks.filter(id__gt=after_check_id)- # Every subject key the property reads, or reaching for it would lazy-load inside the async- # TaskGroup the reconciler runs these keys in.return list(- checks.only("id", "team_id", "subject_type", "metric_id", "saved_query_id", "table_id").order_by("id")[- :RECONCILE_PAGE_SIZE- ]+ checks.only(+ "id", "team_id", "subject_type", "metric_id", "saved_query_id", "table_id", "posthog_table"+ ).order_by("id")[:RECONCILE_PAGE_SIZE])diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 0f0d47ce4c60..3f5604c8ec13 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -26,6 +26,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.posthog_tables import by_namefrom products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.logic.subject_schedules import SubjectScheduleKey, SubjectSchedulesfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun@@ -2057,6 +2058,154 @@ class TestDataQualityCheckAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert response.json()["attr"] == "subject_type"+ def test_a_posthog_table_takes_checks_a_schedule_and_a_window(self) -> None:+ events = by_name("events")+ assert events is not None+ subject = {"subject_type": SubjectType.POSTHOG_TABLE, "subject_uuid": str(events.id)}++ with self.captureOnCommitCallbacks(execute=True):+ created = self.client.post(+ f"{self.url}/",+ {**subject, "check_type": CheckType.NOT_NULL, "column_name": "distinct_id", "config": {}},+ )++ assert created.status_code == status.HTTP_201_CREATED, created.json()+ assert created.json()["subject_uuid"] == str(events.id)+ assert created.json()["subject_name"] == "events"+ check = DataQualityCheck.objects.for_team(self.team.id).get(id=created.json()["id"])+ assert check.posthog_table == "events"++ windowed = self.client.post(+ f"{self.url}/",+ {+ **subject,+ "check_type": CheckType.NOT_NULL,+ "column_name": "distinct_id",+ "config": {"lookback_hours": 24},+ },+ )+ assert windowed.status_code == status.HTTP_201_CREATED, windowed.json()+ assert windowed.json()["id"] != created.json()["id"]++ assert [+ row["subject_uuid"]+ for row in self.client.get(self._checks_of(events.id, SubjectType.POSTHOG_TABLE)).json()["results"]+ ] == [+ str(events.id),+ str(events.id),+ ]+ assert self.client.get(+ f"{self.url}/schedule/?{self._subject_query(events.id, SubjectType.POSTHOG_TABLE)}"+ ).status_code in (+ status.HTTP_200_OK,+ status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ @parameterized.expand(+ [+ ("json_path", "properties.$browser", status.HTTP_201_CREATED),+ ("join_path", "person.properties.email", status.HTTP_400_BAD_REQUEST),+ ("lazy_table", "pdi.person_id", status.HTTP_400_BAD_REQUEST),+ ("unknown_column", "stripe_customer", status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_a_posthog_table_check_names_only_a_column_it_can_select(+ self, _name: str, column_name: str, expected: int+ ) -> None:+ events = by_name("events")+ assert events is not None++ response = self.client.post(+ f"{self.url}/",+ {+ "subject_type": SubjectType.POSTHOG_TABLE,+ "subject_uuid": str(events.id),+ "check_type": CheckType.NOT_NULL,+ "column_name": column_name,+ "config": {},+ },+ )++ assert response.status_code == expected, response.json()++ def test_a_relationships_target_on_a_posthog_table_names_only_a_column_it_can_select(self) -> None:+ events = by_name("events")+ assert events is not None++ response = self.client.post(+ f"{self.url}/",+ self._payload(+ check_type=CheckType.RELATIONSHIPS,+ column_name="customer_id",+ config={+ "to_subject_type": SubjectType.POSTHOG_TABLE,+ "to_subject_uuid": str(events.id),+ "to_column": "person.id",+ },+ ),+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_a_restricted_member_still_lists_and_runs_a_posthog_table_check(self) -> None:+ events = by_name("events")+ assert events is not None+ check = self._create_check(+ subject_type=SubjectType.POSTHOG_TABLE, subject_uuid=str(events.id), column_name="distinct_id"+ )+ self._deny_the_view()++ listed = self.client.get(self._checks_of(events.id, SubjectType.POSTHOG_TABLE))+ health = self.client.get(f"{self.url}/health/")+ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())) as connect:+ started = self.client.post(f"{self.suites_url}/", {})++ assert [row["id"] for row in listed.json()["results"]] == [str(check.id)]+ assert [row["subject_uuid"] for row in health.json()] == [str(events.id)]+ assert started.status_code == status.HTTP_200_OK, started.content+ assert connect.return_value.start_workflow.call_args.args[1]["check_ids"] == [str(check.id)]++ def test_running_a_posthog_table_subject_hands_the_worker_its_selector(self) -> None:+ # Without the selector the worker reads the suite as naming nothing and runs none of the+ # subject's checks, while still reporting the run as finished.+ events = by_name("events")+ assert events is not None++ with patch(START_SUITE) as connect:+ connect.return_value.start_workflow = AsyncMock()+ suite = checks_logic.start_check_suite(+ team=self.team,+ user=self.user,+ subject_type=SubjectType.POSTHOG_TABLE,+ subject_uuids=[str(events.id)],+ )++ assert suite.subject_uuid == str(events.id)+ assert connect.return_value.start_workflow.call_args.args[1]["posthog_table_ids"] == [str(events.id)]++ def test_a_window_is_refused_on_a_subject_with_no_time_column(self) -> None:+ response = self.client.post(f"{self.url}/", self._payload(config={"lookback_hours": 24}))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "lookback_hours" in response.json()["detail"]++ def test_a_target_window_is_refused_on_a_target_with_no_time_column(self) -> None:+ response = self.client.post(+ f"{self.url}/",+ self._payload(+ check_type=CheckType.RELATIONSHIPS,+ config={+ "to_subject_type": SubjectType.VIEW,+ "to_subject_uuid": str(self.view.id),+ "to_column": "id",+ "to_lookback_hours": 24,+ },+ ),+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "to_lookback_hours" in response.json()["detail"]+def test_the_check_type_catalog_needs_no_access_to_any_subject(self) -> None:self._deny_the_view()diff --git a/products/data_quality/backend/tests/test_cleanup.py b/products/data_quality/backend/tests/test_cleanup.pyindex a62011317f0a..0c109da174a7 100644--- a/products/data_quality/backend/tests/test_cleanup.py+++ b/products/data_quality/backend/tests/test_cleanup.py@@ -21,6 +21,7 @@ from products.data_quality.backend.facade.enums import (SuiteRunStatus,SuiteRunTrigger,)+from products.data_quality.backend.logic import posthog_tablesfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.data_quality.backend.temporal.activities import cleanup as cleanup_modulefrom products.data_quality.backend.temporal.activities.cleanup import (@@ -257,6 +258,38 @@ class TestRetentionSweep(BaseTest):assert DataQualityCheckRun.objects.for_team(self.team.id).filter(pk=run.pk).exists() == survivesassert DataQualitySuiteRun.objects.for_team(self.team.id).filter(pk=suite.pk).exists() == survives+ def test_a_posthog_table_check_and_its_history_survive_the_sweep(self) -> None:+ # The registry never loses an entry, so these subjects cannot die the way a warehouse object+ # can. Reading them as dead would destroy a check an hour after it was authored.+ events = posthog_tables.by_name("events")+ assert events is not None+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.POSTHOG_TABLE,+ posthog_table=events.name,+ subject_name=events.name,+ check_type=CheckType.NOT_NULL,+ column_name="distinct_id",+ fingerprint=uuid4().hex,+ )+ self._age(DataQualityCheck, check, 1)+ suite = self._suite(age_days=1, subject_type=SubjectType.POSTHOG_TABLE, subject_uuid=events.id)+ run = self._run(+ age_days=1,+ quality_check=check,+ suite_run=suite,+ subject_type=SubjectType.POSTHOG_TABLE,+ subject_uuid=events.id,+ subject_name=events.name,+ )++ outcome = _cleanup()++ assert outcome.checks_deleted == 0+ assert DataQualityCheck.objects.unscoped().filter(id=check.id).exists()+ assert DataQualityCheckRun.objects.unscoped().filter(id=run.id).exists()+ assert DataQualitySuiteRun.objects.unscoped().filter(id=suite.id).exists()+def test_rows_with_an_unknown_subject_type_are_treated_as_dead(self) -> None:suite = self._suite(age_days=1, subject_type=SubjectType.VIEW, subject_uuid=self.view.id)run = self._run(age_days=1, suite_run=suite)diff --git a/products/data_quality/backend/tests/test_compiler.py b/products/data_quality/backend/tests/test_compiler.pyindex 6d0ad8f1d72b..0239ad8e9bd9 100644--- a/products/data_quality/backend/tests/test_compiler.py+++ b/products/data_quality/backend/tests/test_compiler.py@@ -7,12 +7,31 @@ from products.data_quality.backend.facade.enums import CheckType, SubjectTypefrom products.data_quality.backend.logic.compiler import compile_checkfrom products.data_quality.backend.logic.contracts import Evaluation, SubjectReffrom products.data_quality.backend.logic.errors import CheckConfigError, SubjectUnresolvableError+from products.data_quality.backend.logic.posthog_tables import by_namefrom products.data_quality.backend.logic.registry import UnknownCheckTypeError, all_specs, get_spec, list_check_types-from products.data_quality.backend.logic.serialization import compute_fingerprint, from_config_entry, to_config_entry+from products.data_quality.backend.logic.serialization import (+ canonical_config,+ compute_fingerprint,+ from_config_entry,+ to_config_entry,+)from products.data_quality.backend.logic.spec import CheckTypeSpec, NoConfigfrom products.data_quality.backend.logic.types.custom_sql import CustomSqlConfig, CustomSqlSpec++def _posthog_table(name: str) -> SubjectRef:+ entry = by_name(name)+ assert entry is not None+ return SubjectRef(+ SubjectType.POSTHOG_TABLE, str(entry.id), entry.name, entry.name, exists=True, time_column=entry.time_column+ )++ORDERS = SubjectRef(SubjectType.VIEW, "1cd4a1ef-0000-0000-0000-000000000001", "orders", "orders", exists=True)+EVENTS = _posthog_table("events")+PERSONS = _posthog_table("persons")+GROUPS = _posthog_table("groups")+EVENTS_WITHOUT_TIME = SubjectRef(SubjectType.POSTHOG_TABLE, EVENTS.subject_uuid, "events", "events", exists=True)CUSTOMERS = SubjectRef(SubjectType.TABLE, "1cd4a1ef-0000-0000-0000-000000000002", "customers", "customers", True)RELATIONSHIPS_CONFIG = {@@ -24,7 +43,7 @@ RELATIONSHIPS_CONFIG = {def _normalized(check_type, column_name, config) -> dict:"""What the fingerprint hashes: config put through its type's model first."""- return get_spec(check_type).validate(config, column_name).model_dump(mode="json")+ return canonical_config(get_spec(check_type).validate(config, column_name))def _fingerprint_for(config: dict) -> str:@@ -449,6 +468,14 @@ class TestCheckSerialization:normalized = _normalized(CheckType.ROW_COUNT, "", config)assert _fingerprint_for(normalized) == _fingerprint_for(expected)+ def test_an_unset_relationship_window_preserves_an_existing_fingerprint(self) -> None:+ # A check authored before the windows existed stored neither key. Canonicalizing an unset one+ # as null would rehash it, so re-submitting it unchanged would duplicate it instead of upserting.+ normalized = _normalized(CheckType.RELATIONSHIPS, "customer_id", RELATIONSHIPS_CONFIG)++ assert normalized == RELATIONSHIPS_CONFIG+ assert _fingerprint_for(normalized) == _fingerprint_for(RELATIONSHIPS_CONFIG)+@parameterized.expand([(check_type,) for check_type in CheckType])def test_config_entry_round_trips(self, check_type) -> None:check = {@@ -504,6 +531,7 @@ class TestCheckSerialization:("string_column_reads_a_bool_as_text", "String", [True], ["true"]),("low_cardinality_string_reads_a_number_as_text", "LowCardinality(String)", [200], ["200"]),("unknown_column_type", None, ["1"], ["1"]),+ ("values_that_coercion_makes_equal_collapse", "Int64", ["1", 1], [1.0]),])def test_accepted_values_are_read_as_the_column_reads_them(self, _name, column_type, given, expected) -> None:@@ -516,6 +544,17 @@ class TestCheckSerialization:assert coerced.model_dump(mode="json")["values"] == expected+ def test_reading_accepted_values_as_the_column_reads_them_keeps_the_lookback_window(self) -> None:+ # The window is only authorable on a subject that has a time column, which is exactly where+ # an accepted-values check would otherwise lose it and read the subject's whole history.+ spec = get_spec(CheckType.ACCEPTED_VALUES)+ parsed = spec.validate({"values": ["1"], "lookback_hours": 24}, "status")++ coerced = spec.coerce_to_column(parsed, "Int64")++ assert coerced.lookback_hours == 24+ assert coerced.model_dump(mode="json")["values"] == [1.0]+@parameterized.expand([("a word on a numeric column", "Int64", ["paid"]),@@ -557,3 +596,105 @@ class TestCheckSerialization:assert as_int == as_stringassert _fingerprint_for(as_int) == _fingerprint_for(as_string)+++class TestLookbackWindow:+ GENERIC_TYPES = [+ (CheckType.NOT_NULL, "distinct_id", {}),+ (CheckType.UNIQUE, "distinct_id", {}),+ (CheckType.ACCEPTED_VALUES, "event", {"values": ["$pageview"]}),+ (CheckType.FRESHNESS, "timestamp", {"max_age_minutes": 60}),+ (CheckType.ROW_COUNT, "", {"min": 1}),+ ]++ @staticmethod+ def _window(column: str, hours: int) -> str:+ return f"greaterOrEquals({column}, minus(now(), toIntervalHour({hours})))"++ @pytest.mark.parametrize(("check_type", "column_name", "config"), GENERIC_TYPES)+ def test_no_window_prints_what_it_printed_before_windows_existed(self, check_type, column_name, config) -> None:+ windowed = compile_check(check_type=check_type, subject=EVENTS, column_name=column_name, config=config)+ timeless = compile_check(+ check_type=check_type, subject=EVENTS_WITHOUT_TIME, column_name=column_name, config=config+ )++ assert windowed.printed_query == timeless.printed_query+ assert "toIntervalHour" not in windowed.printed_query++ @pytest.mark.parametrize(("check_type", "column_name", "config"), GENERIC_TYPES)+ def test_a_window_bounds_every_generic_type(self, check_type, column_name, config) -> None:+ compiled = compile_check(+ check_type=check_type, subject=EVENTS, column_name=column_name, config={**config, "lookback_hours": 24}+ )++ assert self._window("timestamp", 24) in compiled.printed_query+ assert self._window("timestamp", 24) in compiled.printed_failing_rows_query++ def test_a_window_narrows_unique_before_it_groups(self) -> None:+ compiled = compile_check(+ check_type=CheckType.UNIQUE, subject=EVENTS, column_name="distinct_id", config={"lookback_hours": 6}+ )++ assert compiled.printed_query.index(self._window("timestamp", 6)) < compiled.printed_query.index("GROUP BY")++ @pytest.mark.parametrize("subject", [PERSONS, GROUPS])+ def test_persons_and_groups_window_on_when_they_were_first_seen(self, subject) -> None:+ compiled = compile_check(+ check_type=CheckType.ROW_COUNT, subject=subject, column_name="", config={"min": 1, "lookback_hours": 12}+ )++ assert self._window("created_at", 12) in compiled.printed_query++ def test_relationships_windows_each_side_on_its_own_column(self) -> None:+ compiled = compile_check(+ check_type=CheckType.RELATIONSHIPS,+ subject=EVENTS,+ column_name="distinct_id",+ config={+ "to_subject_type": SubjectType.POSTHOG_TABLE,+ "to_subject_uuid": PERSONS.subject_uuid,+ "to_column": "id",+ "lookback_hours": 24,+ "to_lookback_hours": 72,+ },+ related_subject=PERSONS,+ )++ assert self._window("timestamp", 24) in compiled.printed_query+ assert self._window("created_at", 72) in compiled.printed_query++ def test_relationships_can_bound_the_target_alone(self) -> None:+ compiled = compile_check(+ check_type=CheckType.RELATIONSHIPS,+ subject=ORDERS,+ column_name="customer_id",+ config={+ "to_subject_type": SubjectType.POSTHOG_TABLE,+ "to_subject_uuid": PERSONS.subject_uuid,+ "to_column": "id",+ "to_lookback_hours": 48,+ },+ related_subject=PERSONS,+ )++ assert self._window("created_at", 48) in compiled.printed_query+ assert compiled.printed_query.count("toIntervalHour") == 1++ def test_a_target_window_is_refused_when_the_target_has_no_time_column(self) -> None:+ with pytest.raises(CheckConfigError):+ compile_check(+ check_type=CheckType.RELATIONSHIPS,+ subject=EVENTS,+ column_name="distinct_id",+ config={**RELATIONSHIPS_CONFIG, "to_lookback_hours": 24},+ related_subject=CUSTOMERS,+ )++ def test_custom_sql_refuses_a_window_rather_than_rewriting_the_query(self) -> None:+ with pytest.raises(CheckConfigError):+ compile_check(+ check_type=CheckType.CUSTOM_SQL,+ subject=EVENTS,+ column_name="",+ config={"query": "SELECT 1 FROM events", "lookback_hours": 24},+ )diff --git a/products/data_quality/backend/tests/test_information_schema.py b/products/data_quality/backend/tests/test_information_schema.pyindex 4943fca90b4c..2ef520db945a 100644--- a/products/data_quality/backend/tests/test_information_schema.py+++ b/products/data_quality/backend/tests/test_information_schema.py@@ -175,6 +175,14 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):config={"query": "SELECT * FROM {metric}"},)self._run_for(metric_check, referenced_subjects=[])+ events_check = self._check(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query_id=None,+ posthog_table="events",+ subject_name="events",+ column_name="distinct_id",+ )+ self._run_for(events_check, referenced_subjects=[])self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]self.organization.save(update_fields=["available_product_features"])AccessControl.objects.create(diff --git a/products/data_quality/backend/tests/test_models.py b/products/data_quality/backend/tests/test_models.pyindex 86074ae6a3f3..d7f1f87cdfa8 100644--- a/products/data_quality/backend/tests/test_models.py+++ b/products/data_quality/backend/tests/test_models.py@@ -18,6 +18,7 @@ from products.data_quality.backend.facade.enums import (SubjectType,SuiteRunTrigger,)+from products.data_quality.backend.logic.posthog_tables import by_namefrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -97,6 +98,37 @@ class TestDataQualityModels(BaseTest):with self.assertRaises(IntegrityError), transaction.atomic():self._create_check(subject_type="metric", saved_query_id=None, metric_id=metric.id)+ def test_a_posthog_table_is_named_and_exclusive_with_every_subject_key(self) -> None:+ bindings: list[dict] = [+ {"posthog_table": "events"},+ {"subject_type": SubjectType.POSTHOG_TABLE, "saved_query_id": None},+ {"subject_type": SubjectType.POSTHOG_TABLE, "posthog_table": "events"},+ {"subject_type": SubjectType.POSTHOG_TABLE, "posthog_table": "events", "table_id": uuid4()},+ ]+ for binding in bindings:+ with self.subTest(binding=binding), self.assertRaises(IntegrityError), transaction.atomic():+ self._create_check(**binding)++ check = self._create_check(+ subject_type=SubjectType.POSTHOG_TABLE, saved_query_id=None, posthog_table="events", subject_name="events"+ )+ events = by_name("events")+ assert events is not None+ assert check.subject_uuid == events.id+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_check(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query_id=None,+ posthog_table="events",+ subject_name="events",+ )+ self._create_check(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query_id=None,+ posthog_table="persons",+ subject_name="persons",+ )+def test_moving_a_check_to_another_metric_keeps_its_audit_entry(self) -> None:# A subject FK enters the diff as a Metric instance, which the activity encoder cannot# serialize, and one unserializable change drops the whole entry -- including the fields adiff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.pyindex 18eaa6c1300a..733909ab19f7 100644--- a/products/data_quality/backend/tests/test_notifications.py+++ b/products/data_quality/backend/tests/test_notifications.py@@ -32,8 +32,9 @@ from products.data_quality.backend.logic.notifications import (notify_check_started_failing,notify_materialization_blocked,)+from products.data_quality.backend.logic.posthog_tables import by_namefrom products.data_quality.backend.logic.runner import run_check-from products.data_quality.backend.logic.subject_access import referenced_subject_names+from products.data_quality.backend.logic.subject_access import pin_referenced_subjects, referenced_subject_namesfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.data_quality.backend.temporal.activities.notify_failing_checks import _notify_failing_checksfrom products.data_quality.backend.temporal.contracts import NotifyFailingChecksInputs@@ -569,6 +570,46 @@ class TestDataQualityNotifications(BaseTest):assert self.user.id in resolvedassert blocked.id not in resolved+ @parameterized.expand([("own_subject",), ("relationships_target",)])+ def test_members_denied_posthog_tables_do_not_get_a_notification_that_reads_one(self, shape: str) -> None:+ events = by_name("events")+ assert events is not None+ self._enable_access_controls()+ allowed = User.objects.create_and_join(self.organization, "[email protected]", "password")+ blocked = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._deny_resource("warehouse_objects", blocked)+ if shape == "own_subject":+ check = self._check(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query_id=None,+ posthog_table="events",+ subject_name="events",+ column_name="distinct_id",+ )+ else:+ check = self._check(+ check_type=CheckType.RELATIONSHIPS,+ column_name="customer_id",+ config={+ "to_subject_type": SubjectType.POSTHOG_TABLE,+ "to_subject_uuid": str(events.id),+ "to_column": "distinct_id",+ },+ )+ resolver = _WarehouseSubjectResolver(+ self.team,+ check.subject_type,+ str(check.subject_uuid),+ referenced_names=referenced_subject_names(self.team.id, check.check_type, check.config),+ executed_references=pin_referenced_subjects(self.team.id, check.check_type, check.config) or (),+ )++ resolved = resolver.resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert self.user.id in resolved+ assert allowed.id in resolved+ assert blocked.id not in resolved+def test_a_relationship_target_keeps_its_name_for_notification_filtering(self) -> None:check = self._check(check_type=CheckType.RELATIONSHIPS,diff --git a/products/data_quality/backend/tests/test_permissions.py b/products/data_quality/backend/tests/test_permissions.pyindex a63bb510dc43..34e2ecf323cd 100644--- a/products/data_quality/backend/tests/test_permissions.py+++ b/products/data_quality/backend/tests/test_permissions.py@@ -7,22 +7,20 @@ from parameterized import parameterizedfrom products.data_quality.backend.facade.enums import SubjectTypefrom products.data_quality.backend.logic.permissions import authorized_subject_types+_WAREHOUSE_TABLES = {SubjectType.TABLE, SubjectType.POSTHOG_TABLE}+_WAREHOUSE_KINDS = _WAREHOUSE_TABLES | {SubjectType.VIEW}+class TestAuthorizedSubjectTypes(SimpleTestCase):@parameterized.expand([- ("per_kind_table_write", ["query:read", "warehouse_table:write"], True, {SubjectType.TABLE}),+ ("per_kind_table_write", ["query:read", "warehouse_table:write"], True, _WAREHOUSE_TABLES),("per_kind_view_read", ["query:read", "warehouse_view:read"], False, {SubjectType.VIEW}),("per_kind_read_cannot_write", ["query:read", "warehouse_table:read"], True, set()),- ("family_read", ["query:read", "warehouse_objects:read"], False, {SubjectType.TABLE, SubjectType.VIEW}),- ("family_write", ["query:read", "warehouse_objects:write"], True, {SubjectType.TABLE, SubjectType.VIEW}),+ ("family_read", ["query:read", "warehouse_objects:read"], False, _WAREHOUSE_KINDS),+ ("family_write", ["query:read", "warehouse_objects:write"], True, _WAREHOUSE_KINDS),("catalog_only", ["query:read", "data_catalog:write"], True, {SubjectType.METRIC}),- (- "family_does_not_reach_metrics",- ["warehouse_objects:write"],- False,- {SubjectType.TABLE, SubjectType.VIEW},- ),+ ("family_does_not_reach_metrics", ["warehouse_objects:write"], False, _WAREHOUSE_KINDS),("session_user", None, True, set(SubjectType)),])diff --git a/products/data_quality/backend/tests/test_posthog_tables.py b/products/data_quality/backend/tests/test_posthog_tables.pynew file mode 100644index 000000000000..2261b228f949--- /dev/null+++ b/products/data_quality/backend/tests/test_posthog_tables.py@@ -0,0 +1,59 @@+from uuid import uuid4++import pytest++from products.data_quality.backend.facade.enums import SubjectType+from products.data_quality.backend.logic.posthog_tables import TABLES, all_ids, by_id, by_name, names+from products.data_quality.backend.logic.subjects import resolve_subject+++class TestPostHogTableRegistry:+ @pytest.mark.parametrize(+ ("name", "time_column"), [("events", "timestamp"), ("persons", "created_at"), ("groups", "created_at")]+ )+ def test_each_table_resolves_by_name_and_by_id(self, name: str, time_column: str) -> None:+ entry = by_name(name)++ assert entry is not None+ assert entry.time_column == time_column+ assert by_id(entry.id) is entry+ assert entry.id in all_ids()+ assert name in names()++ def test_an_id_that_is_no_table_resolves_to_nothing(self) -> None:+ assert by_id(uuid4()) is None+ assert by_id("not-a-uuid") is None+ assert by_name("orders") is None++ def test_columns_leave_out_the_joins_a_check_cannot_select(self) -> None:+ events = by_name("events")+ persons = by_name("persons")+ assert events is not None and persons is not None++ assert events.columns["timestamp"] == "datetime"+ assert persons.columns["properties"] == "json"+ for join in ("person", "pdi", "poe", "goe_0", "session"):+ assert join not in events.columns++ def test_an_id_the_registry_does_not_know_resolves_to_a_missing_subject(self) -> None:+ missing = resolve_subject(1, SubjectType.POSTHOG_TABLE, uuid4())++ assert not missing.exists+ assert missing.time_column is None++ def test_a_registered_table_resolves_without_touching_the_database(self) -> None:+ events = by_name("events")+ assert events is not None++ resolved = resolve_subject(1, SubjectType.POSTHOG_TABLE, events.id)++ assert resolved.exists+ assert resolved.queryable_name == "events"+ assert resolved.time_column == "timestamp"++ def test_every_table_has_a_distinct_stable_id(self) -> None:+ events = by_name("events")+ assert events is not None++ assert len(all_ids()) == len(TABLES)+ assert str(events.id) == "d4fb61da-50ae-59dc-a94f-f2036dfcfe49"diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex ca693432dd29..3d3d4ec57c75 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -315,6 +315,24 @@ class TestCheckRunner(BaseTest):assert query.call_args.kwargs["bypass_warehouse_access_control"] is Falseassert query.call_args.kwargs["user"] == self.user+ def test_an_automated_posthog_table_check_runs_as_its_author(self) -> None:+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.SCHEDULED+ )+ check = self._check(+ subject_type=SubjectType.POSTHOG_TABLE,+ saved_query_id=None,+ posthog_table="events",+ subject_name="events",+ column_name="properties.$browser",+ created_by=self.user,+ )+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:+ run_check(check, suite_run, self.team)++ assert query.call_args.kwargs["bypass_warehouse_access_control"] is False+ assert query.call_args.kwargs["user"] == self.user+@parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])def test_a_manual_referencing_check_without_an_initiator_never_reaches_the_warehouse(self, _name, check_type: CheckTypediff --git a/products/data_quality/backend/tests/test_subject_access.py b/products/data_quality/backend/tests/test_subject_access.pyindex 07f66fed0e97..159921b3e07c 100644--- a/products/data_quality/backend/tests/test_subject_access.py+++ b/products/data_quality/backend/tests/test_subject_access.py@@ -29,6 +29,7 @@ from products.data_quality.backend.facade.enums import SubjectTypefrom products.data_quality.backend.logic.checks import upsert_checkfrom products.data_quality.backend.logic.exceptions import SubjectAccessUnverifiablefrom products.data_quality.backend.logic.permissions import restrict_subject_types, writable_subjects+from products.data_quality.backend.logic.posthog_tables import by_namefrom products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.logic.subject_access import (DeferredDatabase,@@ -321,6 +322,23 @@ class TestMetricSubjectAccess(BaseTest):assert restricted.matcher.matches([written_as]) is True+ @parameterized.expand([("allowed", True), ("restricted_away", False)])+ def test_a_posthog_table_is_readable_unless_its_kind_is_restricted_away(self, _name: str, allowed: bool) -> None:+ events = by_name("events")+ assert events is not None+ context = DenialContext(+ readable=readable_subjects(self.team.id, set()),+ denied=set(),+ database=DeferredDatabase.built(Database.create_for(team=self.team, user=self.user)),+ metadata=subject_metadata(self.team.id),+ )+ kinds = list(SubjectType) if allowed else [SubjectType.VIEW, SubjectType.METRIC]++ restricted = restrict_subject_types(context, kinds)++ assert restricted.readable.contains(SubjectType.POSTHOG_TABLE, events.id) is allowed+ assert bool(restricted.readable.posthog_table_ids) is allowed+def test_failed_composition_cannot_record_empty_references(self) -> None:assert pin_referenced_subjects(self.team.id, "custom_sql", {"query": "SELECT 1"}, subject=self.subject) is Nonediff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.tsindex face9a3271a3..ea9138d90f51 100644--- a/products/data_quality/frontend/checksApi.ts+++ b/products/data_quality/frontend/checksApi.ts@@ -32,13 +32,14 @@ import type {PatchedDataQualityCheckScheduleUpdateApi,PaginatedDataQualityOverviewCheckListApi,PaginatedDataQualitySuiteRunListApi,+ SubjectTypeEnumApi,} from './generated/api.schemas'export function apiErrorDetail(error: unknown): string | null {return error instanceof ApiError ? error.detail : null}-export type DataQualitySubjectType = 'table' | 'view' | 'metric'+export type DataQualitySubjectType = SubjectTypeEnumApiexport interface DataQualitySubjectRef {subjectType: DataQualitySubjectTypediff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex 1ac7c2406216..4ddc51df8e3e 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -11,6 +11,7 @@* * `table` - table* * `view` - view* * `metric` - metric+ * * `posthog_table` - posthog_table*/export type SubjectTypeEnumApi = (typeof SubjectTypeEnumApi)[keyof typeof SubjectTypeEnumApi]@@ -18,6 +19,7 @@ export const SubjectTypeEnumApi = {Table: 'table',View: 'view',Metric: 'metric',+ PosthogTable: 'posthog_table',} as const/**@@ -139,14 +141,15 @@ export interface DataQualityOverviewCheckApi {name?: string/** Why this check exists and what a failure means. */description?: string- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type: SubjectTypeEnumApi/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null@@ -273,13 +276,14 @@ export interface DataQualityCheckCreateApi {name?: string/** Why this check exists and what a failure means. */description?: string- /** Kind of catalog object to check: 'table', 'view', or 'metric'.+ /** Kind of object to check: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type: SubjectTypeEnumApi- /** Id of the table, view, or metric to check. */+ /** Id of the table, view, metric, or PostHog table to check. */subject_uuid: string/** Queryable name of the subject, refreshed on every run. */readonly subject_name: string@@ -377,14 +381,15 @@ export interface DataQualityCheckApi {name?: string/** Why this check exists and what a failure means. */description?: string- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type: SubjectTypeEnumApi/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null@@ -484,14 +489,15 @@ export interface PatchedDataQualityCheckApi {name?: string/** Why this check exists and what a failure means. */description?: string- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type?: SubjectTypeEnumApi/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid?: string | null@@ -582,7 +588,7 @@ export interface DataQualitySuiteRunApi {/** running, completed, failed, or empty (nothing matched the trigger). */readonly status: string/**- * 'table', 'view', or 'metric' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.+ * 'table', 'view', 'metric', or 'posthog_table' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.* @nullable*/readonly subject_type: string | null@@ -696,9 +702,9 @@ export interface DataQualityCheckTypeApi {* Per-subject rollup, the same rule the information_schema.data_quality_health table uses.*/export interface DataQualitySubjectHealthApi {- /** 'table', 'view', or 'metric'. */+ /** 'table', 'view', 'metric', or 'posthog_table'. */subject_type: string- /** Id of the table, view, or metric. */+ /** Id of the table, view, metric, or PostHog table. */subject_uuid: string/** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */health: string@@ -784,13 +790,14 @@ export interface DataQualityCheckScheduleApi {* Which subject's schedule to change, and what to change about it.*/export interface PatchedDataQualityCheckScheduleUpdateApi {- /** Kind of catalog object: 'table', 'view', or 'metric'.+ /** Kind of object: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type?: SubjectTypeEnumApi- /** Id of the table, view, or metric. */+ /** Id of the table, view, metric, or PostHog table. */subject_uuid?: string/** How often all enabled checks on the subject run.*@@ -813,11 +820,12 @@ export type DataQualitySubjectApiColumns = { [key: string]: string }* One thing a check can be authored on, whatever kind it is.*/export interface DataQualitySubjectApi {- /** Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.+ /** Kind of object: 'table', 'view', 'metric', or 'posthog_table'. Pass it back as subject_type when creating a check.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type: SubjectTypeEnumApi/** Id of the subject. Pass it back as subject_uuid when creating a check. */id: string@@ -850,7 +858,8 @@ export interface DataQualityRunRequestApi {** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type?: SubjectTypeEnumApi/** Id of the subject to run every enabled check on. Pass subject_type with it. */subject_uuid?: string@@ -870,11 +879,11 @@ export type DataQualityChecksListParams = {*/offset?: number/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksListSubjectType/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string}@@ -897,13 +906,14 @@ export type DataQualityChecksListSubjectType =export const DataQualityChecksListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as constexport type DataQualityChecksCheckTypesListParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksCheckTypesListSubjectType}@@ -913,17 +923,18 @@ export type DataQualityChecksCheckTypesListSubjectType =export const DataQualityChecksCheckTypesListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as constexport type DataQualityChecksHealthListParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksHealthListSubjectType/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string}@@ -933,17 +944,18 @@ export type DataQualityChecksHealthListSubjectType =export const DataQualityChecksHealthListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as constexport type DataQualityChecksOutputSchemaRetrieveParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksOutputSchemaRetrieveSubjectType/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string}@@ -953,17 +965,18 @@ export type DataQualityChecksOutputSchemaRetrieveSubjectType =export const DataQualityChecksOutputSchemaRetrieveSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as constexport type DataQualityChecksScheduleRetrieveParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksScheduleRetrieveSubjectType/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string}@@ -973,6 +986,7 @@ export type DataQualityChecksScheduleRetrieveSubjectType =export const DataQualityChecksScheduleRetrieveSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const@@ -987,11 +1001,11 @@ export type DataQualityRunsListParams = {*/offset?: number/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityRunsListSubjectType/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string}@@ -1001,6 +1015,7 @@ export type DataQualityRunsListSubjectType =export const DataQualityRunsListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as constdiff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.tsindex 418e39a57dc0..5de2d747634c 100644--- a/products/data_quality/frontend/generated/api.zod.ts+++ b/products/data_quality/frontend/generated/api.zod.ts@@ -35,12 +35,12 @@ export const DataQualityChecksCreateBody = /* @__PURE__ */ zod.describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),subject_type: zod- .enum(['table', 'view', 'metric'])- .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .enum(['table', 'view', 'metric', 'posthog_table'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table').describe(- "Kind of catalog object to check: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"+ "Kind of object to check: 'table', 'view', 'metric', or 'posthog_table'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table"),- subject_uuid: zod.uuid().describe('Id of the table, view, or metric to check.'),+ subject_uuid: zod.uuid().describe('Id of the table, view, metric, or PostHog table to check.'),column_name: zod.string().max(dataQualityChecksCreateBodyColumnNameMax)@@ -249,13 +249,13 @@ export const DataQualityChecksPartialUpdateBody = /* @__PURE__ */ zodexport const DataQualityChecksSchedulePartialUpdateBody = /* @__PURE__ */ zod.object({subject_type: zod- .enum(['table', 'view', 'metric'])- .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .enum(['table', 'view', 'metric', 'posthog_table'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table').optional().describe(- "Kind of catalog object: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"+ "Kind of object: 'table', 'view', 'metric', or 'posthog_table'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table"),- subject_uuid: zod.uuid().optional().describe('Id of the table, view, or metric.'),+ subject_uuid: zod.uuid().optional().describe('Id of the table, view, metric, or PostHog table.'),interval: zod.enum(['1hour', '6hour', '12hour', '24hour', '7day']).describe(@@ -279,11 +279,11 @@ export const DataQualityRunsCreateBody = /* @__PURE__ */ zod.optional().describe('Ids of the checks to run. Omit to run every enabled check in the project.'),subject_type: zod- .enum(['table', 'view', 'metric'])- .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .enum(['table', 'view', 'metric', 'posthog_table'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table').optional().describe(- 'Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric'+ 'Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table'),subject_uuid: zod.uuid()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8ef85adbe504..e8f164ba2494 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23873,6 +23873,7 @@ export namespace Schemas {* * `table` - table* * `view` - view* * `metric` - metric+ * * `posthog_table` - posthog_table*/export type SubjectTypeEnum = typeof SubjectTypeEnum[keyof typeof SubjectTypeEnum];@@ -23881,6 +23882,7 @@ export namespace Schemas {Table: 'table',View: 'view',Metric: 'metric',+ PosthogTable: 'posthog_table',} as const;/**@@ -23906,14 +23908,15 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null;@@ -24011,13 +24014,14 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object to check: 'table', 'view', or 'metric'.+ /** Kind of object to check: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type: SubjectTypeEnum;- /** Id of the table, view, or metric to check. */+ /** Id of the table, view, metric, or PostHog table to check. */subject_uuid: string;/** Queryable name of the subject, refreshed on every run. */readonly subject_name: string;@@ -24284,14 +24288,15 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null;@@ -24405,7 +24410,8 @@ export namespace Schemas {** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type?: SubjectTypeEnum;/** Id of the subject to run every enabled check on. Pass subject_type with it. */subject_uuid?: string;@@ -24420,11 +24426,12 @@ export namespace Schemas {* One thing a check can be authored on, whatever kind it is.*/export interface DataQualitySubject {- /** Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.+ /** Kind of object: 'table', 'view', 'metric', or 'posthog_table'. Pass it back as subject_type when creating a check.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type: SubjectTypeEnum;/** Id of the subject. Pass it back as subject_uuid when creating a check. */id: string;@@ -24442,9 +24449,9 @@ export namespace Schemas {* Per-subject rollup, the same rule the information_schema.data_quality_health table uses.*/export interface DataQualitySubjectHealth {- /** 'table', 'view', or 'metric'. */+ /** 'table', 'view', 'metric', or 'posthog_table'. */subject_type: string;- /** Id of the table, view, or metric. */+ /** Id of the table, view, metric, or PostHog table. */subject_uuid: string;/** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */health: string;@@ -24461,7 +24468,7 @@ export namespace Schemas {/** running, completed, failed, or empty (nothing matched the trigger). */readonly status: string;/**- * 'table', 'view', or 'metric' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.+ * 'table', 'view', 'metric', or 'posthog_table' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.* @nullable*/readonly subject_type: string | null;@@ -67541,14 +67548,15 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */readonly subject_type?: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked. Null once the subject is deleted.+ * Id of the table, view, metric, or PostHog table being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid?: string | null;@@ -67636,13 +67644,14 @@ export namespace Schemas {* Which subject's schedule to change, and what to change about it.*/export interface PatchedDataQualityCheckScheduleUpdate {- /** Kind of catalog object: 'table', 'view', or 'metric'.+ /** Kind of object: 'table', 'view', 'metric', or 'posthog_table'.** * `table` - table* * `view` - view- * * `metric` - metric */+ * * `metric` - metric+ * * `posthog_table` - posthog_table */subject_type?: SubjectTypeEnum;- /** Id of the table, view, or metric. */+ /** Id of the table, view, metric, or PostHog table. */subject_uuid?: string;/** How often all enabled checks on the subject run.*@@ -102394,11 +102403,11 @@ export namespace Schemas {*/offset?: number;/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksListSubjectType;/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string;};@@ -102421,13 +102430,14 @@ export namespace Schemas {export const DataQualityChecksListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;export type DataQualityChecksCheckTypesListParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksCheckTypesListSubjectType;};@@ -102437,17 +102447,18 @@ export namespace Schemas {export const DataQualityChecksCheckTypesListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;export type DataQualityChecksHealthListParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksHealthListSubjectType;/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string;};@@ -102457,17 +102468,18 @@ export namespace Schemas {export const DataQualityChecksHealthListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;export type DataQualityChecksOutputSchemaRetrieveParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksOutputSchemaRetrieveSubjectType;/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string;};@@ -102477,17 +102489,18 @@ export namespace Schemas {export const DataQualityChecksOutputSchemaRetrieveSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;export type DataQualityChecksScheduleRetrieveParams = {/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityChecksScheduleRetrieveSubjectType;/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string;};@@ -102497,6 +102510,7 @@ export namespace Schemas {export const DataQualityChecksScheduleRetrieveSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;@@ -102511,11 +102525,11 @@ export namespace Schemas {*/offset?: number;/**- * Kind of catalog object: 'table', 'view', or 'metric'.+ * Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'.*/subject_type?: DataQualityRunsListSubjectType;/**- * Id of the table, view, or metric.+ * Id of the table, view, metric, or PostHog table.*/subject_uuid?: string;};@@ -102525,6 +102539,7 @@ export namespace Schemas {export const DataQualityRunsListSubjectType = {Metric: 'metric',+ PosthogTable: 'posthog_table',Table: 'table',View: 'view',} as const;diff --git a/services/mcp/src/generated/data_quality/api.ts b/services/mcp/src/generated/data_quality/api.tsindex a1c1a378739d..8968aef19443 100644--- a/services/mcp/src/generated/data_quality/api.ts+++ b/services/mcp/src/generated/data_quality/api.ts@@ -42,12 +42,12 @@ export const DataQualityChecksCreateBody = () => zod.describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),subject_type: zod- .enum(['table', 'view', 'metric'])- .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .enum(['table', 'view', 'metric', 'posthog_table'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table').describe(- "Kind of catalog object to check: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"+ "Kind of object to check: 'table', 'view', 'metric', or 'posthog_table'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table"),- subject_uuid: zod.string().describe('Id of the table, view, or metric to check.'),+ subject_uuid: zod.string().describe('Id of the table, view, metric, or PostHog table to check.'),column_name: zod.string().max(dataQualityChecksCreateBodyColumnNameMax)@@ -233,9 +233,9 @@ export const DataQualityChecksCheckTypesListParams = () => zod.object({export const DataQualityChecksCheckTypesListQueryParams = () => zod.object({subject_type: zod- .enum(['metric', 'table', 'view'])+ .enum(['metric', 'posthog_table', 'table', 'view']).optional()- .describe("Kind of catalog object: 'table', 'view', or 'metric'."),+ .describe("Kind of object being checked: 'table', 'view', 'metric', or 'posthog_table'."),})/**@@ -252,13 +252,13 @@ export const DataQualityChecksSchedulePartialUpdateParams = () => zod.object({export const DataQualityChecksSchedulePartialUpdateBody = () => zod.object({subject_type: zod- .enum(['table', 'view', 'metric'])- .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .enum(['table', 'view', 'metric', 'posthog_table'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table').optional().describe(- "Kind of catalog object: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"+ "Kind of object: 'table', 'view', 'metric', or 'posthog_table'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric\n\* `posthog_table` - posthog_table"),- subject_uuid: zod.string().optional().describe('Id of the table, view, or metric.'),+ subject_uuid: zod.string().optional().describe('Id of the table, view, metric, or PostHog table.'),interval: zod.enum(['1hour', '6hour', '12hour', '24hour', '7day']).describe(