: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): return first release and trend from issue detail (#120320)
James Gill8f78ecad8b39
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex d3d04e3b465b..05c6aa6c9446 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -190,6 +190,7 @@ def get_issue_basics(team_id: int, issue_id: UUID | str) -> contracts.ErrorTrackdescription=issue.description,status=issue.status,severity=issue.severity,+ first_seen=getattr(issue, "first_seen", None),)diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.pyindex b194fa09816e..276e89028a12 100644--- a/products/error_tracking/backend/facade/contracts.py+++ b/products/error_tracking/backend/facade/contracts.py@@ -16,8 +16,18 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+from posthog.enums import LabeledStrEnum+ERROR_TRACKING_ISSUE_SEVERITIES = ("low", "medium", "high", "critical")++class IssueTrendDirection(LabeledStrEnum):+ NEW = "new"+ INCREASING = "increasing"+ DECREASING = "decreasing"+ STABLE = "stable"++# Keep in sync with products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsFixWizardLogic.ts.SOURCE_MAPS_DOCS_URL = "https://posthog.com/docs/error-tracking/upload-source-maps"@@ -302,6 +312,8 @@ class ErrorTrackingIssueBasics:description: str | Nonestatus: strseverity: str | None+ # Earliest across all fingerprints, merged ones included.+ first_seen: datetime | None@dataclass(frozen=True)diff --git a/products/error_tracking/backend/facade/query_utils.py b/products/error_tracking/backend/facade/query_utils.pyindex 87254c67f379..7dda41bd47e1 100644--- a/products/error_tracking/backend/facade/query_utils.py+++ b/products/error_tracking/backend/facade/query_utils.py@@ -10,6 +10,8 @@ from posthog.hogql.escape_sql import escape_hogql_stringfrom posthog.dataclasses import frozenfrom posthog.utils import relative_date_parse+from products.error_tracking.backend.facade.contracts import IssueTrendDirection+MAX_NORMALIZED_TEXT_CHARS = 1000MAX_STACK_FRAMES = 50# The issue detail tool returns the full description, so list rows keep only a preview.@@ -51,7 +53,8 @@ def normalize_volume_resolution(volume_resolution: int) -> int:return max(volume_resolution, 1)-CONTEXT_EVENT_SELECTS = ["properties.$exception_list", "properties.$exception_releases"]+CONTEXT_EVENT_SELECTS = ["properties.$exception_list", "properties.$exception_release"]+RELEASE_EVENT_SELECTS = ["properties.$exception_release"]DEFAULT_EVENT_CONTEXT_INCLUDES = ["exception", "environment", "navigation", "correlation"]EVENT_CONTEXT_PROPERTY_SELECTS = {"exception": [@@ -75,7 +78,7 @@ EVENT_CONTEXT_PROPERTY_SELECTS = {"properties.$app_version","properties.$device_type",],- "release": ["properties.$exception_releases"],+ "release": ["properties.$exception_release"],"navigation": ["properties.$current_url", "properties.$screen_name", "properties.$referrer"],"correlation": ["properties.$session_id",@@ -157,21 +160,19 @@ def add_event_filter(filters: list[dict[str, object]], key: str, operator: str,def add_release_filter(filters: list[dict[str, object]], release: str) -> None:escaped_release = escape_hogql_string(release)- releases_json = "ifNull(nullIf(JSONExtractRaw(properties, '$exception_releases'), ''), '{}')"filters.append({"type": "hogql",- "key": f"position(toString(properties.$exception_releases), {escaped_release}) > 0",+ "key": f"position(toString(properties.$exception_release), {escaped_release}) > 0",})filters.append({"type": "hogql","key": (- f"arrayExists(r -> (r.1 = {escaped_release} "- f"OR JSONExtractString(r.2, 'version') = {escaped_release} "- f"OR JSONExtractString(JSONExtractRaw(r.2, 'metadata'), 'git', 'commit_id') = {escaped_release}), "- f"JSONExtractKeysAndValuesRaw({releases_json}))"+ f"{escaped_release} IN (toString(properties.$exception_release.id), "+ "toString(properties.$exception_release.version), "+ "toString(properties.$exception_release.metadata.git.commit_id))"),})@@ -368,7 +369,7 @@ def normalize_error_property() -> object:if name == "$exception_list":return normalize_exception_list(value, include_stacktrace, only_app_frames, include_code_variables)- if name in {"$exception_releases", "$cymbal_errors"}:+ if name in {"$exception_release", "$cymbal_errors"}:return parse_jsonish(value)if name == "$exception_handled" and isinstance(value, str) and value.lower() in {"true", "false"}:return value.lower() == "true"@@ -502,14 +503,8 @@ def build_top_in_app_frame(issue: dict[str, object], event_properties: dict[str,)-def extract_latest_release(event_properties: dict[str, object]) -> dict[str, object]:- releases = event_properties.get("$exception_releases")- release_values = (- releases if isinstance(releases, list) else list(releases.values()) if isinstance(releases, dict) else []- )- records = [record for value in release_values if (record := as_record(value)) is not None]- records.sort(key=lambda record: str(record.get("timestamp") or record.get("created_at") or ""), reverse=True)- release = records[0] if records else None+def extract_release(event_properties: dict[str, object]) -> dict[str, object]:+ release = as_record(event_properties.get("$exception_release"))if release is None:return {}metadata = as_record(release.get("metadata"))@@ -518,7 +513,7 @@ def extract_latest_release(event_properties: dict[str, object]) -> dict[str, obj{"version": release.get("version"),"project": release.get("project"),- "timestamp": release.get("timestamp") or release.get("created_at"),+ "timestamp": release.get("timestamp"),"commit_id": git.get("commit_id") if git else None,"branch": git.get("branch") if git else None,"repo_name": git.get("repo_name") if git else None,@@ -526,6 +521,36 @@ def extract_latest_release(event_properties: dict[str, object]) -> dict[str, obj)+# A late event can carry a timestamp before first_seen, but no first event is after it.+FIRST_EVENT_LOOKBACK = timedelta(days=1)+# EventsQuery bounds are exclusive, so the window ends just after first_seen.+FIRST_EVENT_LOOKAHEAD = timedelta(seconds=1)+++def parse_timestamp(value: object) -> datetime | None:+ if not isinstance(value, str):+ return None+ try:+ return datetime.fromisoformat(value)+ except ValueError:+ return None+++@frozen+class EventWindow:+ after: str+ before: str+++def first_event_window(first_seen: datetime | None) -> EventWindow | None:+ if first_seen is None:+ return None+ return EventWindow(+ after=(first_seen - FIRST_EVENT_LOOKBACK).isoformat(),+ before=(first_seen + FIRST_EVENT_LOOKAHEAD).isoformat(),+ )++@frozenclass BreakdownRange:date_from: datetime@@ -624,29 +649,77 @@ def build_impact(issue: dict[str, object]) -> dict[str, object]:)-def build_sparkline(issue: dict[str, object]) -> list[float] | None:+def volume_bucket_records(issue: dict[str, object]) -> list[dict[str, object]]:+ aggregations = as_record(issue.get("aggregations")) or {}+ volume_buckets = aggregations.get("volume_buckets")+ if not isinstance(volume_buckets, list):+ return []+ return [record for bucket in volume_buckets if (record := as_record(bucket)) is not None]+++def build_sparkline(issue: dict[str, object], volume_resolution: int) -> list[float] | None:aggregations = as_record(issue.get("aggregations")) or {}volume_range = aggregations.get("volumeRange")+ values: list[float] = []if isinstance(volume_range, list):- numeric_values: list[float] = []for value in volume_range:numeric_value = to_number(value)if numeric_value is None:return None- numeric_values.append(numeric_value)- return numeric_values- volume_buckets = aggregations.get("volume_buckets")- if isinstance(volume_buckets, list):- numeric_values = []- for bucket in volume_buckets:- record = as_record(bucket)- if record is None:- continue- value = to_number(record.get("value"))- if value is not None:- numeric_values.append(value)- return numeric_values or None- return None+ values.append(numeric_value)+ else:+ values = [+ value for record in volume_bucket_records(issue) if (value := to_number(record.get("value"))) is not None+ ]+ if len(values) == volume_resolution * 2:+ # trend_volume_resolution doubled the count, so add each pair of buckets back together.+ values = [first + second for first, second in zip(values[::2], values[1::2])]+ return values or None+++# The fewest volume buckets that split the date range into two halves.+TREND_VOLUME_RESOLUTION = 2+TREND_CHANGE_FRACTION = 0.25+++def trend_volume_resolution(volume_resolution: int) -> int:+ # An odd count has no bucket edge at the midpoint of the date range.+ return volume_resolution * 2 if volume_resolution % 2 else volume_resolution+++def trend_direction(+ previous: int, current: int, first_seen: datetime | None, current_from: object+) -> IssueTrendDirection:+ current_from_at = parse_timestamp(current_from)+ if previous == 0 and current > 0 and first_seen and current_from_at and first_seen >= current_from_at:+ return IssueTrendDirection.NEW+ change = current - previous+ if change and abs(change) >= previous * TREND_CHANGE_FRACTION:+ return IssueTrendDirection.INCREASING if change > 0 else IssueTrendDirection.DECREASING+ return IssueTrendDirection.STABLE+++def build_trend(issue: dict[str, object], first_seen: datetime | None) -> dict[str, object] | None:+ buckets = volume_bucket_records(issue)+ half = len(buckets) // 2+ if half == 0:+ return None+ # With an odd bucket count the middle bucket is left out, so both halves cover the same time.+ previous_buckets, current_buckets = buckets[:half], buckets[-half:]+ previous = int(sum(to_number(bucket.get("value")) or 0 for bucket in previous_buckets))+ current = int(sum(to_number(bucket.get("value")) or 0 for bucket in current_buckets))+ current_from = current_buckets[0].get("label")+ return compact_dict(+ {+ "direction": trend_direction(previous, current, first_seen, current_from).value,+ "current_occurrences": current,+ "previous_occurrences": previous,+ "change_percent": round((current - previous) / previous * 100) if previous else None,+ "previous_from": previous_buckets[0].get("label"),+ "previous_to": buckets[half].get("label"),+ "current_from": current_from,+ }+ )def build_issue_where(issue_id: str) -> list[str]:diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.pyindex c4a2a58aaf8e..76cb524b08da 100644--- a/products/error_tracking/backend/logic/__init__.py+++ b/products/error_tracking/backend/logic/__init__.py@@ -95,7 +95,8 @@ def issue_exists_by_id(team_id: int, issue_id: UUID | str) -> bool:def get_issue_basics(team_id: int, issue_id: UUID | str) -> ErrorTrackingIssue | None:return (- ErrorTrackingIssue.objects.filter(team_id=team_id, id=issue_id)+ ErrorTrackingIssue.objects.with_first_seen()+ .filter(team_id=team_id, id=issue_id).only("id", "name", "description", "status").first())diff --git a/products/error_tracking/backend/presentation/views/query.py b/products/error_tracking/backend/presentation/views/query.pyindex 5afecacd7b0f..2b24049ed356 100644--- a/products/error_tracking/backend/presentation/views/query.py+++ b/products/error_tracking/backend/presentation/views/query.py@@ -40,6 +40,8 @@ from products.error_tracking.backend.facade.query_utils import (ISSUE_BREAKDOWN_PROPERTIES,ISSUE_BREAKDOWN_QUERY_VALUES,ISSUE_FIELDS,+ RELEASE_EVENT_SELECTS,+ TREND_VOLUME_RESOLUTION,breakdown_query_date_range,build_date_range,build_event_selects,@@ -52,15 +54,18 @@ from products.error_tracking.backend.facade.query_utils import (build_search_query,build_sparkline,build_top_in_app_frame,+ build_trend,compact_dict,dedupe_repeated_stacktraces,- extract_latest_release,+ extract_release,+ first_event_window,get_page_info,map_context_event_properties,map_event_row,map_issue_breakdown,normalize_volume_resolution,pick_fields,+ trend_volume_resolution,)from products.error_tracking.backend.presentation.views.query_serializers import (ErrorTrackingIssueBreakdownSerializer,@@ -150,8 +155,8 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):operation_id="error_tracking_query_issue_create",summary="Get compact error tracking issue details",description=(- "Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional "- "sparkline and event breakdown."+ "Fetch one error tracking issue with impact counts, trend, top in_app frame, first and latest release, and "+ "optional sparkline and event breakdown."),)@action(methods=["POST"], detail=False, url_path="issue", required_scopes=["error_tracking:read"])@@ -163,8 +168,9 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):include_breakdown = cast(bool, params.get("includeBreakdown", False))filter_test_accounts = cast(bool, params.get("filterTestAccounts", True))volume_resolution = cast(int, params.get("volumeResolution", 0))- if include_sparkline and volume_resolution <= 0:- volume_resolution = 12+ if volume_resolution <= 0:+ volume_resolution = 12 if include_sparkline else TREND_VOLUME_RESOLUTION+ volume_resolution = normalize_volume_resolution(volume_resolution)issue_basics = facade_api.get_issue_basics(self.team.id, issue_id)if issue_basics is None:return Response(status=status.HTTP_404_NOT_FOUND)@@ -173,7 +179,7 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):issueId=issue_id,dateRange=DateRange(**date_range),filterTestAccounts=filter_test_accounts,- volumeResolution=normalize_volume_resolution(volume_resolution),+ volumeResolution=trend_volume_resolution(volume_resolution),limit=1,orderBy="last_seen",orderDirection="DESC",@@ -203,17 +209,66 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)return Response(payload)issue = cast(dict[str, object], raw_results[0])- event_properties: dict[str, object] = {}+ event_properties = self._issue_event_properties(+ request,+ issue_id,+ after=date_range.get("date_from"),+ before=date_range.get("date_to"),+ order="DESC",+ filter_test_accounts=filter_test_accounts,+ select=CONTEXT_EVENT_SELECTS,+ )+ first_event_properties: dict[str, object] = {}+ if (window := first_event_window(issue_basics.first_seen)) is not None:+ # Test accounts stay in, because first_seen counts their events too.+ first_event_properties = self._issue_event_properties(+ request,+ issue_id,+ after=window.after,+ before=window.before,+ order="ASC",+ filter_test_accounts=False,+ select=RELEASE_EVENT_SELECTS,+ )+ payload = compact_dict(+ {+ **pick_fields(issue, ISSUE_FIELDS),+ "top_in_app_frame": build_top_in_app_frame(issue, event_properties),+ "latest_release": extract_release(event_properties),+ "first_release": extract_release(first_event_properties),+ "impact": build_impact(issue),+ "trend": build_trend(issue, issue_basics.first_seen),+ "sparkline": build_sparkline(issue, volume_resolution) if include_sparkline else None,+ }+ )+ if include_breakdown:+ payload["breakdown"] = self._issue_breakdown(request, issue_id, date_range, filter_test_accounts)+ self._report_issue_read(+ request, issue_id, "issue", include_breakdown=include_breakdown, include_sparkline=include_sparkline+ )+ return Response(payload)++ def _issue_event_properties(+ self,+ request: ValidatedRequest,+ issue_id: str,+ *,+ after: object,+ before: object,+ order: Literal["ASC", "DESC"],+ filter_test_accounts: bool,+ select: list[str],+ ) -> dict[str, object]:try:context_event_query = EventsQuery(kind="EventsQuery",event="$exception",- select=CONTEXT_EVENT_SELECTS,+ select=select,where=build_issue_where(issue_id),filterTestAccounts=filter_test_accounts,- after=date_range.get("date_from"),- before=date_range.get("date_to"),- orderBy=["timestamp DESC"],+ after=after,+ before=before,+ orderBy=[f"timestamp {order}"],limit=1,tags={"productKey": "error_tracking"},)@@ -233,8 +288,8 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):team_id=self.team.pk,error=event_data.get("error"),)- else:- event_properties = map_context_event_properties(event_data)+ return {}+ return map_context_event_properties(event_data)except Exception:logger.warning("error_tracking_issue_context_query_failed",@@ -242,21 +297,7 @@ class ErrorTrackingQueryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):team_id=self.team.pk,exc_info=True,)- payload = compact_dict(- {- **pick_fields(issue, ISSUE_FIELDS),- "top_in_app_frame": build_top_in_app_frame(issue, event_properties),- "latest_release": extract_latest_release(event_properties),- "impact": build_impact(issue),- "sparkline": build_sparkline(issue) if include_sparkline else None,- }- )- if include_breakdown:- payload["breakdown"] = self._issue_breakdown(request, issue_id, date_range, filter_test_accounts)- self._report_issue_read(- request, issue_id, "issue", include_breakdown=include_breakdown, include_sparkline=include_sparkline- )- return Response(payload)+ return {}def _issue_breakdown(self, request: ValidatedRequest, issue_id: str, date_range: dict[str, object], filter_test_accounts: booldiff --git a/products/error_tracking/backend/presentation/views/query_serializers.py b/products/error_tracking/backend/presentation/views/query_serializers.pyindex 3d7dce0bcade..ae2ceca47304 100644--- a/products/error_tracking/backend/presentation/views/query_serializers.py+++ b/products/error_tracking/backend/presentation/views/query_serializers.py@@ -11,6 +11,7 @@ from posthog.schema import ErrorTrackingOrderByfrom posthog.api.documentation import PropertyItemSerializer, extend_schema_fieldfrom products.error_tracking.backend.facade import contracts+from products.error_tracking.backend.facade.query_utils import TREND_CHANGE_FRACTIONfrom products.error_tracking.backend.presentation.views.issues import AssigneeType, ErrorTrackingIssueSeverityFieldSTRING_OR_STRING_LIST_SCHEMA = {@@ -168,7 +169,7 @@ class ErrorTrackingIssuesListQueryRequestSerializer(serializers.Serializer):release = serializers.CharField(required=False,max_length=500,- help_text="Filter by exact release ID, version, or git commit ID captured in $exception_releases.",+ help_text="Filter by exact release ID, version, or git commit ID captured in $exception_release.",)fingerprint = StringOrStringListField(required=False, help_text="Filter by exact exception fingerprint hash, not fuzzy search."@@ -349,6 +350,29 @@ class ErrorTrackingLatestReleaseSerializer(serializers.Serializer):repo_name = serializers.CharField(required=False, help_text="Git repository name.")+class ErrorTrackingIssueTrendSerializer(serializers.Serializer):+ direction = serializers.ChoiceField(+ choices=contracts.IssueTrendDirection.choices,+ help_text=(+ "Occurrences in the second half of dateRange against the first half. 'increasing' or 'decreasing' means "+ f"a change of at least {TREND_CHANGE_FRACTION:.0%}. 'new' means the issue first occurred in the second half, "+ "counting merged fingerprints. "+ "'stable' means a smaller change."+ ),+ )+ current_occurrences = serializers.IntegerField(help_text="Occurrences in the second half of dateRange.")+ previous_occurrences = serializers.IntegerField(help_text="Occurrences in the first half of dateRange.")+ change_percent = serializers.IntegerField(+ required=False,+ help_text="Percent change from the first half to the second half. Absent when the first half has no occurrences.",+ )+ previous_from = serializers.CharField(help_text="Start of the first half.")+ previous_to = serializers.CharField(help_text="End of the first half.")+ current_from = serializers.CharField(+ help_text="Start of the second half. The second half ends at the end of dateRange."+ )++class ErrorTrackingBreakdownValueSerializer(serializers.Serializer):value = serializers.CharField(help_text="Property value.")count = serializers.IntegerField(help_text="Number of matching events with this value.")@@ -394,7 +418,22 @@ class ErrorTrackingIssueDetailSerializer(ErrorTrackingIssueListItemSerializer):)top_in_app_frame = ErrorTrackingTopFrameSerializer(required=False, help_text="Top in_app application frame.")latest_release = ErrorTrackingLatestReleaseSerializer(required=False, help_text="Latest release metadata.")+ first_release = ErrorTrackingLatestReleaseSerializer(+ required=False,+ help_text=(+ "Release metadata from the issue's first event, found near first_seen and not limited by dateRange. "+ "Compare it with latest_release to see which release introduced the issue. Absent when the first event "+ "has no release metadata."+ ),+ )impact = ErrorTrackingImpactSerializer(required=False, help_text="Compact impact counts.")+ trend = ErrorTrackingIssueTrendSerializer(+ required=False,+ help_text=(+ "Whether the issue is getting worse or better: occurrences in the second half of dateRange against the "+ "first half. Absent when the issue has no occurrences in dateRange."+ ),+ )sparkline = serializers.ListField(child=serializers.FloatField(), required=False, help_text="Optional compact occurrence sparkline.")diff --git a/products/error_tracking/backend/tests/api/test_query_api.py b/products/error_tracking/backend/tests/api/test_query_api.pyindex 138ece1c0125..f32820c06f96 100644--- a/products/error_tracking/backend/tests/api/test_query_api.py+++ b/products/error_tracking/backend/tests/api/test_query_api.py@@ -31,6 +31,7 @@ from products.error_tracking.backend.facade.query_utils import (build_issue_filters,build_search_query,build_sparkline,+ build_trend,dedupe_repeated_stacktraces,map_issue_breakdown,normalize_stacktrace,@@ -73,13 +74,54 @@ def test_release_filter_adds_substring_prefilter() -> None:assert filters[0] == {"type": "hogql",- "key": "position(toString(properties.$exception_releases), '2026.04.24') > 0",+ "key": "position(toString(properties.$exception_release), '2026.04.24') > 0",}- assert "JSONExtractKeysAndValuesRaw" in str(filters[1]["key"])+ assert "properties.$exception_release.version" in str(filters[1]["key"])-def test_build_sparkline_accepts_float_values() -> None:- assert build_sparkline({"aggregations": {"volumeRange": [1.0, 2.5]}}) == [1.0, 2.5]+ [+ ("float values", [1.0, 2.5], 2, [1.0, 2.5]),+ ("doubled odd resolution adds pairs back together", [1, 0, 2, 3, 0, 1], 3, [1, 5, 1]),+ ]+)+def test_build_sparkline(_name: str, volume_range: list[float], volume_resolution: int, expected: list[float]) -> None:+ assert build_sparkline({"aggregations": {"volumeRange": volume_range}}, volume_resolution) == expected+++OLD_FIRST_SEEN = datetime(2026, 4, 1, tzinfo=UTC)+++ [+ ("increasing", [2, 2, 5, 5], OLD_FIRST_SEEN, {"direction": "increasing", "change_percent": 150}),+ ("decreasing", [5, 5, 2, 2], OLD_FIRST_SEEN, {"direction": "decreasing", "change_percent": -60}),+ ("small change is stable", [4, 4, 5, 4], OLD_FIRST_SEEN, {"direction": "stable"}),+ (+ "20% drop is stable",+ [3, 2, 2, 2],+ OLD_FIRST_SEEN,+ {"direction": "stable", "change_percent": -20},+ ),+ (+ "25% drop is decreasing",+ [2, 2, 1, 2],+ OLD_FIRST_SEEN,+ {"direction": "decreasing", "change_percent": -25},+ ),+ ("first seen in the current half", [0, 0, 1, 3], datetime(2026, 4, 23, 6, tzinfo=UTC), {"direction": "new"}),+ ("quiet before the current half", [0, 0, 1, 3], OLD_FIRST_SEEN, {"direction": "increasing"}),+ ("odd bucket count leaves the middle out", [1, 9, 1], OLD_FIRST_SEEN, {"direction": "stable"}),+ ]+)+def test_build_trend(_name: str, values: list[int], first_seen: datetime, expected: dict[str, object]) -> None:+ start = datetime(2026, 4, 21, tzinfo=UTC)+ buckets = [+ {"label": (start + timedelta(days=index)).isoformat(), "value": value} for index, value in enumerate(values)+ ]+ trend = build_trend({"aggregations": {"volume_buckets": buckets}}, first_seen)+ assert trend is not None+ assert {key: trend.get(key) for key in expected} == expecteddef test_normalize_stacktrace_keeps_the_frames_closest_to_the_error() -> None:@@ -252,6 +294,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):fingerprint: str | None = None,include_issue_id: bool = True,properties: dict[str, object] | None = None,+ timestamp: datetime | None = None,) -> None:resolved_issue_id = issue_id or self.issue_idresolved_fingerprint = fingerprint or self.fingerprint@@ -268,7 +311,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):event="$exception",team=self.team,properties=event_properties,- timestamp=now() - relativedelta(hours=1),+ timestamp=timestamp or now() - relativedelta(hours=1),)@time_machine.travel("2026-04-24T12:00:00Z", tick=False)@@ -279,13 +322,12 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):"$lib": "posthog-js","$browser": "Chrome","$current_url": "https://example.test/checkout",- "$exception_releases": {- "release-id-1": {- "version": "2026.04.24",- "project": "posthog-js",- "timestamp": "2026-04-24T10:00:00Z",- "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},- }+ "$exception_release": {+ "id": "release-id-1",+ "version": "2026.04.24",+ "project": "posthog-js",+ "timestamp": "2026-04-24T10:00:00Z",+ "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},},})@@ -500,7 +542,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):)assert response.status_code == 200- assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY), (Product.ERROR_TRACKING, Feature.QUERY)]+ assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY)] * 3def test_issue_detail_does_not_expand_fingerprints(self) -> None:self.create_issue()@@ -539,7 +581,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):)assert response.status_code == 200- assert observed_volume_resolutions == [1]+ assert observed_volume_resolutions == [2]assert observed_filter_groups == [None]def test_issue_detail_without_fingerprints_has_no_filter_group(self) -> None:@@ -580,8 +622,44 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):assert observed_filter_groups == [None]@time_machine.travel("2026-04-24T12:00:00Z", tick=False)- def test_issue_detail_returns_impact_top_frame_and_latest_release(self) -> None:- self.create_issue()+ def test_issue_detail_returns_impact_top_frame_and_releases(self) -> None:+ # In the current trend half, so only the merged fingerprint keeps trend from reading new.+ first_seen = datetime(2026, 4, 24, 6, tzinfo=UTC)+ merged_first_seen = datetime(2026, 4, 1, 8, tzinfo=UTC)+ issue = ErrorTrackingIssue.objects.create(id=self.issue_id, team=self.team, name="TypeError")+ for fingerprint, fingerprint_first_seen in [+ (self.fingerprint, first_seen),+ ("merged-fingerprint", merged_first_seen),+ ]:+ created = ErrorTrackingIssueFingerprintV2.objects.create(+ team=self.team, issue=issue, fingerprint=fingerprint+ )+ # The model sets first_seen on create, so overwrite it the way cymbal writes it: the first event's timestamp.+ ErrorTrackingIssueFingerprintV2.objects.filter(id=created.id).update(first_seen=fingerprint_first_seen)+ # Sync once: under the frozen clock a second sync gets the same ReplacingMergeTree version.+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=self.team.pk)+ # A fingerprint merged in from an older issue, with no events in the date range.+ source_issue_id = "01936e7f-d7ff-7314-b2d4-7627981e34f1"+ self.create_exception_event(+ issue_id=source_issue_id,+ fingerprint="merged-fingerprint",+ timestamp=merged_first_seen,+ properties={"$exception_release": {"id": "release-id-1", "version": "2026.04.01"}},+ )+ # Arrived after the fingerprint was created, but happened first.+ self.create_exception_event(+ issue_id=source_issue_id,+ fingerprint="merged-fingerprint",+ timestamp=merged_first_seen - timedelta(hours=2),+ properties={+ "$exception_release": {+ "id": "release-id-0",+ "version": "2026.03.31",+ "project": "posthog-js",+ "timestamp": "2026-03-31T09:00:00Z",+ }+ },+ )self.create_exception_event(properties={"$exception_list": [@@ -608,13 +686,12 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):},}],- "$exception_releases": {- "release-id-1": {- "version": "2026.04.24",- "project": "posthog-js",- "timestamp": "2026-04-24T10:00:00Z",- "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},- }+ "$exception_release": {+ "id": "release-id-1",+ "version": "2026.04.24",+ "project": "posthog-js",+ "timestamp": "2026-04-24T10:00:00Z",+ "metadata": {"git": {"commit_id": "commit-123", "branch": "main"}},},})@@ -639,6 +716,50 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):}assert data["latest_release"]["version"] == "2026.04.24"assert data["latest_release"]["commit_id"] == "commit-123"+ assert data["first_seen"] == "2026-04-24T06:00:00Z"+ assert data["trend"] == {+ "direction": "increasing",+ "current_occurrences": 1,+ "previous_occurrences": 0,+ "previous_from": "2026-04-23T00:00:00+00:00",+ "previous_to": "2026-04-24T00:00:00+00:00",+ "current_from": "2026-04-24T00:00:00+00:00",+ }+ assert data["first_release"] == {+ "version": "2026.03.31",+ "project": "posthog-js",+ "timestamp": "2026-03-31T09:00:00Z",+ }++ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)+ def test_issue_detail_trend_splits_an_odd_volume_resolution_at_the_midpoint(self) -> None:+ self.create_issue()+ for timestamp in [+ "2026-04-21T12:00:00Z",+ "2026-04-22T06:00:00Z",+ "2026-04-22T18:00:00Z",+ "2026-04-23T12:00:00Z",+ ]:+ self.create_exception_event(timestamp=datetime.fromisoformat(timestamp))+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/query/issue",+ data={+ "issueId": self.issue_id,+ "dateRange": {"date_from": "2026-04-21T00:00:00Z", "date_to": "2026-04-24T00:00:00Z"},+ "includeSparkline": True,+ "volumeResolution": 3,+ },+ format="json",+ )++ assert response.status_code == 200+ data = response.json()+ assert data["sparkline"] == [1, 2, 1]+ assert data["trend"]["previous_occurrences"] == 2+ assert data["trend"]["current_occurrences"] == 2+ assert data["trend"]["current_from"] == "2026-04-22T12:00:00+00:00"@time_machine.travel("2026-04-24T12:00:00Z", tick=False)def test_issue_detail_returns_without_context_when_context_query_fails(self) -> None:@@ -1037,7 +1158,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):"$current_url": "https://example.test/checkout","$exception_level": "error","$exception_handled": False,- "$exception_releases": {"release-id": {"version": "2026.04.24"}},+ "$exception_release": {"id": "release-id", "version": "2026.04.24"},"$cymbal_errors": ["source map unavailable"],"$trace_id": "00000000000000000000000000000123","$span_id": "0000000000000456",@@ -1099,7 +1220,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):assert variables_frame["code_variables"] == expected_variablesassert variables_properties["$exception_level"] == "error"assert variables_properties["$exception_handled"] is False- assert variables_properties["$exception_releases"] == {"release-id": {"version": "2026.04.24"}}+ assert variables_properties["$exception_release"] == {"id": "release-id", "version": "2026.04.24"}assert variables_properties["$cymbal_errors"] == ["source map unavailable"]assert variables_properties["$trace_id"] == "00000000000000000000000000000123"assert variables_properties["$span_id"] == "0000000000000456"diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex e8693f7808f3..faf793740105 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -1211,6 +1211,43 @@ export interface ErrorTrackingImpactApi {sessions?: number}+/**+ * * `new` - New+ * * `increasing` - Increasing+ * * `decreasing` - Decreasing+ * * `stable` - Stable+ */+export type IssueTrendDirectionEnumApi = (typeof IssueTrendDirectionEnumApi)[keyof typeof IssueTrendDirectionEnumApi]++export const IssueTrendDirectionEnumApi = {+ New: 'new',+ Increasing: 'increasing',+ Decreasing: 'decreasing',+ Stable: 'stable',+} as const++export interface ErrorTrackingIssueTrendApi {+ /** Occurrences in the second half of dateRange against the first half. 'increasing' or 'decreasing' means a change of at least 25%. 'new' means the issue first occurred in the second half, counting merged fingerprints. 'stable' means a smaller change.+ *+ * * `new` - New+ * * `increasing` - Increasing+ * * `decreasing` - Decreasing+ * * `stable` - Stable */+ direction: IssueTrendDirectionEnumApi+ /** Occurrences in the second half of dateRange. */+ current_occurrences: number+ /** Occurrences in the first half of dateRange. */+ previous_occurrences: number+ /** Percent change from the first half to the second half. Absent when the first half has no occurrences. */+ change_percent?: number+ /** Start of the first half. */+ previous_from: string+ /** End of the first half. */+ previous_to: string+ /** Start of the second half. The second half ends at the end of dateRange. */+ current_from: string+}+export interface ErrorTrackingBreakdownValueApi {/** Property value. */value: string@@ -1302,8 +1339,12 @@ export interface ErrorTrackingIssueDetailApi {top_in_app_frame?: ErrorTrackingTopFrameApi/** Latest release metadata. */latest_release?: ErrorTrackingLatestReleaseApi+ /** Release metadata from the issue's first event, found near first_seen and not limited by dateRange. Compare it with latest_release to see which release introduced the issue. Absent when the first event has no release metadata. */+ first_release?: ErrorTrackingLatestReleaseApi/** Compact impact counts. */impact?: ErrorTrackingImpactApi+ /** Whether the issue is getting worse or better: occurrences in the second half of dateRange against the first half. Absent when the issue has no occurrences in dateRange. */+ trend?: ErrorTrackingIssueTrendApi/** Optional compact occurrence sparkline. */sparkline?: number[]/** Aggregate over matching events. Returned only when includeBreakdown is true. */@@ -1648,7 +1689,7 @@ export interface ErrorTrackingIssuesListQueryRequestApi {/** Filter by SDK/library value from event $lib, for example posthog-js. */library?: string | string[]/**- * Filter by exact release ID, version, or git commit ID captured in $exception_releases.+ * Filter by exact release ID, version, or git commit ID captured in $exception_release.* @maxLength 500*/release?: stringdiff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex 7cfa6af22581..455f063aa85b 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -1211,7 +1211,7 @@ export const getErrorTrackingQueryIssueCreateUrl = (projectId: string) => {}/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.+ * Fetch one error tracking issue with impact counts, trend, top in_app frame, first and latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const errorTrackingQueryIssueCreate = async (diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.tsindex ee79f928d85c..8bf077731be3 100644--- a/products/error_tracking/frontend/generated/api.zod.ts+++ b/products/error_tracking/frontend/generated/api.zod.ts@@ -568,7 +568,7 @@ export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod.object({})/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.+ * Fetch one error tracking issue with impact counts, trend, top in_app frame, first and latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const errorTrackingQueryIssueCreateBodyFilterTestAccountsDefault = true@@ -1009,7 +1009,7 @@ export const ErrorTrackingQueryIssuesListCreateBody = /* @__PURE__ */ zod.object.string().max(errorTrackingQueryIssuesListCreateBodyReleaseMax).optional()- .describe('Filter by exact release ID, version, or git commit ID captured in $exception_releases.'),+ .describe('Filter by exact release ID, version, or git commit ID captured in $exception_release.'),fingerprint: zod.union([zod.string(), zod.array(zod.string()).min(1)]).optional()diff --git a/products/error_tracking/mcp/prompts/query-error-tracking-issue.md b/products/error_tracking/mcp/prompts/query-error-tracking-issue.mdindex 45459cd0fbb2..3aa493a2673b 100644--- a/products/error_tracking/mcp/prompts/query-error-tracking-issue.md+++ b/products/error_tracking/mcp/prompts/query-error-tracking-issue.md@@ -1,6 +1,6 @@Get compact details for one Error tracking issue.-Use this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.+Use this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, trend, top in-app frame, and first and latest release metadata.Defaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.@@ -8,10 +8,15 @@ Defaults are intentionally useful: last 7 days, test accounts filtered out, aggr- `issueId`: required Error tracking issue UUID.- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.-- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.+- `includeSparkline`: set true only if the shape of the volume over time helps answer the user. To ask whether the issue is getting worse or better, read `trend` instead. When true, `volumeResolution` defaults to 12 if not provided.- `volumeResolution`: integer count of equal-width buckets across `dateRange`, from 0 to 200, when sparkline data is needed. It is not a unit such as `hour` or `day`. For daily buckets over the default 7-day range, send `7`.- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.+# Response fields++- `first_release`: the release on the issue's first event, in the same shape as `latest_release`. It does not depend on `dateRange`. When the user asks which release caused the issue, compare it with `latest_release`. It is absent when the first event has no release metadata.+- `trend`: occurrences in the second half of `dateRange` against the first half. Read `direction` (`new`, `increasing`, `decreasing` or `stable`) and do not do the arithmetic again. `increasing` and `decreasing` mean a change of at least 25%. `new` means the issue was first seen in the second half. With small counts, check `current_occurrences` and `previous_occurrences` before you call a change significant. `trend` is absent when the issue has no occurrences in `dateRange`.+# Next stepsUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.diff --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 221f19c16a77..37c288525344 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@@ -15,7 +15,7 @@ Be minimalist. Only add filters needed to answer the user’s question. Do not a- `status`: `active`, `resolved`, `suppressed`, `pending_release`, `archived`, or `all`. Defaults to `active`.- `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_releases`. This intentionally does not match project name, branch, or timestamp fragments.+- `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.- `fingerprint`: exact `$exception_fingerprint` match.- `url`: substring match on `$current_url`.- `personId`: exact PostHog person UUID.diff --git a/products/today/backend/tests/test_highlight_rage.py b/products/today/backend/tests/test_highlight_rage.pyindex 6e792d4bf7e9..b7dda9913727 100644--- a/products/today/backend/tests/test_highlight_rage.py+++ b/products/today/backend/tests/test_highlight_rage.py@@ -117,6 +117,7 @@ class TestRage(SimpleTestCase):description="Cannot read properties of undefined",status="active",severity=None,+ first_seen=None,)registered = next(s for s in load_sources() if s.name == "rage")diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 2b0cdc49f5a6..1e4e374c9e77 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -10462,7 +10462,7 @@"reads_ingested_data": "events"},"query-error-tracking-issue": {- "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: integer count of equal-width buckets across `dateRange`, from 0 to 200, when sparkline data is needed. It is not a unit such as `hour` or `day`. For daily buckets over the default 7-day range, send `7`.\n- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.",+ "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, trend, top in-app frame, and first and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if the shape of the volume over time helps answer the user. To ask whether the issue is getting worse or better, read `trend` instead. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: integer count of equal-width buckets across `dateRange`, from 0 to 200, when sparkline data is needed. It is not a unit such as `hour` or `day`. For daily buckets over the default 7-day range, send `7`.\n- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Response fields\n\n- `first_release`: the release on the issue's first event, in the same shape as `latest_release`. It does not depend on `dateRange`. When the user asks which release caused the issue, compare it with `latest_release`. It is absent when the first event has no release metadata.\n- `trend`: occurrences in the second half of `dateRange` against the first half. Read `direction` (`new`, `increasing`, `decreasing` or `stable`) and do not do the arithmetic again. `increasing` and `decreasing` mean a change of at least 25%. `new` means the issue was first seen in the second half. With small counts, check `current_occurrences` and `previous_occurrences` before you call a change significant. `trend` is absent when the issue has no occurrences in `dateRange`.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issue",@@ -10494,7 +10494,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_releases`. 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- `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.","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 4c98b2178660..2d4351f5e567 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11068,7 +11068,7 @@"reads_ingested_data": "events"},"query-error-tracking-issue": {- "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, top in-app frame, and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if a trend/sparkline helps answer the user. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: integer count of equal-width buckets across `dateRange`, from 0 to 200, when sparkline data is needed. It is not a unit such as `hour` or `day`. For daily buckets over the default 7-day range, send `7`.\n- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.",+ "description": "Get compact details for one Error tracking issue.\n\nUse this after `query-error-tracking-issues-list` when you have an `issueId` and need issue status, severity, name/description, first/last seen timestamps, assignee, compact impact counts, trend, top in-app frame, and first and latest release metadata.\n\nDefaults are intentionally useful: last 7 days, test accounts filtered out, aggregate impact included, and no sparkline unless requested.\n\n# Parameters\n\n- `issueId`: required Error tracking issue UUID.\n- `dateRange`: time range for impact counts and latest-event metadata. Defaults to last 7 days.\n- `includeSparkline`: set true only if the shape of the volume over time helps answer the user. To ask whether the issue is getting worse or better, read `trend` instead. When true, `volumeResolution` defaults to 12 if not provided.\n- `volumeResolution`: integer count of equal-width buckets across `dateRange`, from 0 to 200, when sparkline data is needed. It is not a unit such as `hour` or `day`. For daily buckets over the default 7-day range, send `7`.\n- `includeBreakdown`: set true when the user asks where, for whom, or on which platforms the issue happens. It returns the same breakdowns as the issue page, over all matching events: the most common paths (or URLs, when events have no path, as with backend SDKs), screens, browsers, OS, libraries, library versions, and app versions, each with a count, and up to 5 `$session_id` values with the most events. It covers at most the last 30 days of `dateRange`; `range_limited` is true when it covers less than you asked for. Empty dimensions are left out.\n\n# Response fields\n\n- `first_release`: the release on the issue's first event, in the same shape as `latest_release`. It does not depend on `dateRange`. When the user asks which release caused the issue, compare it with `latest_release`. It is absent when the first event has no release metadata.\n- `trend`: occurrences in the second half of `dateRange` against the first half. Read `direction` (`new`, `increasing`, `decreasing` or `stable`) and do not do the arithmetic again. `increasing` and `decreasing` mean a change of at least 25%. `new` means the issue was first seen in the second half. With small counts, check `current_occurrences` and `previous_occurrences` before you call a change significant. `trend` is absent when the issue has no occurrences in `dateRange`.\n\n# Next steps\n\nUse `query-error-tracking-issue-events` with the same `issueId` only when the user needs a concrete event, a stack trace, code variables, OpenTelemetry trace IDs, or the handled flag. Do not fetch many events to count browsers, URLs, or versions; use `includeBreakdown` instead.\n\nWhen `sample_session_ids` is not empty and the user asks what happened before the error, call `query-session-recordings-list` with `session_ids`.","category": "Error tracking","feature": "error_tracking","summary": "Query error tracking issue",@@ -11100,7 +11100,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_releases`. 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- `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.","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 bf7df22e7577..c42bad04cf74 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -41194,6 +41194,44 @@ export namespace Schemas {repo_name?: string;}+ /**+ * * `new` - New+ * * `increasing` - Increasing+ * * `decreasing` - Decreasing+ * * `stable` - Stable+ */+ export type IssueTrendDirectionEnum = typeof IssueTrendDirectionEnum[keyof typeof IssueTrendDirectionEnum];+++ export const IssueTrendDirectionEnum = {+ New: 'new',+ Increasing: 'increasing',+ Decreasing: 'decreasing',+ Stable: 'stable',+ } as const;++ export interface ErrorTrackingIssueTrend {+ /** Occurrences in the second half of dateRange against the first half. 'increasing' or 'decreasing' means a change of at least 25%. 'new' means the issue first occurred in the second half, counting merged fingerprints. 'stable' means a smaller change.+ *+ * * `new` - New+ * * `increasing` - Increasing+ * * `decreasing` - Decreasing+ * * `stable` - Stable */+ direction: IssueTrendDirectionEnum;+ /** Occurrences in the second half of dateRange. */+ current_occurrences: number;+ /** Occurrences in the first half of dateRange. */+ previous_occurrences: number;+ /** Percent change from the first half to the second half. Absent when the first half has no occurrences. */+ change_percent?: number;+ /** Start of the first half. */+ previous_from: string;+ /** End of the first half. */+ previous_to: string;+ /** Start of the second half. The second half ends at the end of dateRange. */+ current_from: string;+ }+export interface ErrorTrackingIssueDetail {/** Error tracking issue ID. */id: string;@@ -41244,8 +41282,12 @@ export namespace Schemas {top_in_app_frame?: ErrorTrackingTopFrame;/** Latest release metadata. */latest_release?: ErrorTrackingLatestRelease;+ /** Release metadata from the issue's first event, found near first_seen and not limited by dateRange. Compare it with latest_release to see which release introduced the issue. Absent when the first event has no release metadata. */+ first_release?: ErrorTrackingLatestRelease;/** Compact impact counts. */impact?: ErrorTrackingImpact;+ /** Whether the issue is getting worse or better: occurrences in the second half of dateRange against the first half. Absent when the issue has no occurrences in dateRange. */+ trend?: ErrorTrackingIssueTrend;/** Optional compact occurrence sparkline. */sparkline?: number[];/** Aggregate over matching events. Returned only when includeBreakdown is true. */@@ -41681,7 +41723,7 @@ export namespace Schemas {/** Filter by SDK/library value from event $lib, for example posthog-js. */library?: string | string[];/**- * Filter by exact release ID, version, or git commit ID captured in $exception_releases.+ * Filter by exact release ID, version, or git commit ID captured in $exception_release.* @maxLength 500*/release?: string;diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.tsindex 5e74331c6a2e..be665d6d64cd 100644--- a/services/mcp/src/generated/error_tracking/api.ts+++ b/services/mcp/src/generated/error_tracking/api.ts@@ -8216,7 +8216,7 @@ export const ErrorTrackingIssuesSplitCreateBody = () => zod.object({})/**- * Fetch one error tracking issue with impact counts, top in_app frame, latest release, and optional sparkline and event breakdown.+ * Fetch one error tracking issue with impact counts, trend, top in_app frame, first and latest release, and optional sparkline and event breakdown.* @summary Get compact error tracking issue details*/export const ErrorTrackingQueryIssueCreateParams = () => zod.object({@@ -8681,7 +8681,7 @@ export const ErrorTrackingQueryIssuesListCreateBody = () => zod.object({.string().max(errorTrackingQueryIssuesListCreateBodyReleaseMax).optional()- .describe('Filter by exact release ID, version, or git commit ID captured in $exception_releases.'),+ .describe('Filter by exact release ID, version, or git commit ID captured in $exception_release.'),fingerprint: zod.union([zod.string(), zod.array(zod.string()).min(1)]).optional()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 18c3c843a12f..d05c45430a70 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@@ -247,7 +247,7 @@"type": "string"},"release": {- "description": "Filter by exact release ID, version, or git commit ID captured in $exception_releases.",+ "description": "Filter by exact release ID, version, or git commit ID captured in $exception_release.","maxLength": 500,"type": "string"},