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.

chore(error-tracking): split issue filter operator mapping into tables (#105811)

posthog[bot]947c3be7532e
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_builder.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_builder.py
index 179162b4c235..a86fae439f05 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_builder.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_builder.py
@@ -1,4 +1,5 @@
import datetime
+from collections.abc import Callable
from typing import Any, cast
from django.core.exceptions import ValidationError
@@ -131,6 +132,83 @@ def _fingerprint_hash_expr() -> ast.Call:
)
+def _constant_value(value: Any) -> ast.Expr:
+ return ast.Constant(value=value)
+
+
+def _date_time_value(value: Any) -> ast.Expr:
+ return ast.Call(name="toDateTime", args=[ast.Constant(value=str(value))])
+
+
+# Issue filter keys, as sent by the frontend, each mapped to the denormalized
+# issue field and the constructor its values need. The frontend sends the
+# description filter under both names.
+_ISSUE_FILTER_FIELDS: dict[str, tuple[str, Callable[[Any], ast.Expr]]] = {
+ "name": ("issue_name", _constant_value),
+ "description": ("issue_description", _constant_value),
+ "issue_description": ("issue_description", _constant_value),
+ "status": ("issue_status", _constant_value),
+ "severity": ("issue_severity", _constant_value),
+ # A date needs an explicit cast to compare chronologically.
+ "first_seen": ("first_seen", _date_time_value),
+}
+
+# A filter carrying several values compares with the membership operator
+# instead, so each entry holds the single-value operator and that one.
+_MEMBERSHIP_OPERATORS: dict[PropertyOperator, tuple[ast.CompareOperationOp, ast.CompareOperationOp]] = {
+ PropertyOperator.EXACT: (ast.CompareOperationOp.Eq, ast.CompareOperationOp.In),
+ PropertyOperator.IS_NOT: (ast.CompareOperationOp.NotEq, ast.CompareOperationOp.NotIn),
+}
+
+_PATTERN_OPERATORS: dict[PropertyOperator, tuple[str, ast.CompareOperationOp]] = {
+ PropertyOperator.ICONTAINS: ("%{}%", ast.CompareOperationOp.ILike),
+ PropertyOperator.NOT_ICONTAINS: ("%{}%", ast.CompareOperationOp.NotILike),
+ PropertyOperator.STARTS_WITH: ("{}%", ast.CompareOperationOp.ILike),
+ PropertyOperator.NOT_STARTS_WITH: ("{}%", ast.CompareOperationOp.NotILike),
+ PropertyOperator.ENDS_WITH: ("%{}", ast.CompareOperationOp.ILike),
+ PropertyOperator.NOT_ENDS_WITH: ("%{}", ast.CompareOperationOp.NotILike),
+}
+
+_RANGE_OPERATORS: dict[PropertyOperator, ast.CompareOperationOp] = {
+ PropertyOperator.GT: ast.CompareOperationOp.Gt,
+ PropertyOperator.IS_DATE_AFTER: ast.CompareOperationOp.Gt,
+ PropertyOperator.GTE: ast.CompareOperationOp.GtEq,
+ PropertyOperator.LT: ast.CompareOperationOp.Lt,
+ PropertyOperator.IS_DATE_BEFORE: ast.CompareOperationOp.Lt,
+ PropertyOperator.LTE: ast.CompareOperationOp.LtEq,
+}
+
+_NULLABILITY_OPERATORS: dict[PropertyOperator, ast.CompareOperationOp] = {
+ PropertyOperator.IS_SET: ast.CompareOperationOp.NotEq,
+ PropertyOperator.IS_NOT_SET: ast.CompareOperationOp.Eq,
+}
+
+
+def _comparable_values(raw_value: Any) -> list[str | float | bool]:
+ """Keep only the values ClickHouse can compare against an issue field."""
+ candidates = raw_value if isinstance(raw_value, list) else [raw_value]
+ return [candidate for candidate in candidates if isinstance(candidate, (str, float, bool))]
+
+
+def _membership_comparison(
+ field: ast.Expr,
+ operators: tuple[ast.CompareOperationOp, ast.CompareOperationOp],
+ raw_value: Any,
+ make_value: Callable[[Any], ast.Expr],
+) -> ast.Expr | None:
+ single_operator, many_operator = operators
+ values = _comparable_values(raw_value)
+ if not values:
+ return None
+ if len(values) == 1:
+ return ast.CompareOperation(op=single_operator, left=field, right=make_value(values[0]))
+ return ast.CompareOperation(
+ op=many_operator,
+ left=field,
+ right=ast.Tuple(exprs=[make_value(value) for value in values]),
+ )
+
+
class ErrorTrackingQueryBuilder:
"""ClickHouse-only query builder using the denormalized fingerprint table.
@@ -941,99 +1019,23 @@ class ErrorTrackingQueryBuilder:
return property_to_expr(cast(Any, value), self.team, scope="event")
def _issue_property_to_ast(self, prop: ErrorTrackingIssueFilter) -> ast.Expr | None:
- key = "description" if prop.key == "issue_description" else prop.key
-
- field_name_map: dict[str, str] = {
- "name": "issue_name",
- "description": "issue_description",
- "status": "issue_status",
- "severity": "issue_severity",
- "first_seen": "first_seen",
- }
-
- field_name = field_name_map.get(key)
- if field_name is None:
+ filter_field = _ISSUE_FILTER_FIELDS.get(prop.key)
+ if filter_field is None:
return None
+ field_name, make_value = filter_field
field = self._legacy_issue_state_expr(field_name)
- value = prop.value
operator = prop.operator
- def make_value(v) -> ast.Expr:
- if key == "first_seen":
- return ast.Call(name="toDateTime", args=[ast.Constant(value=str(v))])
- return ast.Constant(value=v)
-
- def normalize_values(raw_value: object | list[object]) -> list[str | float | bool]:
- candidates = raw_value if isinstance(raw_value, list) else [raw_value]
- return [candidate for candidate in candidates if isinstance(candidate, (str, float, bool))]
-
- if operator == PropertyOperator.EXACT:
- values = normalize_values(value)
- if not values:
- return None
- if len(values) == 1:
- return ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=field, right=make_value(values[0]))
- return ast.CompareOperation(
- op=ast.CompareOperationOp.In,
- left=field,
- right=ast.Tuple(exprs=[make_value(v) for v in values]),
- )
-
- if operator == PropertyOperator.IS_NOT:
- not_values = normalize_values(value)
- if not not_values:
- return None
- if len(not_values) == 1:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.NotEq, left=field, right=make_value(not_values[0])
- )
- return ast.CompareOperation(
- op=ast.CompareOperationOp.NotIn,
- left=field,
- right=ast.Tuple(exprs=[make_value(v) for v in not_values]),
- )
-
- if operator == PropertyOperator.ICONTAINS:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.ILike, left=field, right=ast.Constant(value=f"%{value}%")
- )
-
- if operator == PropertyOperator.NOT_ICONTAINS:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.NotILike, left=field, right=ast.Constant(value=f"%{value}%")
- )
-
- if operator in (
- PropertyOperator.STARTS_WITH,
- PropertyOperator.NOT_STARTS_WITH,
- PropertyOperator.ENDS_WITH,
- PropertyOperator.NOT_ENDS_WITH,
- ):
- prefix_match = operator in (PropertyOperator.STARTS_WITH, PropertyOperator.NOT_STARTS_WITH)
- negated = operator in (PropertyOperator.NOT_STARTS_WITH, PropertyOperator.NOT_ENDS_WITH)
+ if (membership := _MEMBERSHIP_OPERATORS.get(operator)) is not None:
+ return _membership_comparison(field, membership, prop.value, make_value)
+ if (pattern := _PATTERN_OPERATORS.get(operator)) is not None:
+ template, pattern_operator = pattern
return ast.CompareOperation(
- op=ast.CompareOperationOp.NotILike if negated else ast.CompareOperationOp.ILike,
- left=field,
- right=ast.Constant(value=f"{value}%" if prefix_match else f"%{value}"),
+ op=pattern_operator, left=field, right=ast.Constant(value=template.format(prop.value))
)
-
- if operator in (PropertyOperator.GT, PropertyOperator.IS_DATE_AFTER):
- return ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=field, right=make_value(value))
-
- if operator == PropertyOperator.GTE:
- return ast.CompareOperation(op=ast.CompareOperationOp.GtEq, left=field, right=make_value(value))
-
- if operator in (PropertyOperator.LT, PropertyOperator.IS_DATE_BEFORE):
- return ast.CompareOperation(op=ast.CompareOperationOp.Lt, left=field, right=make_value(value))
-
- if operator == PropertyOperator.LTE:
- return ast.CompareOperation(op=ast.CompareOperationOp.LtEq, left=field, right=make_value(value))
-
- if operator == PropertyOperator.IS_SET:
- return ast.CompareOperation(op=ast.CompareOperationOp.NotEq, left=field, right=ast.Constant(value=None))
-
- if operator == PropertyOperator.IS_NOT_SET:
- return ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=field, right=ast.Constant(value=None))
-
+ if (range_operator := _RANGE_OPERATORS.get(operator)) is not None:
+ return ast.CompareOperation(op=range_operator, left=field, right=make_value(prop.value))
+ if (nullability_operator := _NULLABILITY_OPERATORS.get(operator)) is not None:
+ return ast.CompareOperation(op=nullability_operator, left=field, right=ast.Constant(value=None))
return None
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
index 2f5bb70044b1..c53101303fea 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
@@ -1036,6 +1036,150 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
expected_severity = ErrorTrackingIssue.Severity.HIGH if result["id"] == self.issue_id_one else None
self.assertEqual(result["severity"], expected_severity)
+ @parameterized.expand(
+ [
+ ("exact_single", "name", PropertyOperator.EXACT, ["TypeError"], "equals(e.issue_name, 'TypeError')"),
+ (
+ "exact_multiple",
+ "name",
+ PropertyOperator.EXACT,
+ ["TypeError", "ReferenceError"],
+ "in(e.issue_name, tuple('TypeError', 'ReferenceError'))",
+ ),
+ ("is_not_single", "name", PropertyOperator.IS_NOT, ["TypeError"], "notEquals(e.issue_name, 'TypeError')"),
+ (
+ "is_not_multiple",
+ "name",
+ PropertyOperator.IS_NOT,
+ ["TypeError", "ReferenceError"],
+ "notIn(e.issue_name, tuple('TypeError', 'ReferenceError'))",
+ ),
+ ("icontains", "name", PropertyOperator.ICONTAINS, "Type", "ilike(e.issue_name, '%Type%')"),
+ (
+ "not_icontains",
+ "name",
+ PropertyOperator.NOT_ICONTAINS,
+ "Type",
+ "notILike(e.issue_name, '%Type%')",
+ ),
+ ("starts_with", "name", PropertyOperator.STARTS_WITH, "Type", "ilike(e.issue_name, 'Type%')"),
+ (
+ "not_starts_with",
+ "name",
+ PropertyOperator.NOT_STARTS_WITH,
+ "Type",
+ "notILike(e.issue_name, 'Type%')",
+ ),
+ ("ends_with", "name", PropertyOperator.ENDS_WITH, "Error", "ilike(e.issue_name, '%Error')"),
+ (
+ "not_ends_with",
+ "name",
+ PropertyOperator.NOT_ENDS_WITH,
+ "Error",
+ "notILike(e.issue_name, '%Error')",
+ ),
+ ("is_set", "severity", PropertyOperator.IS_SET, True, "notEquals(e.issue_severity, NULL)"),
+ ("is_not_set", "severity", PropertyOperator.IS_NOT_SET, True, "equals(e.issue_severity, NULL)"),
+ (
+ "description_key_alias",
+ "issue_description",
+ PropertyOperator.ICONTAINS,
+ "boom",
+ "ilike(e.issue_description, '%boom%')",
+ ),
+ (
+ "first_seen_gt",
+ "first_seen",
+ PropertyOperator.GT,
+ "2022-01-01",
+ "greater(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_gte",
+ "first_seen",
+ PropertyOperator.GTE,
+ "2022-01-01",
+ "greaterOrEquals(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_lt",
+ "first_seen",
+ PropertyOperator.LT,
+ "2022-01-01",
+ "less(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_lte",
+ "first_seen",
+ PropertyOperator.LTE,
+ "2022-01-01",
+ "lessOrEquals(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_is_date_after",
+ "first_seen",
+ PropertyOperator.IS_DATE_AFTER,
+ "2022-01-01",
+ "greater(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_is_date_before",
+ "first_seen",
+ PropertyOperator.IS_DATE_BEFORE,
+ "2022-01-01",
+ "less(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_exact_single",
+ "first_seen",
+ PropertyOperator.EXACT,
+ ["2022-01-01"],
+ "equals(e.issue_first_seen, toDateTime('2022-01-01'))",
+ ),
+ (
+ "first_seen_exact_multiple",
+ "first_seen",
+ PropertyOperator.EXACT,
+ ["2022-01-01", "2022-01-02"],
+ "in(e.issue_first_seen, tuple(toDateTime('2022-01-01'), toDateTime('2022-01-02')))",
+ ),
+ (
+ "description_key",
+ "description",
+ PropertyOperator.ICONTAINS,
+ "boom",
+ "ilike(e.issue_description, '%boom%')",
+ ),
+ ("unsupported_operator", "name", PropertyOperator.REGEX, "Type.*", None),
+ ("unsupported_key", "assignee", PropertyOperator.EXACT, ["1"], None),
+ ("empty_value", "name", PropertyOperator.EXACT, [], None),
+ ]
+ )
+ def test_issue_filter_operator_mapping(self, _name, key, operator, value, expected_hogql):
+ builder = ErrorTrackingQueryBuilder(
+ query=ErrorTrackingQuery(
+ kind="ErrorTrackingQuery",
+ dateRange=DateRange(date_from="-7d"),
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[ErrorTrackingIssueFilter(key=key, value=value, operator=operator)],
+ )
+ ],
+ ),
+ orderBy="last_seen",
+ volumeResolution=1,
+ ),
+ team=self.team,
+ date_from=datetime(2022, 1, 3, tzinfo=UTC),
+ date_to=datetime(2022, 1, 10, tzinfo=UTC),
+ )
+
+ expr = builder._user_filter_expr()
+ self.assertEqual(None if expr is None else expr.to_hogql(), expected_hogql)
+
@parameterized.expand(
[
(