:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-quality): read accepted values as the column reads them (#86685)
Thiago Salvatored77e002f4e10
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 03df6fa3fe25..85ddc494a892 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -25,6 +25,7 @@ _LAZY = {"run_saved_query_materialization": "logic.node_materialization","get_materialized_table_uri": "logic.saved_query_reads","get_node_ids_for_saved_queries": "logic.saved_query_reads",+ "get_saved_query_columns": "logic.saved_query_reads","get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "logic.saved_query_reads","saved_query_materialized_at": "logic.saved_query_freshness",diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex dc80c69e0251..070a79b3ee88 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -10,6 +10,32 @@ from ..models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom ..models.node import Node+def _clickhouse_type(entry: object) -> str | None:+ """The stored ClickHouse type, reading a current dict entry keyed ``clickhouse`` or a legacy+ bare type string. None for anything else, so a column with no readable type is dropped."""+ if isinstance(entry, dict):+ entry = entry.get("clickhouse")+ return entry if isinstance(entry, str) else None+++def get_saved_query_columns(team_id: int, saved_query_id: UUID | str) -> dict[str, str]:+ """Each column's ClickHouse type, including any ``Nullable()`` wrapper.++ Empty for a view that has not run yet, since the columns are only recorded once a run has+ established them. A caller must treat that as unknown rather than as having no columns.++ The ``columns`` map stores each value as a bare type string (legacy rows) or a dict keyed+ ``clickhouse`` (current rows); both are unwrapped here so a consumer reads a plain type string.+ """+ stored = (+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id=saved_query_id)+ .exclude(deleted=True)+ .values_list("columns", flat=True)+ .first()+ )+ return {name: type_ for name, entry in (stored or {}).items() if (type_ := _clickhouse_type(entry)) is not None}++def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQuerySummary | None:"""The saved query only if it still resolves, else None.diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex 31b8b7eb0df2..7e92bed40827 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -32,7 +32,7 @@ from .health import CheckStatusRow, roll_up_healthfrom .registry import get_specfrom .serialization import compute_fingerprintfrom .spec import CheckConfig-from .subjects import resolve_subject+from .subjects import resolve_subject, subject_column_type_UPSERTABLE_FIELDS = ("name",@@ -73,11 +73,15 @@ def validate_check(Returns the parsed config so callers do not validate twice, and so the fingerprint hashes thenormalized form rather than whatever representation the request happened to use."""- parsed = get_spec(check_type).validate(config, column_name)+ spec = get_spec(check_type)+ parsed = spec.validate(config, column_name)if not resolve_subject(team.id, subject_type, subject_uuid).exists:raise SubjectUnresolvableError(f"No {subject_type} with id {subject_uuid} in this project.")+ # 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.")diff --git a/products/data_quality/backend/logic/spec.py b/products/data_quality/backend/logic/spec.pyindex f21eddbe44cd..e9785e7ebf45 100644--- a/products/data_quality/backend/logic/spec.py+++ b/products/data_quality/backend/logic/spec.py@@ -62,6 +62,13 @@ class CheckTypeSpec(ABC):raise CheckConfigError(f"A {self.type_name} check needs a column_name.")return self.parse_config(config)+ def coerce_to_column(self, config: CheckConfig, column_type: str | None) -> CheckConfig:+ """Normalize config values against the column's type. Identity for types that hold none.++ ``column_type`` is the raw ClickHouse type, or None when it could not be established.+ """+ return config+def related_subject_ref(self, config: CheckConfig) -> tuple[str, str] | None:"""The second subject this check needs resolved before it can compile, if any."""return Nonediff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.pyindex af0996440dc3..e9300e4a8c64 100644--- a/products/data_quality/backend/logic/subjects.py+++ b/products/data_quality/backend/logic/subjects.py@@ -75,6 +75,29 @@ def _resolve_view(team_id: int, subject_uuid: str | UUID) -> SubjectRef:)+def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUID, column_name: str) -> str | None:+ """The column's ClickHouse type, or None when the subject or the column cannot be established.++ None is unknown, not "untyped": a view records its columns only once it has run, so a check+ authored against a fresh view has nothing to read here.+ """+ if not column_name:+ return None+ kind = SubjectType(subject_type)+ if kind is SubjectType.TABLE:+ table = warehouse_facade.get_queryable_table(UUID(str(subject_uuid)), team_id)+ columns = table.columns if table else {}+ else:+ columns = data_modeling_facade.get_saved_query_columns(team_id, subject_uuid)+ entry = (columns or {}).get(column_name)+ # A table records either a bare type string (older rows) or a dict keyed "clickhouse", the same+ # two shapes hogql_fields_and_structure_for_columns handles; the saved-query facade already+ # unwrapped a view's entry to the string.+ if isinstance(entry, dict):+ entry = entry.get("clickhouse")+ return entry if isinstance(entry, str) else None++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 94e9f4c56e70..9c724487e22c 100644--- a/products/data_quality/backend/logic/types/accepted_values.py+++ b/products/data_quality/backend/logic/types/accepted_values.py@@ -6,6 +6,7 @@ from posthog.hogql import astfrom ...facade.enums import CheckTypefrom ..contracts import CheckPlan, SubjectRef+from ..errors import CheckConfigErrorfrom ..spec import CheckConfig, CheckTypeSpecfrom .common import column, diagnostic_of, one, subject_source@@ -25,12 +26,89 @@ class AcceptedValuesConfig(CheckConfig):return [by_repr[key] for key in sorted(by_repr)]+_NUMERIC_PREFIXES = ("Int", "UInt", "Float", "Decimal")++# Wrappers that do not change how a value is written; the inner scalar type decides coercion. A+# direct ClickHouse source stores them verbatim, e.g. LowCardinality(Nullable(Int64)).+_TRANSPARENT_WRAPPERS = ("Nullable(", "LowCardinality(")+++def _unwrap_type(column_type: str) -> str:+ """Peel transparent wrappers so the inner scalar type name leads.++ ``LowCardinality(Nullable(Int64))`` -> ``Int64``. A wrapper the coercion does not know is left+ in place, so an unexpected shape falls through to "unchanged" rather than being misread.+ """+ while column_type.endswith(")"):+ for wrapper in _TRANSPARENT_WRAPPERS:+ if column_type.startswith(wrapper):+ column_type = column_type[len(wrapper) : -1]+ break+ else:+ break+ return column_type+++def _as_text(value: str | float | bool) -> str:+ """One value as the string a text column would hold, so an agent's 200 matches the editor's "200".++ An integral number drops its trailing ".0" and a boolean reads as ClickHouse writes it, so the+ number or boolean an agent sends canonicalizes to the string the editor's control produces.+ """+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, float):+ return str(int(value)) if value.is_integer() else str(value)+ return str(value)+++def _coerce_value(value: str | float | bool, column_type: str) -> str | float | bool:+ """One accepted value in the column's own type, coercing to text when the column holds strings."""+ if column_type.startswith("Bool"):+ if isinstance(value, bool):+ return value+ lowered = str(value).strip().lower()+ if lowered in ("true", "false"):+ return lowered == "true"+ raise CheckConfigError(f"{value!r} is not a true/false value, but the column is {column_type}.")+ if column_type.startswith(_NUMERIC_PREFIXES):+ if isinstance(value, bool):+ raise CheckConfigError(f"{value!r} is not a number, but the column is {column_type}.")+ try:+ number = float(value)+ except (TypeError, ValueError):+ raise CheckConfigError(f"{value!r} is not a number, but the column is {column_type}.")+ # An integer column cannot hold a fraction, so reject one at authoring time rather than store+ # a value no row can ever match. A whole number written as 2.0 still passes.+ if column_type.startswith(("Int", "UInt")) and not number.is_integer():+ raise CheckConfigError(f"{value!r} is not a whole number, but the column is {column_type}.")+ return number+ # A text column can hold any scalar as a string, so read it as one rather than leaving a number+ # or boolean to fingerprint apart from the editor's string and compile to a mixed-type NOT IN.+ if column_type.startswith(("String", "FixedString")):+ return _as_text(value)+ return value++class AcceptedValuesSpec(CheckTypeSpec):type_name = CheckType.ACCEPTED_VALUESconfig_model = AcceptedValuesConfigrequires_column = Truedescription = "Fails on rows whose column value is outside the allowed set. Nulls are ignored."+ def coerce_to_column(self, config: CheckConfig, column_type: str | None) -> CheckConfig:+ """Read the accepted values as the column reads them.++ The editor's value control can only produce strings, so a numeric or boolean column would+ otherwise be compared against strings -- and "1" would fingerprint differently from the 1 an+ agent sends for the same check. Left alone when the column type is unknown.+ """+ assert isinstance(config, AcceptedValuesConfig)+ if not column_type:+ return config+ bare = _unwrap_type(column_type)+ return AcceptedValuesConfig(values=[_coerce_value(value, bare) for value in config.values])+def build(self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None) -> CheckPlan:diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 7c04ddc97857..2dd37697ac80 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -561,6 +561,21 @@ class TestDataQualityCheckAPI(APIBaseTest):assert history.status_code == status.HTTP_200_OKassert history.json() == []+ def test_accepted_values_are_stored_as_the_column_holds_them(self) -> None:+ # The editor can only send strings. Whether the coercion is wired into the create path at all+ # is what this covers; the type matrix itself is unit-tested against the spec.+ view = self._make_view("payments")+ DataWarehouseSavedQuery.objects.filter(id=view.id).update(columns={"amount": "Nullable(Int64)"})++ response = self.client.post(+ f"{self._checks_url(view.id)}/",+ {"check_type": CheckType.ACCEPTED_VALUES, "column_name": "amount", "config": {"values": ["1", "2"]}},+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ check = DataQualityCheck.objects.for_team(self.team.id).get(id=response.json()["id"])+ assert check.config["values"] == [1.0, 2.0]+def _deny_the_view(self) -> None:# Deny the default member object-level access to the "orders" view, the way the HogQL# database sees it -- so denied_subject_names() picks it up and the endpoint hides it.diff --git a/products/data_quality/backend/tests/test_compiler.py b/products/data_quality/backend/tests/test_compiler.pyindex 5825efaee4fa..a103ccafaff0 100644--- a/products/data_quality/backend/tests/test_compiler.py+++ b/products/data_quality/backend/tests/test_compiler.py@@ -268,6 +268,67 @@ class TestCheckSerialization:assert canonical == shuffledassert _fingerprint_for(canonical) == _fingerprint_for(shuffled)+ @parameterized.expand(+ [+ ("int_column", "Int64", ["1", "2"], [1.0, 2.0]),+ ("int_column_accepts_a_whole_float", "Int64", [2.0], [2.0]),+ ("nullable_int_column", "Nullable(Int64)", ["1"], [1.0]),+ ("low_cardinality_int_column", "LowCardinality(Int64)", ["1"], [1.0]),+ ("low_cardinality_nullable_int_column", "LowCardinality(Nullable(Int64))", ["1"], [1.0]),+ ("float_column", "Float64", ["1.5"], [1.5]),+ ("bool_column", "Bool", ["true", "FALSE"], [False, True]),+ ("string_column", "String", ["1", "paid"], ["1", "paid"]),+ ("low_cardinality_string_column", "LowCardinality(String)", ["1", "paid"], ["1", "paid"]),+ ("string_column_reads_a_number_as_text", "String", [200], ["200"]),+ ("string_column_reads_a_float_as_text", "String", [1.5], ["1.5"]),+ ("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"]),+ ]+ )+ def test_accepted_values_are_read_as_the_column_reads_them(self, _name, column_type, given, expected) -> None:+ # The editor's value control only produces strings, so without this a numeric column is+ # compared against strings and "1" fingerprints differently from the 1 an agent sends.+ spec = get_spec(CheckType.ACCEPTED_VALUES)+ parsed = spec.validate({"values": given}, "status")++ coerced = spec.coerce_to_column(parsed, column_type)++ assert coerced.model_dump(mode="json")["values"] == expected++ @parameterized.expand(+ [+ ("a word on a numeric column", "Int64", ["paid"]),+ ("a word on a boolean column", "Bool", ["paid"]),+ ("a boolean on a numeric column", "Int64", [True]),+ ("a fraction on an integer column", "Int64", [1.5]),+ ]+ )+ def test_an_accepted_value_the_column_cannot_hold_is_rejected(self, _name, column_type, given) -> None:+ # Better to say so at authoring time than to store a check that can never match a row.+ spec = get_spec(CheckType.ACCEPTED_VALUES)+ parsed = spec.validate({"values": given}, "status")++ with pytest.raises(CheckConfigError):+ spec.coerce_to_column(parsed, column_type)++ @parameterized.expand(+ [+ ("numeric_column", "Int64", "1", 1),+ ("text_column", "String", "200", 200),+ ]+ )+ def test_a_string_and_a_number_for_the_same_value_share_a_fingerprint(+ self, _name, column_type, ui_value, agent_value+ ) -> None:+ # The UI sends a string and an agent sends a bare scalar for the same check; they must upsert+ # onto one row rather than becoming twins, whether the column reads numbers or text.+ spec = get_spec(CheckType.ACCEPTED_VALUES)+ from_ui = spec.coerce_to_column(spec.validate({"values": [ui_value]}, "status"), column_type)+ from_agent = spec.coerce_to_column(spec.validate({"values": [agent_value]}, "status"), column_type)++ assert _fingerprint_for(from_ui.model_dump(mode="json")) == _fingerprint_for(from_agent.model_dump(mode="json"))+def test_configs_that_differ_only_in_json_type_share_a_fingerprint(self) -> None:# Normalizing through the type's model first is what makes this hold: an agent sending# max_age_minutes as "60" must upsert the check it already created with 60, not add a twin.