: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(error-tracking): add safe first-seen filtering (#123025)
James Gill8d1986a9fb21
diff --git a/products/error_tracking/backend/facade/query_utils.py b/products/error_tracking/backend/facade/query_utils.pyindex 7dda41bd47e1..96cc9ec4dcea 100644--- a/products/error_tracking/backend/facade/query_utils.py+++ b/products/error_tracking/backend/facade/query_utils.py@@ -180,6 +180,16 @@ def add_release_filter(filters: list[dict[str, object]], release: str) -> None:def build_issue_filters(params: dict[str, object]) -> list[dict[str, object]]:filters = [dict(item) for item in cast(list[dict[str, object]], params.get("filterGroup", []))]+ first_seen_after = params.get("firstSeenAfter")+ if isinstance(first_seen_after, str):+ filters.append(+ {+ "type": "error_tracking_issue",+ "key": "first_seen",+ "operator": "is_date_after",+ "value": first_seen_after,+ }+ )library = params.get("library")if isinstance(library, str | list):add_event_filter(filters, "$lib", "exact", cast(str | list[str], library))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 eb46a0495dfa..a52afa317227 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@@ -1039,6 +1039,39 @@ class ErrorTrackingQueryBuilder:return property_to_expr(cast(Any, value), self.team, scope="event")+ def _issue_first_seen_range(+ self, field: ast.Expr, range_operator: ast.CompareOperationOp, bound: ast.Expr+ ) -> ast.Expr:+ # A merged issue has one first_seen per fingerprint. Compare the earliest, so a new fingerprint does not make an old issue look new.+ issue_first_seen_in_range = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=self._legacy_issue_state_expr("issue_id"),+ right=ast.SelectQuery(+ select=[ast.Field(chain=["issue_id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "error_tracking_fingerprint_issue_state"])),+ group_by=[ast.Field(chain=["issue_id"])],+ having=ast.CompareOperation(+ op=range_operator,+ left=ast.Call(name="min", args=[ast.Field(chain=["first_seen"])]),+ right=bound,+ ),+ ),+ )+ if not self.include_recent_issue_state:+ return issue_first_seen_in_range+ # A fingerprint not yet synced to ClickHouse has no state row, so compare the event's own value.+ return ast.Or(+ exprs=[+ issue_first_seen_in_range,+ ast.And(+ exprs=[+ ast.Call(name="isNull", args=[ast.Field(chain=["fp_state", "issue_id"])]),+ ast.CompareOperation(op=range_operator, left=field, right=bound),+ ]+ ),+ ]+ )+def _issue_property_to_ast(self, prop: ErrorTrackingIssueFilter) -> ast.Expr | None:filter_field = _ISSUE_FILTER_FIELDS.get(prop.key)if filter_field is None:@@ -1056,6 +1089,8 @@ class ErrorTrackingQueryBuilder:op=pattern_operator, left=field, right=ast.Constant(value=template.format(prop.value)))if (range_operator := _RANGE_OPERATORS.get(operator)) is not None:+ if prop.key == "first_seen":+ return self._issue_first_seen_range(field, range_operator, make_value(prop.value))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))diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambrindex 793462904078..a98ed7090756 100644--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr@@ -216,7 +216,16 @@WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)GROUP BY fp_hashHAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), e__fingerprint_issue_state.fp_hash)- WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), ifNull(greaterOrEquals(e__fingerprint_issue_state.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), in(e__fingerprint_issue_state.issue_id,+ (SELECT posthog__error_tracking_fingerprint_issue_state.issue_id AS issue_id+ FROM+ (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, 'UTC')), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen+ FROM error_tracking_fingerprint_issue_state+ WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)+ GROUP BY fp_hash+ HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS posthog__error_tracking_fingerprint_issue_state+ GROUP BY posthog__error_tracking_fingerprint_issue_state.issue_id+ HAVING ifNull(greaterOrEquals(min(posthog__error_tracking_fingerprint_issue_state.first_seen), parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))))GROUP BY idORDER BY last_seen DESC,id DESC@@ -264,7 +273,16 @@WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)GROUP BY fp_hashHAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), e__fingerprint_issue_state.fp_hash)- WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), ifNull(less(e__fingerprint_issue_state.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), in(e__fingerprint_issue_state.issue_id,+ (SELECT posthog__error_tracking_fingerprint_issue_state.issue_id AS issue_id+ FROM+ (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, 'UTC')), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen+ FROM error_tracking_fingerprint_issue_state+ WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)+ GROUP BY fp_hash+ HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS posthog__error_tracking_fingerprint_issue_state+ GROUP BY posthog__error_tracking_fingerprint_issue_state.issue_id+ HAVING ifNull(less(min(posthog__error_tracking_fingerprint_issue_state.first_seen), parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))))GROUP BY idORDER BY last_seen DESC,id DESCdiff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.new_events_schema.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.new_events_schema.ambrindex f17a7de88f81..f266808aaed5 100644--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.new_events_schema.ambr+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.new_events_schema.ambr@@ -222,7 +222,16 @@WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)GROUP BY fp_hashHAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__fingerprint_issue_state ON equals(cityHash64(if(notEquals(toJSONString(e.properties.^`$exception_fingerprint`), '{}'), toJSONString(e.properties.^`$exception_fingerprint`), if(isNull(nullIf(toString(e.properties.`$exception_fingerprint`), '')), NULL, if(and(in(ascii(toString(e.properties.`$exception_fingerprint`)), tuple(91, 123)), in(ascii(toJSONString(e.properties.`$exception_fingerprint`)), tuple(91, 123))), nullIf(nullIf(toJSONString(e.properties.`$exception_fingerprint`), '[]'), '{}'), toString(e.properties.`$exception_fingerprint`))))), e__fingerprint_issue_state.fp_hash)- WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), ifNull(less(e__fingerprint_issue_state.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), in(e__fingerprint_issue_state.issue_id,+ (SELECT posthog__error_tracking_fingerprint_issue_state.issue_id AS issue_id+ FROM+ (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, 'UTC')), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen+ FROM error_tracking_fingerprint_issue_state+ WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)+ GROUP BY fp_hash+ HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS posthog__error_tracking_fingerprint_issue_state+ GROUP BY posthog__error_tracking_fingerprint_issue_state.issue_id+ HAVING ifNull(less(min(posthog__error_tracking_fingerprint_issue_state.first_seen), parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))))GROUP BY idORDER BY last_seen DESC,id DESC@@ -272,7 +281,16 @@WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)GROUP BY fp_hashHAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__fingerprint_issue_state ON equals(cityHash64(if(notEquals(toJSONString(e.properties.^`$exception_fingerprint`), '{}'), toJSONString(e.properties.^`$exception_fingerprint`), if(isNull(nullIf(toString(e.properties.`$exception_fingerprint`), '')), NULL, if(and(in(ascii(toString(e.properties.`$exception_fingerprint`)), tuple(91, 123)), in(ascii(toJSONString(e.properties.`$exception_fingerprint`)), tuple(91, 123))), nullIf(nullIf(toJSONString(e.properties.`$exception_fingerprint`), '[]'), '{}'), toString(e.properties.`$exception_fingerprint`))))), e__fingerprint_issue_state.fp_hash)- WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), ifNull(greaterOrEquals(e__fingerprint_issue_state.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('2016-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), in(e__fingerprint_issue_state.issue_id,+ (SELECT posthog__error_tracking_fingerprint_issue_state.issue_id AS issue_id+ FROM+ (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, 'UTC')), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen+ FROM error_tracking_fingerprint_issue_state+ WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)+ GROUP BY fp_hash+ HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS posthog__error_tracking_fingerprint_issue_state+ GROUP BY posthog__error_tracking_fingerprint_issue_state.issue_id+ HAVING ifNull(greaterOrEquals(min(posthog__error_tracking_fingerprint_issue_state.first_seen), parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0))))GROUP BY idORDER BY last_seen DESC,id DESCdiff --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 405d81f4ca2b..ee465fa54b9e 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@@ -1102,8 +1102,22 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIdeself.assertEqual([result["id"] for result in results], [self.issue_id_one])+ @parameterized.expand(+ [+ (+ "name",+ ErrorTrackingIssueFilter(key="name", value=["Recent unmapped issue"], operator=PropertyOperator.EXACT),+ ),+ (+ "first_seen",+ ErrorTrackingIssueFilter(+ key="first_seen", value="2022-01-10T00:00:00", operator=PropertyOperator.IS_DATE_AFTER+ ),+ ),+ ]+ )@time_machine.travel("2022-01-10T12:11:00", tick=False)- def test_recent_issue_state_keeps_legacy_events_without_fingerprint_state(self):+ def test_recent_issue_state_keeps_legacy_events_without_fingerprint_state(self, _name, issue_filter):issue_id = "01936e80-f594-7a2e-8545-7bcb491aa620"ErrorTrackingIssue.objects.create(id=issue_id,@@ -1130,11 +1144,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIdevalues=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_,- values=[- ErrorTrackingIssueFilter(- key="name", value=["Recent unmapped issue"], operator=PropertyOperator.EXACT- )- ],+ values=[issue_filter],)],)@@ -1228,42 +1238,42 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde"first_seen",PropertyOperator.GT,"2022-01-01",- "greater(e.issue_first_seen, toDateTime('2022-01-01'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING greater(min(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'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING greaterOrEquals(min(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'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING less(min(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'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING lessOrEquals(min(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'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING greater(min(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'))",+ "in(e.issue_id, (SELECT issue_id FROM posthog.error_tracking_fingerprint_issue_state GROUP BY issue_id HAVING less(min(first_seen), toDateTime('2022-01-01'))))",),("first_seen_exact_single",diff --git a/products/error_tracking/backend/presentation/views/query_serializers.py b/products/error_tracking/backend/presentation/views/query_serializers.pyindex c85d5e5aab35..97b2d5e3a9f7 100644--- a/products/error_tracking/backend/presentation/views/query_serializers.py+++ b/products/error_tracking/backend/presentation/views/query_serializers.py@@ -1,6 +1,8 @@from __future__ import annotations+import refrom typing import cast+from zoneinfo import ZoneInfofrom django.db import models@@ -9,6 +11,7 @@ from rest_framework import serializersfrom posthog.schema import ErrorTrackingOrderByfrom posthog.api.documentation import PropertyItemSerializer, extend_schema_field+from posthog.utils import relative_date_parsefrom products.error_tracking.backend.facade import contractsfrom products.error_tracking.backend.facade.query_utils import TREND_CHANGE_FRACTION@@ -75,10 +78,28 @@ class ErrorTrackingDateRangeSerializer(serializers.Serializer):)+# Only the units relative_date_parse resolves: lowercase m is months, uppercase M is minutes.+_SUPPORTED_RELATIVE_DATE = re.compile(r"-?\d+[hdwmqysM]")+_DATE_COMPARISON_OPERATORS = ("gt", "gte", "lt", "lte", "is_date_after", "is_date_before")++def validate_filter_group(value: list[dict[str, object]]) -> list[dict[str, object]]:for item in value:if item.get("type") == "hogql":raise serializers.ValidationError("HogQL property filters are not supported here.")+ if (+ item.get("type") == "error_tracking_issue"+ and item.get("key") == "first_seen"+ and item.get("operator") in _DATE_COMPARISON_OPERATORS+ and isinstance(date_value := item.get("value"), str)+ ):+ try:+ serializers.DateTimeField().run_validation(date_value)+ except serializers.ValidationError:+ raise serializers.ValidationError(+ "first_seen comparisons in filterGroup need an ISO timestamp. "+ "Use firstSeenAfter for relative dates such as -24h."+ )return value@@ -112,6 +133,10 @@ ErrorTrackingIssueOrderBy = models.TextChoices( # type: ignore[call-overload]class ErrorTrackingIssuesListQueryRequestSerializer(serializers.Serializer):+ firstSeenAfter = serializers.CharField(+ required=False,+ help_text="Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences.",+ )dateRange = ErrorTrackingDateRangeSerializer(required=False,help_text="Date range for issue aggregates. Defaults to the last 7 days.",@@ -181,6 +206,14 @@ class ErrorTrackingIssuesListQueryRequestSerializer(serializers.Serializer):required=False, max_length=1000, help_text="Search stack-frame source/file path text.")+ def validate_firstSeenAfter(self, value: str) -> str:+ if _SUPPORTED_RELATIVE_DATE.fullmatch(value):+ try:+ return relative_date_parse(value, ZoneInfo("UTC")).isoformat()+ except (ValueError, OverflowError):+ raise serializers.ValidationError("Expected an ISO timestamp or relative date such as -24h or -7d.")+ return serializers.DateTimeField().run_validation(value).isoformat()+def validate_filterGroup(self, value: list[dict[str, object]]) -> list[dict[str, object]]:return validate_filter_group(value)diff --git a/products/error_tracking/backend/tests/api/test_query_api.py b/products/error_tracking/backend/tests/api/test_query_api.pyindex 81046b54d62f..dd62bf4ca4b6 100644--- a/products/error_tracking/backend/tests/api/test_query_api.py+++ b/products/error_tracking/backend/tests/api/test_query_api.py@@ -391,6 +391,66 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):assert project_response.status_code == 200assert project_response.json()["results"] == []+ @parameterized.expand(+ [+ ("relative", {"firstSeenAfter": "-1d"}, {"new"}),+ ("relative_minutes", {"firstSeenAfter": "-180M"}, {"new"}),+ ("absolute", {"firstSeenAfter": "2026-04-23T12:00:00Z"}, {"new"}),+ ("milliseconds", {"firstSeenAfter": "2026-04-24T10:00:00.500Z"}, set()),+ ("before_both", {"firstSeenAfter": "-3d"}, {"new", "old"}),+ (+ "filter_group_before",+ {+ "filterGroup": [+ {+ "key": "first_seen",+ "type": "error_tracking_issue",+ "operator": "lt",+ "value": "2026-04-23T12:00:00Z",+ }+ ]+ },+ {"old"},+ ),+ ]+ )+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issues_list_filters_by_merged_issue_first_seen(+ self, _name: str, request_fields: dict[str, object], expected: set[str]+ ) -> None:+ old_issue_id = "01936e7f-d7ff-7314-b2d4-7627981e34f1"+ self.create_issue()+ self.create_issue(issue_id=old_issue_id, fingerprint="old-fingerprint")+ for issue_id, first_seen in [+ (self.issue_id, (now() - timedelta(hours=2)).replace(microsecond=200000)),+ (old_issue_id, now() - timedelta(days=2)),+ ]:+ ErrorTrackingIssueFingerprintV2.objects.filter(team=self.team, issue_id=issue_id).update(+ first_seen=first_seen+ )+ ErrorTrackingIssueFingerprintV2.objects.create(+ team=self.team, issue_id=old_issue_id, fingerprint="new-fingerprint-on-old-issue"+ )+ with time_machine.travel("2026-04-24T12:00:01Z", tick=False):+ sync_issues_to_clickhouse(issue_ids=[self.issue_id, old_issue_id], team_id=self.team.pk)+ self.create_exception_event()+ self.create_exception_event(issue_id=old_issue_id, fingerprint="new-fingerprint-on-old-issue")+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issues",+ data={+ "status": "all",+ "dateRange": {"date_from": "-1d", "date_to": "2026-04-25T00:00:00Z"},+ **request_fields,+ },+ format="json",+ )++ assert response.status_code == 200+ ids_by_name = {"new": self.issue_id, "old": old_issue_id}+ assert {row["id"] for row in response.json()["results"]} == {ids_by_name[name] for name in expected}+@time_machine.travel("2026-04-24T12:00:00Z", tick=False)def test_issue_queries_return_severity(self) -> None:self.create_issue(severity=ErrorTrackingIssue.Severity.HIGH)@@ -413,15 +473,42 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):assert detail_response.status_code == 200assert detail_response.json()["severity"] == "high"- def test_rejects_hogql_property_filters(self) -> None:+ @parameterized.expand(+ [+ ({"filterGroup": [{"key": "1 = 1", "type": "hogql", "value": "1"}]}, "HogQL property filters"),+ *(+ (+ {+ "filterGroup": [+ {"key": "first_seen", "type": "error_tracking_issue", "operator": op, "value": v}+ ]+ },+ "firstSeenAfter",+ )+ for op, v in [+ ("gt", "-24h"),+ ("gte", "-24h"),+ ("lt", "-24h"),+ ("lte", "-24h"),+ ("is_date_after", "-24h"),+ ("is_date_before", "-24h"),+ ("gt", "-24H"),+ ("gt", "yesterday"),+ ]+ ),+ ({"firstSeenAfter": "yesterday"}, "firstSeenAfter"),+ ({"firstSeenAfter": "-100000y"}, "firstSeenAfter"),+ ]+ )+ def test_rejects_unsupported_filters(self, request_fields: dict[str, object], message: str) -> None:response = self.client.post(f"/api/environments/{self.team.id}/error_tracking/query/issues",- data={"filterGroup": [{"key": "1 = 1", "type": "hogql", "value": "1"}]},+ data=request_fields,format="json",)assert response.status_code == 400- assert "HogQL property filters are not supported here" in str(response.json())+ assert message in str(response.json())def test_rejects_invalid_person_id(self) -> None:response = self.client.post(diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex cb69fd06b773..115d21589579 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -1736,6 +1736,8 @@ export const ErrorTrackingIssueOrderByEnumApi = {} as constexport interface ErrorTrackingIssuesListQueryRequestApi {+ /** Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences. */+ firstSeenAfter?: string/** Date range for issue aggregates. Defaults to the last 7 days. */dateRange?: ErrorTrackingDateRangeApi/** Filter by issue status. Defaults to active.diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex 44e04576624b..8c0942606d5f 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -828,6 +828,12 @@ export const errorTrackingQueryIssuesListCreateBodyUrlMax = 1000export const errorTrackingQueryIssuesListCreateBodyFilePathMax = 1000export const ErrorTrackingQueryIssuesListCreateBody = /* @__PURE__ */ zod.object({+ firstSeenAfter: zod+ .string()+ .optional()+ .describe(+ 'Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences.'+ ),dateRange: zod.object({date_from: zoddiff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.md b/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.mdindex 37c288525344..b0edfc6fa182 100644--- a/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.md+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issues-list.md@@ -13,6 +13,7 @@ Be minimalist. Only add filters needed to answer the user’s question. Do not a# Common filters- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.+- `firstSeenAfter`: only issues first seen after an ISO timestamp or relative date such as `-24h` or `-7d` (`m` is months, `M` is minutes). Use this for new issues since a deploy.- `searchQuery`: free-text search for exception names, values, stack frames, and email text.- `library`: exact `$lib` match, for example `posthog-js`.- `release`: exact release ID, release version, or git commit ID captured in `$exception_release`. This intentionally does not match project name, branch, or timestamp fragments.@@ -23,7 +24,7 @@ Be minimalist. Only add filters needed to answer the user’s question. Do not a- `filePath`: stack-frame file/source text search.- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit. For severity, use type `error_tracking_issue`, key `severity`, and `exact`, `is_set`, or `is_not_set`.-Use `dateRange` for time, not property filters. Omit `date_to` for now.+Use `dateRange` for occurrence times and `firstSeenAfter` for when an issue first appeared. Omit `date_to` for now. Relative dates on `first_seen` in `filterGroup` are rejected; use an ISO timestamp there.# Next stepsdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 803e0089324a..2b8ad685c128 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -11664,7 +11664,7 @@"system_prompt_hint": "Error event samples, stack traces, code variables, and session IDs (error-tracking category)"},"query-error-tracking-issues-list": {- "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, severity, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, 10 rows per page, and compact aggregate counts. Each row carries a short `description` preview. Use `query-error-tracking-issue` for the full description.\n\nKeep `limit` small. When `hasMore` is true and you need more rows, fetch the next page with `offset` set to `nextOffset`. Set `volumeResolution` only when the user asks for volume over time. It is an integer count of equal-width buckets across `dateRange`, from 0 to 200, not a unit such as `hour` or `day`. For daily volume over the default 7-day range, send `7`. For hourly volume over the last 24 hours, send `24` with `dateRange.date_from` set to `-24h`.\n\nFor all-time issue counts by status or severity, query `system.error_tracking_issues` with `posthog:execute-sql`. The table follows the connected user's Error tracking access and only returns issues from the current project. This list tool only includes issues observed during `dateRange`.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_release`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit. For severity, use type `error_tracking_issue`, key `severity`, and `exact`, `is_set`, or `is_not_set`.\n\nUse `dateRange` for time, not property filters. Omit `date_to` for now.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.",+ "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, severity, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, 10 rows per page, and compact aggregate counts. Each row carries a short `description` preview. Use `query-error-tracking-issue` for the full description.\n\nKeep `limit` small. When `hasMore` is true and you need more rows, fetch the next page with `offset` set to `nextOffset`. Set `volumeResolution` only when the user asks for volume over time. It is an integer count of equal-width buckets across `dateRange`, from 0 to 200, not a unit such as `hour` or `day`. For daily volume over the default 7-day range, send `7`. For hourly volume over the last 24 hours, send `24` with `dateRange.date_from` set to `-24h`.\n\nFor all-time issue counts by status or severity, query `system.error_tracking_issues` with `posthog:execute-sql`. The table follows the connected user's Error tracking access and only returns issues from the current project. This list tool only includes issues observed during `dateRange`.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `firstSeenAfter`: only issues first seen after an ISO timestamp or relative date such as `-24h` or `-7d` (`m` is months, `M` is minutes). Use this for new issues since a deploy.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_release`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit. For severity, use type `error_tracking_issue`, key `severity`, and `exact`, `is_set`, or `is_not_set`.\n\nUse `dateRange` for occurrence times and `firstSeenAfter` for when an issue first appeared. Omit `date_to` for now. Relative dates on `first_seen` in `filterGroup` are rejected; use an ISO timestamp there.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issues list",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 59e9bf5ab89d..11075a9d75b0 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -12321,7 +12321,7 @@"system_prompt_hint": "Error event samples, stack traces, code variables, and session IDs (error-tracking category)"},"query-error-tracking-issues-list": {- "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, severity, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, 10 rows per page, and compact aggregate counts. Each row carries a short `description` preview. Use `query-error-tracking-issue` for the full description.\n\nKeep `limit` small. When `hasMore` is true and you need more rows, fetch the next page with `offset` set to `nextOffset`. Set `volumeResolution` only when the user asks for volume over time. It is an integer count of equal-width buckets across `dateRange`, from 0 to 200, not a unit such as `hour` or `day`. For daily volume over the default 7-day range, send `7`. For hourly volume over the last 24 hours, send `24` with `dateRange.date_from` set to `-24h`.\n\nFor all-time issue counts by status or severity, query `system.error_tracking_issues` with `posthog:execute-sql`. The table follows the connected user's Error tracking access and only returns issues from the current project. This list tool only includes issues observed during `dateRange`.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_release`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit. For severity, use type `error_tracking_issue`, key `severity`, and `exact`, `is_set`, or `is_not_set`.\n\nUse `dateRange` for time, not property filters. Omit `date_to` for now.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.",+ "description": "List and filter Error tracking issues. Returns compact issue rows with aggregate impact counts (`occurrences`, `users`, `sessions`) and optional volume buckets.\n\nUse this first when the user asks which errors are happening, which errors are most common, or wants to narrow issues by status, severity, release, library, fingerprint, URL, user, person, or properties.\n\nDefaults are intentionally useful: active issues, last 7 days, sorted by occurrences, test accounts filtered out, 10 rows per page, and compact aggregate counts. Each row carries a short `description` preview. Use `query-error-tracking-issue` for the full description.\n\nKeep `limit` small. When `hasMore` is true and you need more rows, fetch the next page with `offset` set to `nextOffset`. Set `volumeResolution` only when the user asks for volume over time. It is an integer count of equal-width buckets across `dateRange`, from 0 to 200, not a unit such as `hour` or `day`. For daily volume over the default 7-day range, send `7`. For hourly volume over the last 24 hours, send `24` with `dateRange.date_from` set to `-24h`.\n\nFor all-time issue counts by status or severity, query `system.error_tracking_issues` with `posthog:execute-sql`. The table follows the connected user's Error tracking access and only returns issues from the current project. This list tool only includes issues observed during `dateRange`.\n\nBe minimalist. Only add filters needed to answer the user’s question. Do not add \"is set\" filters unless the user explicitly asks for them.\n\n# Common filters\n\n- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.\n- `firstSeenAfter`: only issues first seen after an ISO timestamp or relative date such as `-24h` or `-7d` (`m` is months, `M` is minutes). Use this for new issues since a deploy.\n- `searchQuery`: free-text search for exception names, values, stack frames, and email text.\n- `library`: exact `$lib` match, for example `posthog-js`.\n- `release`: exact release ID, release version, or git commit ID captured in `$exception_release`. This intentionally does not match project name, branch, or timestamp fragments.\n- `fingerprint`: exact `$exception_fingerprint` match.\n- `url`: substring match on `$current_url`.\n- `personId`: exact PostHog person UUID.\n- `user`: user/email text search.\n- `filePath`: stack-frame file/source text search.\n- `filterGroup`: advanced flat AND property filters. Prefer typed fields above when they fit. For severity, use type `error_tracking_issue`, key `severity`, and `exact`, `is_set`, or `is_not_set`.\n\nUse `dateRange` for occurrence times and `firstSeenAfter` for when an issue first appeared. Omit `date_to` for now. Relative dates on `first_seen` in `filterGroup` are rejected; use an ISO timestamp there.\n\n# Next steps\n\n- Use `query-error-tracking-issue` with `issueId` to inspect one issue.\n- Use `query-error-tracking-issue-events` with `issueId` to fetch sampled exception events, stack traces, URLs, and `$session_id` values.\n- If the user asks what people were doing before the error, use `$session_id` values from issue events with `query-session-recordings-list` and its `session_ids` parameter.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issues list",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b6a0b8033b60..fbac4483ea12 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -43806,6 +43806,8 @@ export namespace Schemas {}export interface ErrorTrackingIssuesListQueryRequest {+ /** Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences. */+ firstSeenAfter?: string;/** Date range for issue aggregates. Defaults to the last 7 days. */dateRange?: ErrorTrackingDateRange;/** Filter by issue status. Defaults to active.diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex f094d11028d2..e83fcb04043a 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -8550,6 +8550,12 @@ export const errorTrackingQueryIssuesListCreateBodyUrlMax = 1000export const errorTrackingQueryIssuesListCreateBodyFilePathMax = 1000export const ErrorTrackingQueryIssuesListCreateBody = () => zod.object({+ firstSeenAfter: zod+ .string()+ .optional()+ .describe(+ 'Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences.'+ ),dateRange: zod.object({date_from: zoddiff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.tsindex b268e2a565a1..7bc352b7c4a4 100644--- a/services/mcp/src/tools/generated/error_tracking.ts+++ b/services/mcp/src/tools/generated/error_tracking.ts@@ -855,6 +855,9 @@ const queryErrorTrackingIssuesList = (): ToolBase<handler: async (context: Context, params: z.infer<ReturnType<typeof QueryErrorTrackingIssuesListSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}+ if (params.firstSeenAfter !== undefined) {+ body['firstSeenAfter'] = params.firstSeenAfter+ }if (params.dateRange !== undefined) {body['dateRange'] = params.dateRange}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issues-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issues-list.jsonindex d05c45430a70..91854abe2435 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issues-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-error-tracking-issues-list.json@@ -202,6 +202,10 @@],"description": "Filter by exact exception fingerprint hash, not fuzzy search."},+ "firstSeenAfter": {+ "description": "Only include issues first seen strictly after this ISO timestamp or relative date, such as -24h or -7d. Independent of dateRange, which filters occurrences.",+ "type": "string"+ },"library": {"anyOf": [{