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(hogql): type datetime subtraction as numeric, not datetime (#96308)

Thomas Obermüller653c3600a0cd
diff --git a/posthog/hogql/functions/clickhouse/conversions.py b/posthog/hogql/functions/clickhouse/conversions.py
index 780ad39c8388..638aaa8edf7c 100644
--- a/posthog/hogql/functions/clickhouse/conversions.py
+++ b/posthog/hogql/functions/clickhouse/conversions.py
@@ -155,7 +155,9 @@ DATE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
((StringType(),), DateType()),
((DateTimeType(),), DateType()),
],
- overloads=[((ast.DateTimeType, ast.DateType), "toDate")],
+ # Only the plain constructor takes a number: toDateOrNull expects a String, and rejects a
+ # Float with code 43. Integer covers `date - date`, Float `timestamp - timestamp`.
+ overloads=[((ast.DateTimeType, ast.DateType, ast.IntegerType, ast.FloatType), "toDate")],
)
for name in ["toDate", "to_date"]
},
@@ -166,7 +168,8 @@ DATE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
# Incorrect for parseDateTime64BestEffortOrNull but it is required because when we overload to toDateTime, we use this to figure out if timestamp is already in a function.
tz_aware=True,
overloads=[
- ((ast.DateTimeType, ast.DateType, ast.IntegerType), "toDateTime"),
+ # Float covers the `timestamp - timestamp` duration, which the parser cannot take.
+ ((ast.DateTimeType, ast.DateType, ast.IntegerType, ast.FloatType), "toDateTime"),
# ((ast.StringType,), "parseDateTime64"),
],
signatures=[
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 47a717190c74..b6e6bad75c12 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -246,6 +246,15 @@ class ClickHousePrinter(BasePrinter):
relevant_clickhouse_name = overload_clickhouse_name
break # Found an overload matching the first function org
+ # A Float duration is Decimal(18, 6) at runtime once the timestamps are DateTime64, and
+ # both constructors reject a Decimal with code 44. toFloat64 is a no-op for a real float.
+ if (
+ args
+ and relevant_clickhouse_name in ("toDate", "toDateTime")
+ and isinstance(first_arg_constant_type, ast.FloatType)
+ ):
+ args[0] = f"toFloat64({args[0]})"
+
if func_meta.tz_aware:
has_tz_override = len(node.args) == func_meta.max_args
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 173e419dec93..19df10ace370 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -3005,6 +3005,21 @@ class TestPrinter(BaseTest):
printed = self._expr("toDateTime(properties.dt_prop AS d)")
self.assertEqual(printed.count("parseDateTime64BestEffortOrNull"), 1, printed)
+ @parameterized.expand(
+ [
+ ("toDate(toDateTime(200000) - toDateTime(100000))", "toDate(toFloat64(minus("),
+ ("toDateTime(toDateTime(200000) - toDateTime(100000))", "toDateTime(toFloat64(minus("),
+ ("toDate(toDate(timestamp) - toDate(timestamp))", "toDate(minus("),
+ ]
+ )
+ def test_date_conversion_of_a_duration_uses_the_plain_constructor(self, expression: str, expected_prefix: str):
+ # The parsers behind these names take only strings (code 43). A datetime duration is a
+ # Decimal once the timestamps are DateTime64, which the constructors reject too (code 44).
+ printed = self._expr(expression)
+ assert "toDateOrNull" not in printed, printed
+ assert "parseDateTime64BestEffort" not in printed, printed
+ assert printed.startswith(expected_prefix), printed
+
def test_window_functions(self):
self.assertEqual(
self._select(
@@ -4164,6 +4179,13 @@ class TestPrinter(BaseTest):
assert "divide(10, 3)" in printed_int, printed_int
assert "divideDecimal" not in printed_int, printed_int
+ # An integer duration unifies with a decimal branch as a decimal, in HogQL and in ClickHouse.
+ printed_branch = self._select(
+ "SELECT if(event = 'x', toDate(timestamp) - toDate(timestamp), rate) / rate AS ratio FROM events",
+ context,
+ )
+ assert "divideDecimal(" in printed_branch, printed_branch
+
def test_sortable_semver(self):
# Also test different capitalizations
printed = self._print(
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 40ea4d094c8e..cd7a1d0dbb0f 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -1833,6 +1833,20 @@ class Resolver(CloningVisitor):
node.type = ast.FloatType()
elif isinstance(left_type, ast.FloatType) and isinstance(right_type, ast.IntegerType):
node.type = ast.FloatType()
+ elif (
+ node.op == ast.ArithmeticOperationOp.Sub
+ and isinstance(left_type, ast.DateTimeType | ast.DateType)
+ and isinstance(right_type, ast.DateTimeType | ast.DateType)
+ ):
+ # ClickHouse returns a number here, not a datetime, and a DateTime type would make the
+ # printer wrap later references in toTimeZone() and fail with code 43. `Date - Date` is
+ # Int32, and an integer unifies with a Decimal branch as ClickHouse does, which keeps
+ # divideDecimal on a division. A DateTime duration is Int32 or Decimal(18, 6), a precision
+ # HogQL does not carry, so Float is the widest numeric safe for both.
+ if isinstance(left_type, ast.DateType) and isinstance(right_type, ast.DateType):
+ node.type = ast.IntegerType()
+ else:
+ node.type = ast.FloatType()
elif isinstance(left_type, ast.DateTimeType) or isinstance(right_type, ast.DateTimeType):
node.type = ast.DateTimeType()
elif isinstance(left_type, ast.DecimalType) or isinstance(right_type, ast.DecimalType):
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 988ec71d0354..f58bf107d4d4 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -1985,6 +1985,23 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.results, [])
self.assertResponseMatchesSnapshot(response)
+ def test_timestamp_subtraction_is_a_numeric_duration(self):
+ # Reading the duration and converting it each failed the whole query with code 43.
+ response = execute_hogql_query(
+ "SELECT gap, toDate(gap) FROM (SELECT toDateTime(200000) - toDateTime(100000) AS gap)",
+ team=self.team,
+ pretty=False,
+ )
+ self.assertEqual(response.results, [(100000, datetime.date(1970, 1, 2))])
+
+ # An events timestamp is DateTime64, so its duration is a Decimal, rejected with code 44.
+ response = execute_hogql_query(
+ "SELECT toDate(gap) FROM (SELECT toDateTime64(200000, 6) - toDateTime64(100000, 6) AS gap)",
+ team=self.team,
+ pretty=False,
+ )
+ self.assertEqual(response.results, [(datetime.date(1970, 1, 2),)])
+
def test_hogql_query_filters_empty_true(self):
query = "SELECT event from events where {filters}"
response = execute_hogql_query(
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index 00392c91197b..3ab1117c5834 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -1455,6 +1455,20 @@ class TestResolver(BaseTest):
node = cast(ast.SelectQuery, resolve_types(node, self.context, dialect="clickhouse"))
self._assert_first_columm_is_type(node, ast.FloatType(nullable=False))
+ # a duration typed as DateTime brings back the toTimeZone wrap that fails with code 43
+ node = self._select("select timestamp - timestamp as key from events")
+ node = cast(ast.SelectQuery, resolve_types(node, self.context, dialect="clickhouse"))
+ self._assert_first_columm_is_type(node, ast.FloatType(nullable=False))
+
+ # Int32 days, where Float would lose divideDecimal on a division of a decimal branch
+ node = self._select("select toDate(timestamp) - toDate(timestamp) as key from events")
+ node = cast(ast.SelectQuery, resolve_types(node, self.context, dialect="clickhouse"))
+ self._assert_first_columm_is_type(node, ast.IntegerType(nullable=False))
+
+ node = self._select("select timestamp - 1 as key from events")
+ node = cast(ast.SelectQuery, resolve_types(node, self.context, dialect="clickhouse"))
+ self._assert_first_columm_is_type(node, ast.DateTimeType(nullable=False))
+
def test_boolean_types(self):
node: ast.SelectQuery = self._select("select true and false as key from events")
node = cast(ast.SelectQuery, resolve_types(node, self.context, dialect="clickhouse"))
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.py
index c6db5f4fb475..ea35f0d9b203 100644
--- a/posthog/hogql/test/test_type_system.py
+++ b/posthog/hogql/test/test_type_system.py
@@ -818,15 +818,16 @@ class TestHogQLTypeSystem:
# Falls through to the `*OrNull` parser, so the result really can be NULL.
("toDate", [ast.StringType(nullable=False)], True),
("toDateTime", [ast.StringType(nullable=False)], True),
- # toDate overloads only for Date/DateTime, so an integer still parses.
- ("toDate", [ast.IntegerType(nullable=False)], True),
# toDateTimeUS declares no overloads at all — always the US best-effort parser.
("toDateTimeUS", [ast.StringType(nullable=False)], True),
("toDateTimeUS", [ast.DateTimeType(nullable=False)], True),
# An overload wins, printing the plain constructor, which cannot fail.
("toDate", [ast.DateTimeType(nullable=False)], False),
("toDateTime", [ast.DateTimeType(nullable=False)], False),
+ ("toDate", [ast.IntegerType(nullable=False)], False),
("toDateTime", [ast.IntegerType(nullable=False)], False),
+ ("toDate", [ast.FloatType(nullable=False)], False),
+ ("toDateTime", [ast.FloatType(nullable=False)], False),
# `_toDate` is already the plain constructor, so it never parses.
("_toDate", [ast.StringType(nullable=False)], False),
# A nullable argument stays nullable down either path.