: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(error-tracking): sort the issue list by severity (#116293)
James Gille73c7f006004
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex e067ad4cb34c..6b3a49418395 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -24011,7 +24011,7 @@"type": "string"},"ErrorTrackingOrderBy": {- "enum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],+ "enum": ["last_seen", "first_seen", "occurrences", "users", "sessions", "severity"],"title": "ErrorTrackingOrderBy","type": "string"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 53cf147d8e38..a4111621b37e 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -4337,7 +4337,7 @@ export type CachedSessionAttributionExplorerQueryResponse = CachedQueryResponse</* Error Tracking *//** @title ErrorTrackingOrderBy */-export type ErrorTrackingOrderBy = 'last_seen' | 'first_seen' | 'occurrences' | 'users' | 'sessions'+export type ErrorTrackingOrderBy = 'last_seen' | 'first_seen' | 'occurrences' | 'users' | 'sessions' | 'severity'/** @title ErrorTrackingQueryIssueSeverity */export type ErrorTrackingQueryIssueSeverity = 'low' | 'medium' | 'high' | 'critical'diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex fa51f0151aad..976b7ea20661 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1317,6 +1317,7 @@ class ErrorTrackingOrderBy(StrEnum):OCCURRENCES = "occurrences"USERS = "users"SESSIONS = "sessions"+ SEVERITY = "severity"class ErrorTrackingQueryIssueSeverity(StrEnum):diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 905b145d9ff3..ce639d3b3775 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -8224,6 +8224,7 @@ export const ErrorTrackingOrderByApi = {Occurrences: 'occurrences',Users: 'users',Sessions: 'sessions',+ Severity: 'severity',} as constexport type OrderDirection2Api = (typeof OrderDirection2Api)[keyof typeof OrderDirection2Api]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.pyindex 4e7574549e57..eb46a0495dfa 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@@ -23,7 +23,7 @@ from products.error_tracking.backend.hogql_queries.error_tracking_query_runner_uextract_aggregations,extract_event,innermost_frame_attribute,- order_direction,+ order_by_exprs,search_tokenizer,select_sparkline_array,)@@ -429,7 +429,7 @@ class ErrorTrackingQueryBuilder:),where=ast.And(exprs=outer_where_exprs) if outer_where_exprs else None,group_by=[ast.Field(chain=["id"])],- order_by=[ast.OrderExpr(expr=ast.Field(chain=[self.query.orderBy]), order=order_direction(self.query))],+ order_by=order_by_exprs(self.query),)def _build_inner_query(self) -> ast.SelectQuery:@@ -741,7 +741,7 @@ class ErrorTrackingQueryBuilder:select_from=select_from,where=ast.And(exprs=self._where_exprs_legacy()),group_by=[ast.Field(chain=["id"])],- order_by=[ast.OrderExpr(expr=ast.Field(chain=[self.query.orderBy]), order=order_direction(self.query))],+ order_by=order_by_exprs(self.query),)def _select_expressions_legacy(self) -> list[ast.Expr]:diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.pyindex 4af48338f7f8..9ec9f9990a88 100644--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py@@ -5,7 +5,7 @@ from uuid import UUIDfrom rest_framework.exceptions import ValidationError as DRFValidationError-from posthog.schema import ErrorTrackingQuery+from posthog.schema import ErrorTrackingOrderBy, ErrorTrackingQuery, ErrorTrackingQueryIssueSeverityfrom posthog.hogql import ast@@ -158,3 +158,43 @@ def order_direction(query: ErrorTrackingQuery) -> Literal["ASC", "DESC"]:if query.orderDirection:return "ASC" if query.orderDirection.value == "ASC" else "DESC"return "ASC" if query.orderBy == "first_seen" else "DESC"+++# Ascending order of seriousness. The sort rank of a row is its position in this list, so the+# order of the entries is the ranking itself. A new level in ErrorTrackingQueryIssueSeverity must+# get a place here as well, or it ranks the same as unset.+SEVERITY_RANKING: list[str] = [+ ErrorTrackingQueryIssueSeverity.LOW.value,+ ErrorTrackingQueryIssueSeverity.MEDIUM.value,+ ErrorTrackingQueryIssueSeverity.HIGH.value,+ ErrorTrackingQueryIssueSeverity.CRITICAL.value,+]+++def order_by_exprs(query: ErrorTrackingQuery) -> list[ast.OrderExpr]:+ direction = order_direction(query)++ if query.orderBy != ErrorTrackingOrderBy.SEVERITY:+ return [ast.OrderExpr(expr=ast.Field(chain=[query.orderBy]), order=direction)]++ # Sorting on the `severity` column itself is wrong two ways, and both fail silently. It is a+ # Nullable(String), so the order is alphabetical (critical, high, low, medium), and ClickHouse+ # ranks NULL above every value, so DESC leads with the unset majority. Sort on the position in+ # SEVERITY_RANKING instead. `indexOf` gives 1 to 4 for a known level and 0 for a value that is+ # not in the array, and a NULL needle also gives 0, so unset ranks below `low`.+ severity_rank = ast.Call(+ name="indexOf",+ args=[+ ast.Array(exprs=[ast.Constant(value=level) for level in SEVERITY_RANKING]),+ ast.Field(chain=["severity"]),+ ],+ )+ # Four levels plus unset leave most rows sharing a rank. The paginator pages with LIMIT/OFFSET+ # over a re-run query, so rows move between pages and the infinite scroll repeats and drops+ # them unless the order is total. `last_seen` puts the most recently seen issue first within a+ # rank, and `id` is the GROUP BY key of both query shapes, so adding it makes the order total.+ return [+ ast.OrderExpr(expr=severity_rank, order=direction),+ ast.OrderExpr(expr=ast.Field(chain=["last_seen"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["id"]), order="DESC"),+ ]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.pyindex 360c869c4895..3d8c6806cf19 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@@ -25,6 +25,7 @@ from posthog.schema import (DateRange,ErrorTrackingIssueFilter,ErrorTrackingQuery,+ ErrorTrackingQueryIssueSeverity,ErrorTrackingSimilarIssuesQuery,EventPropertyFilter,FilterLogicalOperator,@@ -57,7 +58,10 @@ from products.error_tracking.backend.hogql_queries.error_tracking_issue_correlat)from products.error_tracking.backend.hogql_queries.error_tracking_query_builder import ErrorTrackingQueryBuilderfrom products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunner-from products.error_tracking.backend.hogql_queries.error_tracking_query_runner_utils import search_tokenizer+from products.error_tracking.backend.hogql_queries.error_tracking_query_runner_utils import (+ SEVERITY_RANKING,+ search_tokenizer,+)from products.error_tracking.backend.hogql_queries.error_tracking_similar_issues_query_runner import (ErrorTrackingSimilarIssuesQueryRunner,SimilarFingerprint,@@ -89,9 +93,13 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIdeissue_id_one = "01936e7f-d7ff-7314-b2d4-7627981e34f0"issue_id_two = "01936e80-5e69-7e70-b837-871f5cdad28b"issue_id_three = "01936e80-aa51-746f-aec4-cdf16a5c5332"+ issue_id_four = "01936e81-1d2c-7bb6-9f2e-2a1a3a0c54c1"+ issue_id_five = "01936e81-6a73-7f41-8d58-6c0f9e1c7b2a"issue_one_fingerprint = "issue_one_fingerprint"issue_two_fingerprint = "issue_two_fingerprint"issue_three_fingerprint = "issue_three_fingerprint"+ issue_four_fingerprint = "issue_four_fingerprint"+ issue_five_fingerprint = "issue_five_fingerprint"def override_fingerprint(self, fingerprint, issue_id, version=1):update_error_tracking_issue_fingerprints(team_id=self.team.pk, issue_id=issue_id, fingerprints=[fingerprint])@@ -226,6 +234,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIdesearchQuery=None,filterGroup=None,orderBy="last_seen",+ orderDirection=None,status=None,volumeResolution=1,withAggregations=False,@@ -249,6 +258,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIdesearchQuery=searchQuery,filterGroup=filterGroup,orderBy=orderBy, # pyright: ignore[reportArgumentType]+ orderDirection=orderDirection,status=status,volumeResolution=volumeResolution,withFirstEvent=withFirstEvent,@@ -692,6 +702,112 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIderesults = self._calculate(orderBy="first_seen")["results"]self.assertEqual([r["id"] for r in results], [self.issue_id_one, self.issue_id_two, self.issue_id_three])+ def _assign_severities(self):+ # `sync_issues_to_clickhouse` stamps rows with the wall clock as their ReplacingMergeTree+ # version, and the test clock is frozen, so two syncs under one frozen instant write the+ # same version and ClickHouse picks between them arbitrarily. Create at the fixture instant.+ with time_machine.travel("2020-01-10 12:11:00", tick=False):+ for issue_id, fingerprint in (+ (self.issue_id_four, self.issue_four_fingerprint),+ (self.issue_id_five, self.issue_five_fingerprint),+ ):+ self.create_events_and_issue(+ issue_id=issue_id,+ fingerprint=fingerprint,+ distinct_ids=[self.distinct_id_one],+ timestamp=now() - relativedelta(hours=4),+ )+ flush_persons_and_events()++ severities = {+ self.issue_id_one: ErrorTrackingIssue.Severity.CRITICAL,+ self.issue_id_two: ErrorTrackingIssue.Severity.LOW,+ self.issue_id_three: ErrorTrackingIssue.Severity.HIGH,+ self.issue_id_four: ErrorTrackingIssue.Severity.MEDIUM,+ }+ for issue_id, severity in severities.items():+ ErrorTrackingIssue.objects.filter(id=issue_id).update(severity=severity)+ sync_issues_to_clickhouse(issue_ids=list(severities), team_id=self.team.pk)++ def _severity_is_set_filter(self) -> PropertyGroupFilter:+ return PropertyGroupFilter(+ type=FilterLogicalOperator.AND_,+ values=[+ PropertyGroupFilterValue(+ type=FilterLogicalOperator.AND_,+ values=[ErrorTrackingIssueFilter(key="severity", value=True, operator=PropertyOperator.IS_SET)],+ )+ ],+ )++ @parameterized.expand(+ [+ ("descending", "DESC", False),+ ("ascending", "ASC", False),+ ("descending_with_severity_filter", "DESC", True),+ ("ascending_with_severity_filter", "ASC", True),+ ]+ )+ @time_machine.travel("2022-01-10T12:11:00", tick=False)+ def test_severity_ordering(self, _name: str, direction: str, with_severity_filter: bool):+ # A severity filter is an issue-level filter, so it drops the query onto the legacy shape.+ self._assign_severities()+ by_descending_severity = [+ self.issue_id_one,+ self.issue_id_three,+ self.issue_id_four,+ self.issue_id_two,+ self.issue_id_five,+ ]+ filter_group = None+ if with_severity_filter:+ filter_group = self._severity_is_set_filter()+ by_descending_severity = [i for i in by_descending_severity if i != self.issue_id_five]++ expected = by_descending_severity if direction == "DESC" else list(reversed(by_descending_severity))++ results = self._calculate(orderBy="severity", orderDirection=direction, filterGroup=filter_group)["results"]++ self.assertEqual([result["id"] for result in results], expected)++ @parameterized.expand(+ [+ ("optimized_shape_descending", False, "DESC"),+ ("optimized_shape_ascending", False, "ASC"),+ ("legacy_shape_descending", True, "DESC"),+ ("legacy_shape_ascending", True, "ASC"),+ ]+ )+ @time_machine.travel("2022-01-10T12:11:00", tick=False)+ def test_severity_ordering_is_total(self, _name: str, legacy_shape: bool, direction: str):+ # Most rows share a severity, and the paginator pages with LIMIT/OFFSET, so rows repeat and+ # drop between pages unless the tiebreakers make the order total in both directions.+ filter_group = self._severity_is_set_filter() if legacy_shape else None++ builder = ErrorTrackingQueryBuilder(+ query=ErrorTrackingQuery(+ kind="ErrorTrackingQuery",+ dateRange=DateRange(date_from="-7d"),+ filterGroup=filter_group,+ orderBy="severity",+ orderDirection=direction, # pyright: ignore[reportArgumentType]+ volumeResolution=1,+ ),+ team=self.team,+ date_from=datetime(2022, 1, 3, tzinfo=UTC),+ date_to=datetime(2022, 1, 10, tzinfo=UTC),+ )+ self.assertEqual(builder._needs_legacy_shape(), legacy_shape)++ self.assertEqual(+ [(order.expr.to_hogql(), order.order) for order in builder.build_query().order_by or []],+ [+ ("indexOf(['low', 'medium', 'high', 'critical'], severity)", direction),+ ("last_seen", "DESC"),+ ("id", "DESC"),+ ],+ )+@time_machine.travel("2022-01-10T12:11:00", tick=False)def test_status(self):resolved_issue = ErrorTrackingIssue.objects.get(id=self.issue_id_one)@@ -1672,6 +1788,14 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIderunner.validate_query_runner_access(self.user)+class TestSeverityRanking(TestCase):+ def test_ranking_covers_every_severity_level(self):+ # A level the ranking omits gets rank 0 from `indexOf` and silently sorts as unset. The+ # model enum is what reaches the `severity` column, the schema enum is what the API offers.+ self.assertEqual(set(SEVERITY_RANKING), {severity.value for severity in ErrorTrackingQueryIssueSeverity})+ self.assertEqual(set(SEVERITY_RANKING), set(ErrorTrackingIssue.Severity.values))++class TestSearchTokenizer(TestCase):test_cases = [(diff --git a/products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic.ts b/products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic.tsindex 755e2cac9802..f7b079cacc63 100644--- a/products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic.ts+++ b/products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic.ts@@ -30,6 +30,7 @@ export const ORDER_BY_OPTIONS: Record<ErrorTrackingQueryOrderBy, string> = {occurrences: 'Occurrences',users: 'Users',sessions: 'Sessions',+ severity: 'Severity',}const DEFAULT_ORDER_BY: ErrorTrackingQueryOrderBy = 'last_seen'diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 229c1a1558cc..ef5b6b9c607e 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7088,6 +7088,7 @@ export const ErrorTrackingOrderByApi = {Occurrences: 'occurrences',Users: 'users',Sessions: 'sessions',+ Severity: 'severity',} as constexport type OrderDirection2Api = (typeof OrderDirection2Api)[keyof typeof OrderDirection2Api]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 55abd3f763fc..7eca560eb182 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9997,6 +9997,7 @@ export namespace Schemas {Occurrences: 'occurrences',Users: 'users',Sessions: 'sessions',+ Severity: 'severity',} as const;export type OrderDirection2 = typeof OrderDirection2[keyof typeof OrderDirection2];