Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(experiments): reject warehouse metric timestamp columns that are not dates (#118472)

Juraj Majerikdb80cbfc491d
diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.py
index d56f5dbd44b3..925521e69542 100644
--- a/products/experiments/backend/experiment_saved_metric_service.py
+++ b/products/experiments/backend/experiment_saved_metric_service.py
@@ -16,7 +16,7 @@ from products.experiments.backend.metric_validation import (
validate_metric_action_ids,
)
from products.experiments.backend.models.experiment import ExperimentSavedMetric, saved_metric_has_legacy_query
-from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_access
+from products.experiments.backend.warehouse_access_control import validate_warehouse_metrics
class ExperimentSavedMetricService:
@@ -44,7 +44,7 @@ class ExperimentSavedMetricService:
"""Create a saved metric with full business-logic validation."""
normalized_query = self.normalize_query_for_write(query)
validate_metric_action_ids([normalized_query], self.team, user=self.user)
- enforce_warehouse_metric_access([normalized_query], team=self.team, user=self.user)
+ validate_warehouse_metrics([normalized_query], team=self.team, user=self.user)
return ExperimentSavedMetric.objects.create(
team=self.team,
@@ -68,7 +68,7 @@ class ExperimentSavedMetricService:
validate_metric_action_ids(
[update_data["query"]], self.team, user=self.user, known_action_ids=stored_action_ids
)
- enforce_warehouse_metric_access([update_data["query"]], team=self.team, user=self.user)
+ validate_warehouse_metrics([update_data["query"]], team=self.team, user=self.user)
for attr, value in update_data.items():
setattr(saved_metric, attr, value)
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 8d11b0b6a39b..02b6fa55673e 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -98,7 +98,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.result_serialization import strip_step_sessions
-from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_access
+from products.experiments.backend.warehouse_access_control import validate_warehouse_metrics
from products.feature_flags.backend.api.feature_flag import parse_created_by_ids
from products.feature_flags.backend.facade.api import (
archive_flag,
@@ -1174,7 +1174,7 @@ class ExperimentService:
if not allow_unknown_events:
self.validate_metric_event_names(metrics)
self.validate_metric_event_names(metrics_secondary)
- enforce_warehouse_metric_access(
+ validate_warehouse_metrics(
[
*(metrics or []),
*(metrics_secondary or []),
@@ -3445,7 +3445,7 @@ class ExperimentService:
require_existing=False,
)
- enforce_warehouse_metric_access(
+ validate_warehouse_metrics(
[
*(update_data.get("metrics") or []),
*(update_data.get("metrics_secondary") or []),
@@ -4582,7 +4582,7 @@ class ExperimentService:
raise ValidationError("Cannot recalculate timeseries for experiment that hasn't started")
# The backfill runs this metric without a user, so the caller's warehouse access is checked here.
- enforce_warehouse_metric_access([metric], team=self.team, user=self.user)
+ validate_warehouse_metrics([metric], team=self.team, user=self.user)
existing_recalculation = ExperimentTimeseriesRecalculation.objects.filter(
experiment=experiment,
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 9bafe329dee7..0a03b0110b34 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -25,6 +25,8 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.query import execute_hogql_query
@@ -72,6 +74,7 @@ from products.experiments.backend.metric_resolution import metric_reads_data_war
from products.experiments.backend.metric_utils import get_default_metric_title
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+from products.experiments.backend.warehouse_timestamp_validation import enforce_warehouse_metric_timestamp_types
logger = structlog.get_logger(__name__)
@@ -441,12 +444,29 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
settings.join_algorithm = "grace_hash"
settings.grace_hash_join_initial_buckets = 2
+ # Built once here and handed to the executor, so the timestamp check reads the same catalog
+ # the query runs against. The column can change type after the metric was saved.
+ database = Database.create_for(
+ team=self.team,
+ user=self.user,
+ modifiers=modifiers,
+ timings=self.timings,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
+ )
+ enforce_warehouse_metric_timestamp_types([self.metric.model_dump(mode="json")], database)
+
response = execute_hogql_query(
query_type="ExperimentQuery",
query=experiment_query_ast,
team=self.team,
user=self.user,
bypass_warehouse_access_control=self.bypass_warehouse_access_control,
+ context=HogQLContext(
+ team_id=self.team.pk,
+ user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
+ database=database,
+ ),
timings=self.timings,
modifiers=modifiers,
settings=settings,
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
index 7ba382cca5d3..d0ccdd70d5e5 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
@@ -6,6 +6,7 @@ from posthog.test.base import _create_event, _create_person, flush_persons_and_e
from django.test import override_settings
from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
from posthog.schema import (
ExperimentDataWarehouseNode,
@@ -23,10 +24,48 @@ from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import count_cohort_members
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
+ def test_query_runner_rejects_string_timestamp_column(self):
+ feature_flag = self.create_feature_flag()
+ experiment = self.create_experiment(
+ feature_flag=feature_flag, start_date=datetime(2023, 1, 1), end_date=datetime(2023, 1, 31)
+ )
+ # A saved metric whose timestamp column is a string must fail with the column named, not
+ # with a ClickHouse type error from the date range comparison.
+ credential = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="string_timestamps",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ credential=credential,
+ url_pattern="s3://bucket/string_timestamps/*",
+ columns={"userid": "String", "created_at": "String"},
+ )
+ metric = ExperimentMeanMetric(
+ source=ExperimentDataWarehouseNode(
+ table_name=table.name,
+ events_join_key="distinct_id",
+ data_warehouse_join_key="userid",
+ timestamp_field="created_at",
+ math=ExperimentMetricMathType.TOTAL,
+ ),
+ )
+ experiment.metrics = [metric.model_dump(mode="json")]
+ experiment.save()
+ experiment_query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
+
+ with self.assertRaises(ValidationError) as context:
+ ExperimentQueryRunner(query=experiment_query, team=self.team).calculate()
+
+ assert (
+ "Column 'created_at' on data warehouse table 'string_timestamps' is not a date or datetime column"
+ in str(context.exception)
+ )
+
@snapshot_clickhouse_queries
def test_query_runner_group_aggregation_data_warehouse_mean_metric(self):
feature_flag = self.create_feature_flag()
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 8119c3dcfd1a..774196f2d0ff 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -7585,6 +7585,59 @@ class TestValidateExcludedVariants:
ExperimentService.validate_excluded_variants(value)
+class TestExperimentServiceWarehouseTimestampColumn(APIBaseTest):
+ def _table_with_timestamp_type(self, column_type: str) -> DataWarehouseTable:
+ credential = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=self.team)
+ return DataWarehouseTable.objects.create(
+ name="orders",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ credential=credential,
+ url_pattern="s3://bucket/orders/*",
+ columns={"id": "String", "ordered_at": column_type},
+ )
+
+ def _dw_metric(self, table: DataWarehouseTable) -> dict:
+ return {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {
+ "kind": "ExperimentDataWarehouseNode",
+ "table_name": table.name,
+ "events_join_key": "distinct_id",
+ "data_warehouse_join_key": "id",
+ "timestamp_field": "ordered_at",
+ "math": "total",
+ },
+ }
+
+ @parameterized.expand([("string", "String"), ("integer", "Int64")])
+ def test_create_experiment_rejects_non_datetime_timestamp_column(self, _name: str, column_type: str):
+ table = self._table_with_timestamp_type(column_type)
+ service = ExperimentService(team=self.team, user=self.user)
+ with pytest.raises(ValidationError, match="is not a date or datetime column"):
+ service.create_experiment(
+ name="DW experiment",
+ feature_flag_key="dw-timestamp",
+ metrics=[self._dw_metric(table)],
+ allow_unknown_events=True,
+ )
+ assert not Experiment.objects.filter(team=self.team, name="DW experiment").exists()
+
+ @parameterized.expand([("datetime", "DateTime"), ("date", "Date")])
+ def test_create_experiment_accepts_date_timestamp_column(self, _name: str, column_type: str):
+ table = self._table_with_timestamp_type(column_type)
+ service = ExperimentService(team=self.team, user=self.user)
+ experiment = service.create_experiment(
+ name="DW experiment",
+ feature_flag_key="dw-timestamp",
+ metrics=[self._dw_metric(table)],
+ allow_unknown_events=True,
+ )
+ assert experiment.metrics is not None
+ assert experiment.metrics[0]["source"]["timestamp_field"] == "ordered_at"
+
+
@patch("posthoganalytics.feature_enabled", new=MagicMock(return_value=True))
class TestExperimentServiceWarehouseMetricAccess(APIBaseTest):
def setUp(self):
diff --git a/products/experiments/backend/test/test_warehouse_timestamp_validation.py b/products/experiments/backend/test/test_warehouse_timestamp_validation.py
new file mode 100644
index 000000000000..a59c5ef39abd
--- /dev/null
+++ b/products/experiments/backend/test/test_warehouse_timestamp_validation.py
@@ -0,0 +1,60 @@
+from collections.abc import Collection
+
+from unittest.mock import MagicMock
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql import ast
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.models import (
+ DateTimeDatabaseField,
+ ExpressionField,
+ FieldOrTable,
+ StringDatabaseField,
+ Table,
+)
+
+from products.experiments.backend.warehouse_timestamp_validation import enforce_warehouse_metric_timestamp_types
+
+
+class TestEnforceWarehouseMetricTimestampTypes(SimpleTestCase):
+ def _metric(self, table_name: str = "payments", column: str = "created_at") -> dict:
+ return {
+ "kind": "ExperimentMetric",
+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": table_name, "timestamp_field": column},
+ }
+
+ def _database(self, tables: dict[str, FieldOrTable], *, denied: Collection[str] = ()) -> MagicMock:
+ database = MagicMock(spec=Database)
+ database.has_table.side_effect = lambda name: name in tables
+ database.is_table_access_denied.side_effect = lambda name: name in denied
+ database.get_table.side_effect = lambda name: Table(fields={"created_at": tables[name]})
+ return database
+
+ @parameterized.expand(
+ [
+ ("datetime", DateTimeDatabaseField(name="created_at")),
+ # Curated sources expose converted datetimes as computed columns.
+ ("computed", ExpressionField(name="created_at", expr=ast.Call(name="toDateTime", args=[]))),
+ ]
+ )
+ def test_accepts_date_like_columns(self, _name: str, field: FieldOrTable) -> None:
+ enforce_warehouse_metric_timestamp_types([self._metric()], self._database({"payments": field}))
+
+ def test_rejects_plain_string_column_on_any_table_in_the_metric(self) -> None:
+ database = self._database(
+ {"payments": DateTimeDatabaseField(name="created_at"), "refunds": StringDatabaseField(name="created_at")}
+ )
+ with self.assertRaisesMessage(
+ ValidationError, "Column 'created_at' on data warehouse table 'refunds' is not a date or datetime column"
+ ):
+ enforce_warehouse_metric_timestamp_types([self._metric("payments"), self._metric("refunds")], database)
+
+ def test_skips_table_the_caller_is_denied(self) -> None:
+ # The query must fail on access later, as it did before this check existed.
+ database = self._database({"payments": StringDatabaseField(name="created_at")}, denied={"payments"})
+ enforce_warehouse_metric_timestamp_types([self._metric()], database)
+ database.get_table.assert_not_called()
diff --git a/products/experiments/backend/warehouse_access_control.py b/products/experiments/backend/warehouse_access_control.py
index 755c5e7ed07b..3feb29e1300a 100644
--- a/products/experiments/backend/warehouse_access_control.py
+++ b/products/experiments/backend/warehouse_access_control.py
@@ -8,30 +8,36 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.experiments.backend.metric_utils import collect_metric_warehouse_tables
+from products.experiments.backend.warehouse_timestamp_validation import enforce_warehouse_metric_timestamp_types
-def enforce_warehouse_metric_access(metrics: list[dict[str, Any]], *, team: Team, user: Any) -> None:
- """Raise PermissionDenied if a metric uses an ExperimentDataWarehouseNode whose warehouse table
- or view the user can't access.
+def validate_warehouse_metrics(metrics: list[dict[str, Any]], *, team: Team, user: Any) -> None:
+ """Check the warehouse tables a metric uses before it is saved: access first, then column types.
- Background recomputes bypass warehouse access control (they run without a request user), so access
- must be enforced when the metric is created or updated — otherwise an inaccessible table would be
- saved and only fail later, during recalculation.
+ Raise PermissionDenied if a metric uses an ExperimentDataWarehouseNode whose warehouse table
+ or view the user can't access. Background recomputes bypass warehouse access control (they
+ run without a request user), so access must be enforced when the metric is created or
+ updated — otherwise an inaccessible table would be saved and only fail later, during
+ recalculation. The access decision is delegated to the HogQL database build (the same code
+ that enforces warehouse access at query time) rather than re-derived here.
- The access decision is delegated to the HogQL database build (the same code that enforces
- warehouse access at query time) rather than re-derived here.
+ Raise ValidationError if a metric's timestamp_field is not a date or datetime column, so the
+ metric does not save and then fail on every recalculation.
"""
- # Synthetic principals (project secret API keys) and anonymous/userless callers bypass warehouse
- # access control at query time, so there's nothing to enforce against here.
- if not isinstance(user, User):
- return
-
table_names = collect_metric_warehouse_tables(metrics)
if not table_names:
# No warehouse nodes in the metric — skip the database build.
return
- database = Database.create_for(team=team, user=user)
- blocked = sorted(name for name in table_names if database.is_table_access_denied(name))
- if blocked:
- raise PermissionDenied("You don't have access to data warehouse table(s): " + ", ".join(blocked))
+ # Synthetic principals (project secret API keys) and anonymous/userless callers bypass warehouse
+ # access control at query time, so there's nothing to enforce against for them.
+ is_user = isinstance(user, User)
+ database = Database.create_for(
+ team=team, user=user if is_user else None, bypass_warehouse_access_control=not is_user
+ )
+ if is_user:
+ blocked = sorted(name for name in table_names if database.is_table_access_denied(name))
+ if blocked:
+ raise PermissionDenied("You don't have access to data warehouse table(s): " + ", ".join(blocked))
+
+ enforce_warehouse_metric_timestamp_types(metrics, database)
diff --git a/products/experiments/backend/warehouse_timestamp_validation.py b/products/experiments/backend/warehouse_timestamp_validation.py
new file mode 100644
index 000000000000..f5805b9b9f43
--- /dev/null
+++ b/products/experiments/backend/warehouse_timestamp_validation.py
@@ -0,0 +1,88 @@
+from typing import Any
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.models import (
+ BooleanDatabaseField,
+ DateTimeArrayDatabaseField,
+ DecimalDatabaseField,
+ FloatArrayDatabaseField,
+ FloatDatabaseField,
+ IntegerArrayDatabaseField,
+ IntegerDatabaseField,
+ StringArrayDatabaseField,
+ StringDatabaseField,
+ StringJSONDatabaseField,
+ StructDatabaseField,
+ UUIDDatabaseField,
+)
+
+from posthog.dataclasses import frozen
+
+# Only plain non-date column types are rejected. A computed column (ExpressionField, which curated
+# sources use for datetime conversions) or an unknown type passes, and fails later if it is wrong.
+_NON_DATE_FIELD_TYPES = (
+ StringDatabaseField,
+ IntegerDatabaseField,
+ FloatDatabaseField,
+ DecimalDatabaseField,
+ BooleanDatabaseField,
+ UUIDDatabaseField,
+ StringJSONDatabaseField,
+ StructDatabaseField,
+ StringArrayDatabaseField,
+ FloatArrayDatabaseField,
+ IntegerArrayDatabaseField,
+ DateTimeArrayDatabaseField,
+)
+
+
+@frozen(order=True)
+class WarehouseTimestampColumn:
+ table_name: str
+ column: str
+
+
+def collect_metric_warehouse_timestamp_columns(metrics: list[dict[str, Any]]) -> set[WarehouseTimestampColumn]:
+ """Collect the timestamp columns of the ExperimentDataWarehouseNodes in metric queries."""
+ columns: set[WarehouseTimestampColumn] = set()
+ stack: list[Any] = list(metrics)
+ while stack:
+ obj = stack.pop()
+ if isinstance(obj, dict):
+ if (
+ obj.get("kind") == "ExperimentDataWarehouseNode"
+ and obj.get("table_name")
+ and obj.get("timestamp_field")
+ ):
+ columns.add(WarehouseTimestampColumn(table_name=obj["table_name"], column=obj["timestamp_field"]))
+ stack.extend(obj.values())
+ elif isinstance(obj, list):
+ stack.extend(obj)
+ return columns
+
+
+def enforce_warehouse_metric_timestamp_types(metrics: list[dict[str, Any]], database: Database) -> None:
+ """Raise ValidationError when a warehouse metric's timestamp_field is a plain non-date column.
+
+ The query builders compare that column with the experiment's date range and the exposure
+ time, so a string or integer column fails inside ClickHouse with a type error that names
+ neither the metric nor the column.
+
+ `database` is the caller's HogQL database, built with its own access context: a table the
+ caller is denied is skipped here, so the query fails on access as it did before.
+ """
+ for timestamp in sorted(collect_metric_warehouse_timestamp_columns(metrics)):
+ # A missing table or column fails later with its own error.
+ if not database.has_table(timestamp.table_name) or database.is_table_access_denied(timestamp.table_name):
+ continue
+ field = database.get_table(timestamp.table_name).fields.get(timestamp.column)
+ if not isinstance(field, _NON_DATE_FIELD_TYPES):
+ continue
+ # The message is persisted on background recomputes, which bypass warehouse access, and shown to
+ # every experiment viewer. It names only what the metric config already shows, not the column type.
+ raise ValidationError(
+ f"Column '{timestamp.column}' on data warehouse table '{timestamp.table_name}' is not a date or "
+ "datetime column, but the timestamp field must be one. Create a view that converts it and use the view."
+ )