Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(metrics): overlay error tracking spikes on metric charts (PoC) (#88055)

Jimmy Zhu39e3af9630a2
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 03699f95c62b..f32e89782463 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -405,6 +405,7 @@ export const FEATURE_FLAGS = {
MEMBER_BILLING_USAGE_SPEND_READ_ACCESS: 'member-billing-usage-spend-read-access', // owner: @pawelcebula #team-billing, grants members read-only access to billing usage/spend tabs; owner-only-billing takes precedence
MESSAGING_SES: 'messaging-ses', // owner #team-workflows
METRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)
+ METRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics charts
NEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-ux
NEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analytics
NOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-tools
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index e5a469dc90ec..874d1e859b77 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -82,6 +82,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
```
- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.
+- A custom overlay child with its own click/hover behavior (e.g. a clickable marker) should mark its interactive root with the `data-hog-charts-interactive-overlay` attribute. It bubbles inside the same wrapper the chart's own mousemove hover tracking listens on, so without the attribute the chart's nearest-point tooltip fights the overlay's own tooltip for the cursor.
- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.
- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) from the sum, and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored. Rows share one grid (swatch, label, value), so the value column is as wide as the widest value and every row's label ends at the same x — a `labelRenderer` that pushes part of its label right (e.g. a date) lines up as a column down the tooltip. Pinned tooltips are copy-friendly: outside-dismissal keys off where the press _started_ (pointer-down outside the tooltip/chart, or Escape), so a text-selection drag that releases outside the tooltip doesn't dismiss it, and a click that completes a text selection inside a row doesn't fire `onRowClick`.
- A custom `tooltip` render prop builds its panel from the exported tooltip pieces: `TooltipSurface` (the floating panel), `TooltipSwatch` (series-color dot), and `TooltipFooter` (divider + muted row for a "click to inspect" hint — the same slot `DefaultTooltip`'s `footer` renders into, so a bespoke tooltip's hint stays styled like the built-in one).
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index bef563f481fe..f9127205e239 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -24,11 +24,24 @@ import { useDragToZoom } from './useDragToZoom'
import { useLatest } from './useLatest'
import { useTooltipLifecycle } from './useTooltipLifecycle'
+function originatesInElement(e: React.SyntheticEvent, selector: string): boolean {
+ return e.target instanceof Element && !!e.target.closest(selector)
+}
+
/** The tooltip is portaled out of the wrapper's DOM tree, but React portals still bubble
* synthetic events through the React tree — so a click or drag that starts inside the pinned
* tooltip reaches the wrapper's handlers and would dismiss the pin or start a zoom drag. */
function originatesInTooltip(e: React.SyntheticEvent): boolean {
- return e.target instanceof Element && !!e.target.closest('[data-hog-charts-tooltip]')
+ return originatesInElement(e, '[data-hog-charts-tooltip]')
+}
+
+/** An interactive overlay child (e.g. a clickable exemplar marker) renders inside the same
+ * wrapper this hook's mousemove handler is bound to, so every hover over it still bubbles here.
+ * Without this guard the chart's own nearest-point tooltip fights the overlay child's tooltip
+ * for the cursor. An overlay opts out of chart hover tracking by marking its interactive root
+ * with this attribute. */
+function originatesInInteractiveOverlay(e: React.SyntheticEvent): boolean {
+ return originatesInElement(e, '[data-hog-charts-interactive-overlay]')
}
interface UseChartInteractionOptions<Meta> {
@@ -285,6 +298,15 @@ export function useChartInteraction<Meta = unknown>({
return
}
+ if (originatesInInteractiveOverlay(e)) {
+ // Matches onMouseLeave. A pinned tooltip stays until explicitly unpinned, so
+ // moving onto an overlay marker must not clear it out from under the user.
+ if (!isPinned) {
+ clearTooltip()
+ }
+ return
+ }
+
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
@@ -480,7 +502,7 @@ export function useChartInteraction<Meta = unknown>({
const guardedMouseDown = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
- if (originatesInTooltip(e)) {
+ if (originatesInTooltip(e) || originatesInInteractiveOverlay(e)) {
return
}
onMouseDown(e)
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 3b0b10891ba0..3295f46891df 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -244,11 +244,12 @@ def list_spike_events(
order_by: str | None = None,
limit: int | None = None,
offset: int = 0,
+ include_total_count: bool = True,
) -> tuple[list[contracts.ErrorTrackingSpikeEvent], int]:
qs = logic.list_spike_events(
team_id=team_id, issue_ids=issue_ids, date_from=date_from, date_to=date_to, order_by=order_by
)
- total = qs.count()
+ total = qs.count() if include_total_count else 0
rows = qs if limit is None else qs[offset : offset + limit]
return [_to_spike_event(event) for event in rows], total
diff --git a/products/error_tracking/frontend/utils.test.ts b/products/error_tracking/frontend/utils.test.ts
index 6b491795e42e..4dcda97f1c10 100644
--- a/products/error_tracking/frontend/utils.test.ts
+++ b/products/error_tracking/frontend/utils.test.ts
@@ -220,6 +220,21 @@ describe('getIssueReplayDateRange', () => {
'2024-01-01T13:00:00.000Z'
)
})
+
+ // first_seen is null for an issue with no ingested events — reachable via the
+ // metrics error-spike overlay, and it used to crash the issue scene render.
+ it('anchors on last_seen when first_seen is missing', () => {
+ const range = getIssueReplayDateRange(null, dayjs('2024-01-02T12:00:00.000Z'))
+ expect(range.date_from).toEqual('2024-01-02T11:00:00.000Z')
+ expect(range.date_to).toEqual('2024-01-02T13:00:00.000Z')
+ })
+
+ it('anchors on the selected event when first_seen and last_seen are missing', () => {
+ const range = getIssueReplayDateRange(null, null, '2024-04-01T12:00:00.000Z')
+ expect(range.date_from).toEqual('2024-04-01T11:00:00.000Z')
+ expect(range.date_to).toEqual('2024-04-01T13:00:00.000Z')
+ expect(() => getIssueReplayDateRange(null, null)).not.toThrow()
+ })
})
describe('getIssueReplayFilterGroup', () => {
diff --git a/products/error_tracking/frontend/utils.ts b/products/error_tracking/frontend/utils.ts
index ece17638fc34..a43bc324d7fb 100644
--- a/products/error_tracking/frontend/utils.ts
+++ b/products/error_tracking/frontend/utils.ts
@@ -115,12 +115,18 @@ export function isThirdPartyScriptError(value: ErrorTrackingException['value']):
// before the exception fired, and past last_seen so a single-occurrence issue isn't a zero-width window.
// The selected event keeps the range valid when the user clicks before the last_seen query finishes.
export function getIssueReplayDateRange(
- firstSeen: string,
+ firstSeen: string | null | undefined,
lastSeen: Dayjs | null,
selectedEventTimestamp?: string | null
): DateRange {
- const from = dayjs(firstSeen)
+ const firstSeenAt = dayjs(firstSeen)
const selectedEventSeenAt = selectedEventTimestamp ? dayjs(selectedEventTimestamp) : null
+ // first_seen is annotated from fingerprint rows, so an issue with no ingested events
+ // (reachable via the metrics error-spike overlay) has none — anchor on another known
+ // timestamp instead of letting toISOString throw on an invalid date.
+ const from = firstSeenAt.isValid()
+ ? firstSeenAt
+ : ([lastSeen, selectedEventSeenAt].find((d): d is Dayjs => !!d?.isValid()) ?? dayjs())
const latestKnownSeenAt =
selectedEventSeenAt?.isValid() && (!lastSeen || selectedEventSeenAt.isAfter(lastSeen))
? selectedEventSeenAt
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index a4e79143ad0e..b49397e2147b 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -12,6 +12,7 @@ from typing import Any
from posthog.models import Team
+from products.error_tracking.backend.facade.api import list_spike_events
from products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomaly
from products.metrics.backend.diagnostics import decompose_bucket as _decompose_bucket
from products.metrics.backend.facade.contracts import (
@@ -20,6 +21,7 @@ from products.metrics.backend.facade.contracts import (
InvestigationResult,
MetricAnomalyReport,
MetricBucketDecomposition,
+ MetricErrorSpike,
MetricEventSample,
MetricFilter,
MetricPoint,
@@ -327,6 +329,35 @@ def list_metric_event_samples(
return [MetricEventSample(**row) for row in runner.run()]
+# PoC cap: team-wide — Error Tracking spike events carry no service attribution,
+# so there is no correlation key to scope them to one metric's service yet.
+_ERROR_SPIKES_LIMIT = 200
+
+
+def list_metric_error_spikes(*, team: Team, date_from: dt.datetime, date_to: dt.datetime) -> list[MetricErrorSpike]:
+ """List Error Tracking issue spikes detected in a time window, for the
+ metrics chart's error-spike overlay.
+
+ Team-wide: Error Tracking issues carry no service attribution today, so
+ this cannot be scoped to the metric's own service yet.
+ """
+ events, _total = list_spike_events(
+ team_id=team.id,
+ date_from=date_from.isoformat(),
+ date_to=date_to.isoformat(),
+ limit=_ERROR_SPIKES_LIMIT,
+ include_total_count=False,
+ )
+ return [
+ MetricErrorSpike(
+ detected_at=event.detected_at.isoformat(),
+ issue_id=str(event.issue.id),
+ issue_name=event.issue.name,
+ )
+ for event in events
+ ]
+
+
def characterize_metric_anomaly(
*,
team: Team,
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 73aaaa7f3d76..44851ff9e2ed 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -32,6 +32,10 @@ MAX_CLAUSES_PER_QUERY = 10
# must check the same flag, or one of them becomes a bypass.
METRICS_FEATURE_FLAG = "metrics"
+# Extra gate for the error-spike overlay PoC, layered on top of METRICS_FEATURE_FLAG.
+# Staff-only while it is a proof of concept.
+METRICS_ERROR_OVERLAYS_FEATURE_FLAG = "metrics-error-overlays"
+
@dataclass(frozen=True, slots=True)
class MetricFilter:
@@ -191,6 +195,27 @@ class MetricEventSample:
resource_attributes: dict[str, str]
+@dataclass(frozen=True, slots=True)
+class MetricErrorSpike:
+ """An Error Tracking issue spike detected in a time window.
+
+ PoC for the metrics chart's error-spike overlay: team-wide, not yet
+ scoped to a specific metric's service (Error Tracking issues carry no
+ service attribution today; scoping needs a service attribute on spikes
+ or a trace_id join against $exception events).
+
+ Deliberately narrower than error_tracking's own ErrorTrackingSpikeEvent
+ contract (fewer fields, string timestamps instead of datetime) since the
+ chart overlay only needs enough to render and link a marker. Keep it
+ narrow rather than reusing that contract directly, so metrics isn't
+ coupled to error_tracking's internal shape.
+ """
+
+ detected_at: str # ISO 8601
+ issue_id: str
+ issue_name: str | None
+
+
@dataclass(frozen=True, slots=True)
class CompanionMetric:
"""A metric to check alongside the primary one to confirm or rule out a
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index ed6fcc6d8ffe..4069eb6578a8 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -6,13 +6,14 @@ recognizable.
import datetime as dt
from dataclasses import asdict
+from typing import cast
from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import ParseError
+from rest_framework.exceptions import ParseError, PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
@@ -20,7 +21,8 @@ from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import report_user_action
-from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.models import User
+from posthog.permissions import PostHogFeatureFlagPermission, posthog_feature_flag_enabled
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from products.metrics.backend.facade.api import (
@@ -29,6 +31,7 @@ from products.metrics.backend.facade.api import (
get_metrics_overview,
list_metric_attribute_keys,
list_metric_attribute_values,
+ list_metric_error_spikes,
list_metric_event_samples,
list_metric_names,
run_metric_query,
@@ -36,6 +39,7 @@ from products.metrics.backend.facade.api import (
)
from products.metrics.backend.facade.contracts import (
MAX_CLAUSES_PER_QUERY,
+ METRICS_ERROR_OVERLAYS_FEATURE_FLAG,
METRICS_FEATURE_FLAG,
MetricFilter,
MetricGroupBy,
@@ -608,6 +612,35 @@ class _MetricSamplesResponseSerializer(serializers.Serializer):
)
+class _MetricErrorSpikesParamsSerializer(serializers.Serializer):
+ dateFrom = serializers.DateTimeField(
+ help_text="Lower bound (inclusive) for the spike window. ISO 8601.",
+ )
+ dateTo = serializers.DateTimeField(
+ required=False,
+ help_text="Upper bound (exclusive) for the spike window. Defaults to now if omitted.",
+ )
+
+
+class _MetricErrorSpikeSerializer(serializers.Serializer):
+ detected_at = serializers.CharField(help_text="When the error spike was detected, ISO 8601.")
+ issue_id = serializers.CharField(help_text="Error Tracking issue that spiked.")
+ issue_name = serializers.CharField(
+ allow_null=True,
+ help_text="Issue name, if one is set.",
+ )
+
+
+class _MetricErrorSpikesResponseSerializer(serializers.Serializer):
+ results = _MetricErrorSpikeSerializer(
+ many=True,
+ help_text=(
+ "Error Tracking issue spikes detected in the window, newest first. Team-wide: not yet "
+ "scoped to a specific metric's service."
+ ),
+ )
+
+
class _MetricExplainBodySerializer(serializers.Serializer):
metricName = serializers.CharField(
max_length=255,
@@ -968,6 +1001,46 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return Response({"results": [asdict(s) for s in samples]}, status=status.HTTP_200_OK)
+ @extend_schema(
+ parameters=[_MetricErrorSpikesParamsSerializer], responses={200: _MetricErrorSpikesResponseSerializer}
+ )
+ # Both scopes: the response is Error Tracking data, so a token scoped to metrics
+ # alone must not reach it (scopes gate the token; the access-control check below
+ # gates the user).
+ @action(detail=False, methods=["GET"], required_scopes=["metrics:read", "error_tracking:read"])
+ def error_spikes(self, request: Request, *args, **kwargs) -> Response:
+ """Error Tracking issue spikes detected in a time window — backs the
+ metrics chart's error-spike overlay (PoC). Team-wide: not yet scoped
+ to the metric's own service."""
+ # Layered on top of the viewset's `metrics` gate: the overlay is a PoC
+ # kept to staff only, so it needs its own flag even once metrics is on.
+ if not posthog_feature_flag_enabled(
+ METRICS_ERROR_OVERLAYS_FEATURE_FLAG,
+ str(cast(User, request.user).distinct_id),
+ organization_id=self.team.organization_id,
+ team_id=self.team.pk,
+ ):
+ raise PermissionDenied("The metrics error-spike overlay is not enabled for this user.")
+
+ # This action serves Error Tracking data (issue ids and names), so the caller
+ # needs view access to that resource too — metrics access alone must not leak
+ # it. The frontend hides the overlay on the same condition.
+ if not self.user_access_control.check_access_level_for_resource("error_tracking", "viewer"):
+ raise PermissionDenied("You do not have access to error tracking.")
+
+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)
+
+ params = _MetricErrorSpikesParamsSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+
+ spikes = list_metric_error_spikes(
+ team=self.team,
+ date_from=params.validated_data["dateFrom"],
+ date_to=params.validated_data.get("dateTo") or timezone.now(),
+ )
+
+ return Response({"results": [asdict(s) for s in spikes]}, status=status.HTTP_200_OK)
+
@extend_schema(request=_MetricExplainRequestSerializer, responses={200: _MetricExplainResponseSerializer})
@action(
detail=False,
diff --git a/products/metrics/backend/tests/test_api.py b/products/metrics/backend/tests/test_api.py
index 36c2302edd33..2f3c194cca68 100644
--- a/products/metrics/backend/tests/test_api.py
+++ b/products/metrics/backend/tests/test_api.py
@@ -1,22 +1,28 @@
+from datetime import timedelta
+
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.apps import apps
from django.test import SimpleTestCase
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.facade.user_access_control import (
ACCESS_CONTROL_RESOURCES,
AccessControlLevelResource,
)
from products.access_control.backend.models.access_control import AccessControl
+from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSpikeEvent
def test_metrics_app_is_installed():
@@ -42,6 +48,70 @@ class TestMetricsValuesApi(APIBaseTest):
assert response.json()["attr"] == "limit"
+class TestMetricsErrorSpikesApi(APIBaseTest):
+ def test_returns_spikes_from_error_tracking_in_the_window(self) -> None:
+ issue = ErrorTrackingIssue.objects.create(team=self.team, name="Boom")
+ now = timezone.now()
+ ErrorTrackingSpikeEvent.objects.create(
+ team=self.team,
+ issue=issue,
+ detected_at=now,
+ computed_baseline=1.0,
+ current_bucket_value=10,
+ )
+
+ # The overlay is a staff-only PoC behind its own flag, on top of the
+ # `metrics` gate the conftest already enables — turn both on here.
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/metrics/error_spikes/",
+ {"dateFrom": (now - timedelta(hours=1)).isoformat()},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert len(results) == 1
+ assert results[0]["issue_id"] == str(issue.id)
+ assert results[0]["issue_name"] == "Boom"
+
+ def test_is_forbidden_when_only_the_metrics_flag_is_enabled(self) -> None:
+ # The autouse conftest enables `metrics` but not `metrics-error-overlays`,
+ # so the endpoint must stay closed even though the rest of metrics is open.
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/metrics/error_spikes/",
+ {"dateFrom": (timezone.now() - timedelta(hours=1)).isoformat()},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @parameterized.expand(
+ [
+ ("metrics_scope_only", ["metrics:read"], status.HTTP_403_FORBIDDEN),
+ ("both_scopes", ["metrics:read", "error_tracking:read"], status.HTTP_200_OK),
+ ]
+ )
+ def test_token_needs_the_error_tracking_scope_too(
+ self, _name: str, scopes: list[str], expected_status: int
+ ) -> None:
+ # The response is Error Tracking data, so a token delegated only metrics:read
+ # must not reach it — the scope check is the token-level counterpart of the
+ # user-level access-control check.
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="scoped", user=self.user, secure_value=hash_key_value(token), scopes=scopes)
+ self.client.logout()
+
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/metrics/error_spikes/",
+ {"dateFrom": (timezone.now() - timedelta(hours=1)).isoformat()},
+ headers={"authorization": f"Bearer {token}"},
+ )
+
+ assert response.status_code == expected_status
+ if expected_status == status.HTTP_403_FORBIDDEN:
+ assert response.json()["detail"] == "API key missing required scope 'error_tracking:read'"
+
+
class TestMetricsFeatureFlagGate(APIBaseTest):
@parameterized.expand(
[
@@ -73,11 +143,13 @@ class TestMetricsAccessControl(APIBaseTest):
self.organization, "[email protected]", "testtest"
)
- def _create_access_control(self, user: User, access_level: AccessControlLevelResource) -> None:
+ def _create_access_control(
+ self, user: User, access_level: AccessControlLevelResource, resource: str = "metrics"
+ ) -> None:
membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
AccessControl.objects.create(
team=self.team,
- resource="metrics",
+ resource=resource,
resource_id=None,
access_level=access_level,
organization_member=membership,
@@ -111,6 +183,7 @@ class TestMetricsAccessControl(APIBaseTest):
("attribute_values", "GET", {}),
("query", "POST", {}),
("samples", "POST", {}),
+ ("error_spikes", "GET", {}),
("explain", "POST", {}),
("characterize", "POST", {}),
]
@@ -128,3 +201,26 @@ class TestMetricsAccessControl(APIBaseTest):
response = self.client.post(url, payload, format="json")
assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @parameterized.expand(
+ [
+ ("error_tracking_viewer", "viewer", status.HTTP_200_OK),
+ ("error_tracking_none", "none", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_error_spikes_requires_error_tracking_access(
+ self, _name: str, error_tracking_level: AccessControlLevelResource, expected_status: int
+ ) -> None:
+ # The overlay endpoint serves Error Tracking data, so metrics access alone must not
+ # reach it — the caller also needs Error Tracking view access.
+ self._create_access_control(self.viewer_user, "viewer", resource="metrics")
+ self._create_access_control(self.viewer_user, error_tracking_level, resource="error_tracking")
+ self.client.force_login(self.viewer_user)
+
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/metrics/error_spikes/",
+ {"dateFrom": (timezone.now() - timedelta(hours=1)).isoformat()},
+ )
+
+ assert response.status_code == expected_status
diff --git a/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx b/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx
index 350949735d7f..bc138acd1727 100644
--- a/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx
+++ b/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx
@@ -6,6 +6,15 @@ import { dimensions, makeOverlayContext, renderOverlayInChart } from '@posthog/q
import { MetricsExemplarMarkers } from './MetricsExemplarMarkers'
+// jsdom has no stylesheet to resolve real color vars from, so both tokens would
+// otherwise fall back to the same value — mock the lookup so per-marker colors
+// (e.g. error spikes using 'danger') are distinguishable in assertions below.
+// jsdom's style setter rejects `var(...)` as an inline value, so map to plain
+// hex colors instead of round-tripping the token name.
+jest.mock('lib/colors', () => ({
+ getColorVar: (variable: string) => (variable === 'danger' ? '#ff0000' : '#0000ff'),
+}))
+
// Three hourly buckets, laid out 100px apart, so an interpolated x is checkable by eye.
const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']
const BUCKET_X: Record<string, number> = { [BUCKETS[0]]: 100, [BUCKETS[1]]: 200, [BUCKETS[2]]: 300 }
@@ -14,7 +23,11 @@ const RADIUS = 4
function renderMarkers(timestamps: string[], onClick: () => void = jest.fn()): void {
renderOverlayInChart(
<MetricsExemplarMarkers
- exemplars={timestamps.map((timestamp) => ({ timeMs: Date.parse(timestamp), onClick }))}
+ exemplars={timestamps.map((timestamp) => ({
+ timeMs: Date.parse(timestamp),
+ onClick,
+ tooltipLabel: `test exemplar at ${timestamp}`,
+ }))}
/>,
makeOverlayContext(
{ x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
@@ -57,7 +70,9 @@ describe('MetricsExemplarMarkers', () => {
it('clamps an exemplar onto a single-bucket chart instead of dropping it', () => {
renderOverlayInChart(
- <MetricsExemplarMarkers exemplars={[{ timeMs: Date.parse('2026-08-01T10:30:00Z'), onClick: jest.fn() }]} />,
+ <MetricsExemplarMarkers
+ exemplars={[{ timeMs: Date.parse('2026-08-01T10:30:00Z'), onClick: jest.fn(), tooltipLabel: 'test' }]}
+ />,
makeOverlayContext(
{ x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
{ labels: [BUCKETS[0]] }
@@ -79,9 +94,55 @@ describe('MetricsExemplarMarkers', () => {
expect(onClick).toHaveBeenCalledTimes(1)
})
+ // Regression: error-spike markers sharing this overlay with trace exemplars
+ // must render in their own color, or the two kinds become visually identical.
+ it('uses a marker-specific color when provided, and the default otherwise', () => {
+ renderOverlayInChart(
+ <MetricsExemplarMarkers
+ exemplars={[
+ { timeMs: Date.parse(BUCKETS[0]), onClick: jest.fn(), tooltipLabel: 'default color' },
+ {
+ timeMs: Date.parse(BUCKETS[1]),
+ onClick: jest.fn(),
+ color: 'danger',
+ tooltipLabel: 'danger color',
+ },
+ ]}
+ />,
+ makeOverlayContext(
+ { x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
+ { labels: BUCKETS }
+ )
+ )
+ const [defaultDot, coloredDot] = screen.getAllByTestId('metrics-exemplar-marker')
+ expect(defaultDot.style.borderColor).toBe('#0000ff')
+ expect(coloredDot.style.borderColor).toBe('#ff0000')
+ })
+
+ // A screen-reader user tells markers apart only by aria-label, so it must match each
+ // marker's own content rather than a shared or hardcoded label.
+ it('labels each marker with its own tooltip text', () => {
+ renderOverlayInChart(
+ <MetricsExemplarMarkers
+ exemplars={[
+ { timeMs: Date.parse(BUCKETS[0]), onClick: jest.fn(), tooltipLabel: 'Traced emission' },
+ { timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn(), tooltipLabel: 'Error spike: checkout' },
+ ]}
+ />,
+ makeOverlayContext(
+ { x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
+ { labels: BUCKETS }
+ )
+ )
+ expect(screen.getByLabelText('Traced emission')).toBeInTheDocument()
+ expect(screen.getByLabelText('Error spike: checkout')).toBeInTheDocument()
+ })
+
it('renders nothing when the chart has no buckets yet', () => {
renderOverlayInChart(
- <MetricsExemplarMarkers exemplars={[{ timeMs: Date.parse(BUCKETS[0]), onClick: jest.fn() }]} />,
+ <MetricsExemplarMarkers
+ exemplars={[{ timeMs: Date.parse(BUCKETS[0]), onClick: jest.fn(), tooltipLabel: 'test' }]}
+ />,
makeOverlayContext({ x: () => undefined, y: (value) => value, yTicks: () => [] }, { labels: [] })
)
expect(screen.queryAllByTestId('metrics-exemplar-marker')).toHaveLength(0)
diff --git a/products/metrics/frontend/components/MetricsExemplarMarkers.tsx b/products/metrics/frontend/components/MetricsExemplarMarkers.tsx
index 79d33e59d552..42ec71d7f805 100644
--- a/products/metrics/frontend/components/MetricsExemplarMarkers.tsx
+++ b/products/metrics/frontend/components/MetricsExemplarMarkers.tsx
@@ -1,3 +1,4 @@
+import { Tooltip } from '@posthog/lemon-ui'
import { useChartLayout } from '@posthog/quill-charts'
import { getColorVar } from 'lib/colors'
@@ -8,6 +9,12 @@ export interface MetricsExemplar {
/** Emission time of the traced sample, as epoch ms. */
timeMs: number
onClick: () => void
+ /** Design-token color name. Defaults to 'brand-blue'; error-spike markers pass 'danger' so the
+ * two kinds sharing this overlay stay distinguishable. */
+ color?: string
+ /** Shown in a hover tooltip and as the button's aria-label — what this dot is, before
+ * the user clicks it. Required: an unlabeled dot on a chart is not self-explanatory. */
+ tooltipLabel: string
}
const RADIUS = 4
@@ -22,10 +29,21 @@ export function MetricsExemplarMarkers({ exemplars }: { exemplars: MetricsExempl
}
const bucketTimes = labels.map((label) => dayjs(label).valueOf())
- // `link`, not a data color: a dot navigates to a trace, and it must not read as a fourth series.
- const color = getColorVar('link')
const baseline = dimensions.plotTop + dimensions.plotHeight
+ // `getColorVar` reads computed styles (a potential style recalc), so resolve each
+ // distinct token once here rather than per marker — there are only a couple across
+ // the whole overlay (default plus any caller override like 'danger').
+ const resolvedColors = new Map<string, string>()
+ const colorFor = (token: string): string => {
+ let color = resolvedColors.get(token)
+ if (color === undefined) {
+ color = getColorVar(token)
+ resolvedColors.set(token, color)
+ }
+ return color
+ }
+
return (
<>
{exemplars.map((exemplar, index) => {
@@ -33,26 +51,32 @@ export function MetricsExemplarMarkers({ exemplars }: { exemplars: MetricsExempl
if (x === null) {
return null
}
+ const color = colorFor(exemplar.color ?? 'brand-blue')
return (
- <button
- key={`${exemplar.timeMs}-${index}`}
- type="button"
- aria-label={`Open the trace emitted at ${dayjs(exemplar.timeMs).format('D MMM YYYY HH:mm:ss')}`}
- data-attr="metrics-exemplar-marker"
- onClick={(e) => {
- e.stopPropagation()
- exemplar.onClick()
- }}
- className="absolute pointer-events-auto rounded-full border cursor-pointer transition-transform hover:scale-150"
- style={{
- left: x - RADIUS,
- top: baseline - RADIUS,
- width: RADIUS * 2,
- height: RADIUS * 2,
- backgroundColor: hexToRGBA(color, 0.85),
- borderColor: color,
- }}
- />
+ <Tooltip key={`${exemplar.timeMs}-${index}`} title={exemplar.tooltipLabel}>
+ <button
+ type="button"
+ aria-label={exemplar.tooltipLabel}
+ data-attr="metrics-exemplar-marker"
+ onClick={(e) => {
+ e.stopPropagation()
+ exemplar.onClick()
+ }}
+ // Opts this marker out of the chart's own hover/tooltip tracking (see
+ // `useChartInteraction`'s `originatesInInteractiveOverlay`), so hovering
+ // the dot shows its own tooltip instead of the chart's nearest-point one.
+ data-hog-charts-interactive-overlay
+ className="absolute pointer-events-auto rounded-full border cursor-pointer transition-transform hover:scale-150"
+ style={{
+ left: x - RADIUS,
+ top: baseline - RADIUS,
+ width: RADIUS * 2,
+ height: RADIUS * 2,
+ backgroundColor: hexToRGBA(color, 0.85),
+ borderColor: color,
+ }}
+ />
+ </Tooltip>
)
})}
</>
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.test.tsx b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
index b3ef06471622..424f319d1aaf 100644
--- a/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
+++ b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
@@ -11,6 +11,7 @@ import {
import { initKeaTests } from '~/test/init'
+import type { MetricsExemplar } from './MetricsExemplarMarkers'
import type { MetricsChartSeries } from './metricsSeries'
import { MetricsSeriesChart } from './MetricsSeriesChart'
@@ -20,7 +21,7 @@ function seriesWith(labels: Record<string, string>, values: (number | null)[]):
return { labels, points: BUCKETS.map((time, i) => ({ time, value: values[i] })) }
}
-function renderChart(series: MetricsChartSeries[], exemplars?: { timeMs: number; onClick: () => void }[]): void {
+function renderChart(series: MetricsChartSeries[], exemplars?: MetricsExemplar[]): void {
render(<MetricsSeriesChart series={series} fallbackName="http.requests" exemplars={exemplars} />)
}
@@ -54,7 +55,10 @@ describe('MetricsSeriesChart', () => {
})
it('renders a clickable dot per traced exemplar', () => {
- renderChart([seriesWith({}, [1, 2, 3])], [{ timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn() }])
+ renderChart(
+ [seriesWith({}, [1, 2, 3])],
+ [{ timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn(), tooltipLabel: 'test exemplar' }]
+ )
expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)
})
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index aef2d000053b..f4d8c917e553 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -23,11 +23,13 @@ import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
+import { urls } from 'scenes/urls'
import {
AccessControlLevel,
@@ -147,7 +149,10 @@ export const MetricsViewer = (): JSX.Element => {
closeAddToDashboardModal,
} = useActions(logic)
const { items: pickerItems } = useValues(pickerLogic)
- const { traceExemplars } = useValues(metricsSamplesLogic)
+ const { traceExemplars, errorSpikes, showErrorSpikes } = useValues(metricsSamplesLogic)
+ const { toggleShowErrorSpikes } = useActions(metricsSamplesLogic)
+ // Staff-only PoC gate, layered on top of the wider metrics alpha flag.
+ const errorOverlaysEnabled = useFeatureFlag('METRICS_ERROR_OVERLAYS')
const { exemplarDotClicked } = useActions(metricsUsageTrackingLogic)
const metricsViewerDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Metrics,
@@ -158,29 +163,53 @@ export const MetricsViewer = (): JSX.Element => {
AccessControlResourceType.Tracing,
AccessControlLevel.Viewer
)
+ const errorTrackingDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.ErrorTracking,
+ AccessControlLevel.Viewer
+ )
- // Traced emissions as clickable dots along the bottom of the chart — the
- // metric->trace pivot without opening the Samples tab. Skipped entirely when
- // the user can't view traces, so a dot never leads to a dead end.
- const exemplarMarkers: MetricsExemplar[] = useMemo(
- () =>
- tracingDisabledReason
+ // Clickable dots along the bottom of the chart: traced emissions (the
+ // metric->trace pivot) and Error Tracking issue spikes (team-wide — spike
+ // events carry no service attribution). Each kind is skipped entirely when
+ // the user can't view its target product, so a dot never leads to a dead
+ // end. One memo, so the chart prop keeps a stable identity across renders.
+ const chartMarkers: MetricsExemplar[] = useMemo(() => {
+ const traceMarkers: MetricsExemplar[] = tracingDisabledReason
+ ? []
+ : traceExemplars.map((exemplar) => ({
+ timeMs: dayjs(exemplar.timestamp).valueOf(),
+ tooltipLabel: `Traced emission at ${dayjs(exemplar.timestamp).format('D MMM HH:mm:ss')}. Click to view the trace.`,
+ onClick: () => {
+ exemplarDotClicked(!!exemplar.spanId)
+ router.actions.push(
+ traceUrl({
+ traceId: exemplar.traceId,
+ spanId: exemplar.spanId || null,
+ ts: exemplar.timestamp,
+ })
+ )
+ },
+ }))
+ const spikeMarkers: MetricsExemplar[] =
+ !errorOverlaysEnabled || errorTrackingDisabledReason
? []
- : traceExemplars.map((exemplar) => ({
- timeMs: dayjs(exemplar.timestamp).valueOf(),
+ : errorSpikes.map((spike) => ({
+ timeMs: dayjs(spike.detected_at).valueOf(),
+ color: 'danger',
+ tooltipLabel: `Error spike at ${dayjs(spike.detected_at).format('D MMM HH:mm:ss')}: ${spike.issue_name ?? 'Untitled issue'}. Click to view the issue.`,
onClick: () => {
- exemplarDotClicked(!!exemplar.spanId)
- router.actions.push(
- traceUrl({
- traceId: exemplar.traceId,
- spanId: exemplar.spanId || null,
- ts: exemplar.timestamp,
- })
- )
+ router.actions.push(urls.errorTrackingIssue(spike.issue_id, { timestamp: spike.detected_at }))
},
- })),
- [traceExemplars, tracingDisabledReason, exemplarDotClicked]
- )
+ }))
+ return [...traceMarkers, ...spikeMarkers]
+ }, [
+ traceExemplars,
+ tracingDisabledReason,
+ exemplarDotClicked,
+ errorSpikes,
+ errorOverlaysEnabled,
+ errorTrackingDisabledReason,
+ ])
// Refetch the chart whenever any filter changes — the loader breakpoint debounces input.
useEffect(() => {
@@ -261,6 +290,19 @@ export const MetricsViewer = (): JSX.Element => {
data-attr="metrics-viewer-live-toggle"
disabledReason={metricsViewerDisabledReason}
/>
+ {/* Hidden (not disabled) without Error Tracking view access, so the
+ toggle never references a product the user cannot see. */}
+ {errorOverlaysEnabled && !errorTrackingDisabledReason && (
+ <LemonSwitch
+ label="Error spikes"
+ checked={showErrorSpikes}
+ onChange={toggleShowErrorSpikes}
+ tooltip="Mark Error Tracking issue spikes on the chart (team-wide, PoC)"
+ bordered
+ data-attr="metrics-viewer-error-spikes-toggle"
+ disabledReason={metricsViewerDisabledReason}
+ />
+ )}
</div>
</div>
{/* Aggregation and grouping controls sit below the filter bar. */}
@@ -347,7 +389,7 @@ export const MetricsViewer = (): JSX.Element => {
<MetricsSeriesChart
series={chartSeries}
fallbackName={metricName}
- exemplars={exemplarMarkers}
+ exemplars={chartMarkers}
/>
) : !queryResultsLoading ? (
<div className="h-full flex items-center justify-center text-secondary text-sm">
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.test.ts b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
index 2573b8a568a1..29458a2f6e8c 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.test.ts
+++ b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
@@ -12,7 +12,7 @@ import {
UniversalFiltersGroupValue,
} from '~/types'
-import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
+import { metricsErrorSpikesRetrieve, metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import { metricsViewerLogic } from './metricsViewerLogic'
@@ -20,9 +20,11 @@ import { metricsViewerLogic } from './metricsViewerLogic'
jest.mock('products/metrics/frontend/generated/api', () => ({
...jest.requireActual('products/metrics/frontend/generated/api'),
metricsSamplesCreate: jest.fn(),
+ metricsErrorSpikesRetrieve: jest.fn(),
}))
const mockSamplesCreate = metricsSamplesCreate as jest.MockedFunction<typeof metricsSamplesCreate>
+const mockErrorSpikesRetrieve = metricsErrorSpikesRetrieve as jest.MockedFunction<typeof metricsErrorSpikesRetrieve>
const SAMPLE = {
timestamp: '2026-07-09T05:46:28.132600+00:00',
@@ -60,6 +62,12 @@ const UNTRACED_SAMPLE = {
span_id: '',
}
+const ERROR_SPIKE = {
+ detected_at: '2026-07-09T05:46:00.000000+00:00',
+ issue_id: '0198e2b1-0000-7000-8000-000000000001',
+ issue_name: 'NullPointerException',
+}
+
describe('metricsSamplesLogic', () => {
let logic: ReturnType<typeof metricsSamplesLogic.build>
@@ -69,11 +77,15 @@ describe('metricsSamplesLogic', () => {
resource_access_control: {
...window.POSTHOG_APP_CONTEXT?.resource_access_control,
[AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
+ // The error-spikes loader also requires Error Tracking view access.
+ [AccessControlResourceType.ErrorTracking]: AccessControlLevel.Viewer,
},
} as AppContext
initKeaTests()
mockSamplesCreate.mockReset()
mockSamplesCreate.mockResolvedValue({ results: [SAMPLE] })
+ mockErrorSpikesRetrieve.mockReset()
+ mockErrorSpikesRetrieve.mockResolvedValue({ results: [ERROR_SPIKE] })
metricsViewerLogic.mount()
logic = metricsSamplesLogic()
logic.mount()
@@ -213,4 +225,33 @@ describe('metricsSamplesLogic', () => {
await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
})
+
+ // Regression: an always-on error-spikes fetch would spam Error Tracking on
+ // every chart redraw for every metrics viewer, whether or not the overlay is
+ // visible — the toggle must gate the request, not just the chart markers.
+ it('does not fetch error spikes until the toggle is enabled', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+
+ metricsViewerLogic.actions.fetchQueryResultsSuccess([])
+ await expectLogic(logic).delay(10)
+
+ expect(mockErrorSpikesRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.errorSpikes).toEqual([])
+ })
+
+ // Regression: toggling on must actually fetch immediately, and the chart's
+ // ongoing refresh trigger must keep firing it afterwards — the overlay
+ // otherwise silently shows stale (or no) spikes once enabled.
+ it('fetches error spikes once the toggle is enabled', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+
+ logic.actions.toggleShowErrorSpikes()
+ await expectLogic(logic).toDispatchActions(['loadErrorSpikesSuccess'])
+ expect(mockErrorSpikesRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.errorSpikes).toEqual([ERROR_SPIKE])
+
+ metricsViewerLogic.actions.fetchQueryResultsSuccess([])
+ await expectLogic(logic).toDispatchActions(['loadErrorSpikesSuccess'])
+ expect(mockErrorSpikesRetrieve).toHaveBeenCalledTimes(2)
+ })
})
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index 127b98d27ef9..4b425d810db9 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -1,12 +1,14 @@
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'
-import { UniversalFiltersGroup } from '~/types'
+import { AccessControlLevel, AccessControlResourceType, UniversalFiltersGroup } from '~/types'
-import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
+import { metricsErrorSpikesRetrieve, metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
import type {
+ _MetricErrorSpikeApi,
_MetricEventSampleApi,
_MetricFilterApi,
OtelMetricTypeEnumApi,
@@ -50,8 +52,11 @@ export interface metricsSamplesLogicValues {
currentTeamId: number | null // teamLogic
activeTab: MetricsPanelTab
aggregateRows: MetricsAggregateRow[]
+ errorSpikes: _MetricErrorSpikeApi[]
+ errorSpikesLoading: boolean
samples: _MetricEventSampleApi[]
samplesLoading: boolean
+ showErrorSpikes: boolean
traceExemplars: MetricsTraceExemplar[]
}
@@ -79,6 +84,21 @@ export interface metricsSamplesLogicActions {
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
metricType: OtelMetricTypeEnumApi | null
} // metricsViewerLogic
+ loadErrorSpikes: (_: any) => any
+ loadErrorSpikesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadErrorSpikesSuccess: (
+ errorSpikes: _MetricErrorSpikeApi[],
+ payload?: any
+ ) => {
+ errorSpikes: _MetricErrorSpikeApi[]
+ payload?: any
+ }
loadSamples: (_: any) => any
loadSamplesFailure: (
error: string,
@@ -97,6 +117,9 @@ export interface metricsSamplesLogicActions {
setActiveTab: (activeTab: MetricsPanelTab) => {
activeTab: MetricsPanelTab
}
+ toggleShowErrorSpikes: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -140,9 +163,11 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
})),
actions({
setActiveTab: (activeTab: MetricsPanelTab) => ({ activeTab }),
+ toggleShowErrorSpikes: true,
}),
reducers({
activeTab: ['aggregates' as MetricsPanelTab, { setActiveTab: (_, { activeTab }) => activeTab }],
+ showErrorSpikes: [false, { toggleShowErrorSpikes: (state) => !state }],
}),
loaders(({ values }) => ({
samples: [
@@ -174,6 +199,36 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
},
},
],
+ errorSpikes: [
+ [] as _MetricErrorSpikeApi[],
+ {
+ loadErrorSpikes: async (_, breakpoint) => {
+ // The single gate for the overlay's data: listeners dispatch this
+ // unconditionally, and this guard decides — returning [] also clears
+ // stale spikes when the toggle turns off. Error Tracking view access
+ // is required because the response is that product's data.
+ if (
+ !canViewMetrics() ||
+ !values.showErrorSpikes ||
+ !userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer)
+ ) {
+ return []
+ }
+ const dateFrom = resolveDate(values.dateFrom)
+ if (!dateFrom) {
+ return []
+ }
+ await breakpoint(300)
+ const dateTo = resolveDate(values.dateTo) ?? undefined
+ const response = await metricsErrorSpikesRetrieve(String(values.currentTeamId), {
+ dateFrom,
+ ...(dateTo ? { dateTo } : {}),
+ })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
})),
selectors({
// Rows for the Aggregates tab, derived from the chart's series so both
@@ -222,9 +277,15 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
}
},
// The chart's exemplar overlay renders from these samples, so every chart
- // redraw refreshes them.
+ // redraw refreshes them. Error spikes ride the same trigger, so both
+ // overlays stay in sync with the chart's own window. Both dispatches are
+ // unconditional — the loaders' own guards are the single gate.
fetchQueryResultsSuccess: () => {
actions.loadSamples({})
+ actions.loadErrorSpikes({})
+ },
+ toggleShowErrorSpikes: () => {
+ actions.loadErrorSpikes({})
},
setMetricName: reloadWhenShown,
setDateFrom: reloadWhenShown,
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index e00fd6a82003..5619f7b0d282 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -270,6 +270,23 @@ export interface _MetricAnomalyReportApi {
series: _MetricSeriesApi
}
+export interface _MetricErrorSpikeApi {
+ /** When the error spike was detected, ISO 8601. */
+ detected_at: string
+ /** Error Tracking issue that spiked. */
+ issue_id: string
+ /**
+ * Issue name, if one is set.
+ * @nullable
+ */
+ issue_name: string | null
+}
+
+export interface _MetricErrorSpikesResponseApi {
+ /** Error Tracking issue spikes detected in the window, newest first. Team-wide: not yet scoped to a specific metric's service. */
+ results: _MetricErrorSpikeApi[]
+}
+
/**
* * `gauge` - gauge
* * `sum` - sum
@@ -807,6 +824,17 @@ export type MetricsAttributesRetrieveParams = {
search?: string
}
+export type MetricsErrorSpikesRetrieveParams = {
+ /**
+ * Lower bound (inclusive) for the spike window. ISO 8601.
+ */
+ dateFrom: string
+ /**
+ * Upper bound (exclusive) for the spike window. Defaults to now if omitted.
+ */
+ dateTo?: string
+}
+
export type MetricsValuesRetrieveParams = {
/**
* Max number of names to return. Defaults to 100; maximum 1000.
diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.ts
index 1c01893fbc50..fb4e3de668d1 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -13,12 +13,14 @@ import type {
AppMetricsTotalsResponseApi,
MetricsAttributeValuesRetrieveParams,
MetricsAttributesRetrieveParams,
+ MetricsErrorSpikesRetrieveParams,
MetricsValuesRetrieveParams,
_HasMetricsResponseApi,
_MetricAnomalyReportApi,
_MetricAnomalyRequestApi,
_MetricAttributeKeysResponseApi,
_MetricAttributeValuesResponseApi,
+ _MetricErrorSpikesResponseApi,
_MetricExplainRequestApi,
_MetricExplainResponseApi,
_MetricNamesResponseApi,
@@ -158,6 +160,38 @@ export const metricsCharacterizeCreate = async (
})
}
+export const getMetricsErrorSpikesRetrieveUrl = (projectId: string, params: MetricsErrorSpikesRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/metrics/error_spikes/?${stringifiedParams}`
+ : `/api/projects/${projectId}/metrics/error_spikes/`
+}
+
+/**
+ * Error Tracking issue spikes detected in a time window — backs the
+ * metrics chart's error-spike overlay (PoC). Team-wide: not yet scoped
+ * to the metric's own service.
+ */
+export const metricsErrorSpikesRetrieve = async (
+ projectId: string,
+ params: MetricsErrorSpikesRetrieveParams,
+ options?: RequestInit
+): Promise<_MetricErrorSpikesResponseApi> => {
+ return apiMutator<_MetricErrorSpikesResponseApi>(getMetricsErrorSpikesRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getMetricsExplainCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/metrics/explain/`
}
diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yaml
index 9ec372dde715..70880f737e24 100644
--- a/products/metrics/mcp/tools.yaml
+++ b/products/metrics/mcp/tools.yaml
@@ -44,6 +44,9 @@ tools:
metrics-attributes-retrieve:
operation: metrics_attributes_retrieve
enabled: false
+ metrics-error-spikes-retrieve:
+ operation: metrics_error_spikes_retrieve
+ enabled: false
metrics-explain-create:
operation: metrics_explain_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 17e4311471bb..869e0b290574 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -87192,6 +87192,23 @@ export namespace Schemas {
groupBy?: _MetricGroupBy[];
}
+ export interface _MetricErrorSpike {
+ /** When the error spike was detected, ISO 8601. */
+ detected_at: string;
+ /** Error Tracking issue that spiked. */
+ issue_id: string;
+ /**
+ * Issue name, if one is set.
+ * @nullable
+ */
+ issue_name: string | null;
+ }
+
+ export interface _MetricErrorSpikesResponse {
+ /** Error Tracking issue spikes detected in the window, newest first. Team-wide: not yet scoped to a specific metric's service. */
+ results: _MetricErrorSpike[];
+ }
+
/**
* Per-emission attributes (high-cardinality labels on the data point).
*/
@@ -95616,6 +95633,17 @@ export namespace Schemas {
search?: string;
};
+ export type MetricsErrorSpikesRetrieveParams = {
+ /**
+ * Lower bound (inclusive) for the spike window. ISO 8601.
+ */
+ dateFrom: string;
+ /**
+ * Upper bound (exclusive) for the spike window. Defaults to now if omitted.
+ */
+ dateTo?: string;
+ };
+
export type MetricsValuesRetrieveParams = {
/**
* Max number of names to return. Defaults to 100; maximum 1000.
diff --git a/tach.toml b/tach.toml
index 4c47f3239b39..b177f216fb5e 100644
--- a/tach.toml
+++ b/tach.toml
@@ -549,7 +549,7 @@ layer = "modules"
[[modules]]
path = "products.metrics"
-depends_on = ["posthog", "products.access_control"]
+depends_on = ["posthog", "products.access_control", "products.error_tracking"]
layer = "modules"
[[interfaces]]