:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(error-tracking): count only frames an upload would resolve (#121179)
Aleksander Błaszkiewicz65ef8b610461
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8048a7593a90..558a3045d377 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3224,6 +3224,14 @@ snapshots:hash: v1.k794b7964.48197d9cf132e3225936969e3d4d337db9811ab31ab2624df878317847e38109.6jga9VY3EA1ilp9PgPNPVdrux9Elev944fjSFOJjGqoerrortracking-ratelimitsimulationchart--with-limit--light:hash: v1.k794b7964.3319d12b63700f0e20c2345c8706223a8940d5fe37a4278a597ba5f13d81ba65.ubh71HB2yJA2-HrliI_wUJB_HMOlOgRNmgb_o0Lhu9U+ errortracking-sourcemapsexamplesbrowser--master-detail--dark:+ hash: v1.k794b7964.1ab012ee22c5de8a4876d5eb635d77bc75518039bbd06bbb64fb50d8a99b8a00.PlKEqZH86A6v2VdgsoBHd26kdxeq-ExQWNi-69TK2x8+ errortracking-sourcemapsexamplesbrowser--master-detail--light:+ hash: v1.k794b7964.1987a860ee18b09f7f5babf4b0066a4eb8fca2029a79c21406c4da81e9104776.UH50ypZckpPst0TqNoBOdIOMRGhW8DzYauNWbHPZzsg+ errortracking-sourcemapsexamplesbrowser--narrow--dark:+ hash: v1.k794b7964.f8c279eaf92924650536e08d59a2ea2eeb300dbefb9607f6abde246339b6ed5e.Hj6GSowOJBrQ2yYfxhTo_3QzBLcH48FrLb9D4558NkA+ errortracking-sourcemapsexamplesbrowser--narrow--light:+ hash: v1.k794b7964.189e9c8195afaacbe9591f33d4ae737cbee7a2c274005ff21a66d3338fe93d40.hdvzpBdEF6I9hgUQ1j_11p8X4QZeGxR85Dh4qtOnPmEerrortracking-stacktraceactions--default--dark:hash: v1.k794b7964.66675f9b97886c67caa1944ddebc31ea5efb020398be48d74bbc1bf09e6dcab0.h_iqU-qk8JaIXWcf4fo7OBrIK0IVvMaOTQ-2KIjoH3Aerrortracking-stacktraceactions--default--light:@@ -10767,17 +10775,17 @@ snapshots:scenes-app-errortracking--list-page-with-rate-limits-banner--light:hash: v1.k794b7964.5601fa6fc8daacb5c7bcee039783618bc412b4e9b99ac0e87b724ba74a1ca24b.4x2ftv3DN_y7bWtcrLCdxc_zN9m7q898vWL4JcEnyw0scenes-app-errortracking--list-page-with-source-maps-banner--dark:- hash: v1.k794b7964.5c1f7558f79a3d4c7d075ecd4fd84bf060917e13629c0df26fa133f64bfdfab8.65JnjJ09bh15yzqFjeUHEIxMBWGJ0Z8OfmBzFCQMsKM+ hash: v1.k794b7964.1823b525d027418baf8ea375e15ceb86995477e9bdf2f4990fe1374522f35903.LNES7vxmJs7gx2tbkL0TctzXeBZSSU-nzWNbUbuLW1Yscenes-app-errortracking--list-page-with-source-maps-banner--light:- hash: v1.k794b7964.b24ffe1fee7932dfaa60f7e33c45d47292175915d4d6808e8b14ad385c79a4ab.HmCwMfIGY7bB3-m_Qm7qMUMw6weAb3YaB0DsmG8g4jw+ hash: v1.k794b7964.27a4ad835a513637900e96e64c271bbd46bcb7633f4dd82bec88ffe7022a116d.k2nPX0wGeoUTgL2ZCQDLORRIz0P73JgIN9xwOW1l7asscenes-app-errortracking--list-page-with-source-maps-banner-narrow--dark:- hash: v1.k794b7964.594c92db07d283fa6cdfad3710b23bb31f4d727e989ed1d2d64becfaa1c53ac7.8492KCauUtFUeZ83WjkbgnqMon4RYSVqY9D6AMl9_0I+ hash: v1.k794b7964.f1deff7eb195f2398bad42ba55c44f5566f71127073022a479165686b562f1e2.fufB8tFZwAo0VXlQyvoo-ehvX8wIKaLHKs0v47t73eIscenes-app-errortracking--list-page-with-source-maps-banner-narrow--light:- hash: v1.k794b7964.3dd4b6c2de0c4c759995bfa537e9b67ca8923f21f94dd4fec9a948b3122d1746.eLWFdwl7u1yxFjaW-QcP-i8znZEURoh2qEuIm9dn4ko+ hash: v1.k794b7964.cd1bf57c562df57362df8bac8ff300b49ecfa4b7a32ac47f11abee48b5664d70.WFXRPMhIQXCYrSazhgNP5Cjstox8CR48z2h6QMw8_Qsscenes-app-errortracking--list-page-with-stacked-banners--dark:- hash: v1.k794b7964.aff3898ea14ab795c09e66d34c11e4b968fb1694d5825107ccc6d804636b09c5.FD3T-3N8kACVT6lTwvI6zI5uK5eFvorATmyyoPA8IjY+ hash: v1.k794b7964.502a216bbc9268301578d6cebf9f46d13d3a802734f4fd7bd2707bdf8f0c9911.kpruIOz8uQ8wg26EB5QjeBVvFyLZVQV9FI4UqZ4Egsgscenes-app-errortracking--list-page-with-stacked-banners--light:- hash: v1.k794b7964.c9b1b9e1cbd1f222b720bfa49136df00605cc402ac231399392643f72b17e0cf.py6UFtlSm-v_ev6kF1NcOlVo7nMjm6de2ulS61Fh_8U+ hash: v1.k794b7964.7f8d251eac06e80fcd07c83ecda7fd43de79caf8f2c6bfe47fad10ab5ae094eb.OgfZFV7i9PlPfw0x6u6BbDnZ6fzWxpn6M3moLNzCBd8scenes-app-errortracking-linkedreports--fix-proposed--dark:hash: v1.k794b7964.1b50022f8fafb4684dacd255b966bd2969f79e84d5c7c7daeb68291772a1e36d.9uyjrwufsjMCFx9c7cjsoIyabB3A4ZBnPSVUouM0RZEscenes-app-errortracking-linkedreports--fix-proposed--light:diff --git a/frontend/src/scenes/health/components/ErrorTrackingHealthTable.tsx b/frontend/src/scenes/health/components/ErrorTrackingHealthTable.tsxindex 2bc3b33e5b21..898a9d91a6b9 100644--- a/frontend/src/scenes/health/components/ErrorTrackingHealthTable.tsx+++ b/frontend/src/scenes/health/components/ErrorTrackingHealthTable.tsx@@ -7,16 +7,25 @@ import { issueActionsColumn, severityColumn } from './healthTableColumns'const SOURCE_MAPS_DOCS_URL = 'https://posthog.com/docs/error-tracking/upload-source-maps'+const SOURCE_MAPS_PLATFORM_LABELS: Record<string, { platform: string; symbols: string }> = {+ javascript: { platform: 'JavaScript', symbols: 'source maps' },+ java: { platform: 'Android', symbols: 'mapping files' },+ native: { platform: 'iOS and native', symbols: 'debug symbols' },+}+function missingSourceMapsDescription(issue: HealthIssue): string {- const { unresolved_pct, unresolved_frames, total_frames, lookback_hours } = issue.payload+ const { unresolved_pct, unresolved_frames, total_frames, lookback_hours, platform } = issue.payloadconst percent = Math.round((Number(unresolved_pct) || 0) * 100)const frames =unresolved_frames != null && total_frames != null? ` (${Number(unresolved_frames).toLocaleString()} of ${Number(total_frames).toLocaleString()})`: ''- return `${percent}% of JavaScript stack frames${frames} were unresolved in the last ${+ // Payloads written before per-platform scoring have no platform, and they counted JavaScript frames only.+ const labels =+ SOURCE_MAPS_PLATFORM_LABELS[String(platform ?? 'javascript')] ?? SOURCE_MAPS_PLATFORM_LABELS.javascript+ return `${percent}% of ${labels.platform} stack frames that need ${labels.symbols}${frames} were missing them in the last ${Number(lookback_hours) || 24- } hours. Unresolved frames also degrade issue grouping. Upload source maps so stack traces show your original source code and errors group correctly.`+ } hours. Unresolved frames also degrade issue grouping. Upload ${labels.symbols} so stack traces show your original source code and errors group correctly.`}export function ErrorTrackingHealthTable({diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 3572c535aaa6..cc97bdf1902f 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -696,6 +696,19 @@ class ErrorTrackingFingerprintProjectionSustainedRateThrottle(_TeamBucketRateThrrate = "100/hour"+# The source maps examples scan reads the properties of every exception in the last 24 hours, and+# browser sessions skip the default throttles. A team-wide bucket caps the project's total scans.+# Each open of the examples dialog runs one scan, so these rates leave room for normal use.+class ErrorTrackingSourceMapsExamplesBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "error_tracking_source_maps_examples_burst"+ rate = "10/minute"+++class ErrorTrackingSourceMapsExamplesSustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "error_tracking_source_maps_examples_sustained"+ rate = "100/hour"++# The logs anomaly scan aggregates weeks of baseline slices from ClickHouse in one synchronous# request — the heaviest single query the logs product exposes, budgeted at gigabytes of reads# per call. A team-wide bucket caps the project's total spend regardless of how many users ordiff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.pyindex 276e89028a12..f31687a4220e 100644--- a/products/error_tracking/backend/facade/contracts.py+++ b/products/error_tracking/backend/facade/contracts.py@@ -329,6 +329,83 @@ class ErrorTrackingRecommendation:updated_at: datetime+class SymbolsPlatform(LabeledStrEnum):+ JAVASCRIPT = "javascript", "JavaScript"+ JAVA = "java", "Android"+ NATIVE = "native", "iOS and native"+++class MissingSymbolsReason(LabeledStrEnum):+ CHUNK_NOT_UPLOADED = "chunk_not_uploaded", "Source map not uploaded"+ NO_SOURCE_MAP_LINKED = "no_source_map_linked", "Script links no source map"+ FILE_NOT_REACHABLE = "file_not_reachable", "Script or source map not reachable"+ INVALID_SOURCE_MAP = "invalid_source_map", "Source map URL returns something else"+ TOO_LARGE_TO_FETCH = "too_large_to_fetch", "Too large to fetch"+ BUNDLE_NOT_INJECTED = "bundle_not_injected", "Bundle not processed by the PostHog CLI"+ MAPPING_NOT_UPLOADED = "mapping_not_uploaded", "Mapping file not uploaded"+ DSYM_NOT_UPLOADED = "dsym_not_uploaded", "dSYM not uploaded"+ DEBUG_SYMBOLS_NOT_UPLOADED = "debug_symbols_not_uploaded", "Debug symbols not uploaded"+++@dataclass(frozen=True)+class MissingSymbolsIssue:+ """An issue whose recent exceptions contain frames from one missing-symbols example."""++ id: UUID+ name: str | None+ description: str | None+ occurrences: int+++@dataclass(frozen=True)+class MissingSymbolsStackFrame:+ function: str | None+ source: str | None+ line: int | None+ column: int | None+ in_app: bool+ missing_symbols: bool+++@dataclass(frozen=True)+class MissingSymbolsExampleException:+ # The issue page opens this event from the issue ID, the fingerprint and the timestamp.+ issue_id: UUID | None+ fingerprint: str+ timestamp: datetime+ type: str | None+ value: str | None+ # Most recent call first, the order the issue page shows.+ frames: list[MissingSymbolsStackFrame]+++@dataclass(frozen=True)+class MissingSymbolsExample:+ """Frames from one file or build that miss the same symbols, for the same reason."""++ reason: MissingSymbolsReason+ location: str | None+ symbol_id: str | None+ http_status: int | None+ frames: int+ # The issues with the most occurrences. `issue_count` counts them all.+ issues: list[MissingSymbolsIssue]+ issue_count: int+ # True when the scan searched only a sample of the frames or stopped at its fingerprint limit,+ # so `issue_count` is a lower bound.+ issue_count_capped: bool+ example_exception: MissingSymbolsExampleException | None+++@dataclass(frozen=True)+class MissingSymbolsExamples:+ platform: SymbolsPlatform+ lookback_hours: int+ # False when the exception lookup failed, so the issues and examples are unknown rather than absent.+ exceptions_loaded: bool+ results: list[MissingSymbolsExample]++@dataclass(frozen=True)class ErrorTrackingAlertDestination:id: UUIDdiff --git a/products/error_tracking/backend/facade/recommendations.py b/products/error_tracking/backend/facade/recommendations.pyindex 58e1388a368b..ed5e1c8b1ee4 100644--- a/products/error_tracking/backend/facade/recommendations.py+++ b/products/error_tracking/backend/facade/recommendations.py@@ -7,8 +7,11 @@ config-only consumers of the main facade.from uuid import UUID+from posthog.models.user import User+from ..logic.recommendations import (refresh as _refresh,+ source_maps_examples as _source_maps_examples,store as _store,)from . import contracts@@ -52,3 +55,9 @@ def dismiss_recommendation(team_id: int, recommendation_id: UUID) -> contracts.Edef restore_recommendation(team_id: int, recommendation_id: UUID) -> contracts.ErrorTrackingRecommendation:return _to_recommendation(_store.restore_recommendation(team_id, recommendation_id))+++def list_missing_symbols_examples(+ team_id: int, platform: contracts.SymbolsPlatform, *, user: User+) -> contracts.MissingSymbolsExamples:+ return _source_maps_examples.missing_symbols_examples(team_id, platform, user)diff --git a/products/error_tracking/backend/logic/recommendations/source_maps.py b/products/error_tracking/backend/logic/recommendations/source_maps.pyindex e9813c75064e..36a0871c7ed7 100644--- a/products/error_tracking/backend/logic/recommendations/source_maps.py+++ b/products/error_tracking/backend/logic/recommendations/source_maps.py@@ -1,66 +1,202 @@+import operator+import functools+import dataclassesfrom datetime import timedeltafrom typing import Any-from django.db.models import Count+from django.conf import settings+from django.db.models import Case, Count, Q, Value, Whenfrom django.utils import timezone+from posthog.dataclasses import frozen++from products.error_tracking.backend.facade.contracts import MissingSymbolsReasonfrom products.error_tracking.backend.models import ErrorTrackingStackFramefrom .base import Recommendation# Don't fire the recommendation unless we have a meaningful sample.# Tiny teams with a couple of errors shouldn't get a noisy card.-MIN_SAMPLE_FRAMES = 20+MIN_SAMPLE_FRAMES = 10-# Show the card when more than this fraction of recent JS/TS frames are unresolved.+# Flag a platform when more than this fraction of its recent frames that need symbols are missing them.UNRESOLVED_THRESHOLD = 0.30LOOKBACK_HOURS = 24+PLATFORM_LABELS: dict[str, tuple[str, str]] = {+ "javascript": ("JavaScript", "source maps"),+ "java": ("Android", "mapping files"),+ "native": ("iOS and native", "debug symbols"),+}++# Name this in READ_REPLICA_OPT_IN to run the frame counts on the read replica.+READ_REPLICA_OPT_IN_KEY = "error_tracking_source_maps"+++def _resolve_failure_starts_with(*prefixes: str) -> Q:+ condition = Q()+ for prefix in prefixes:+ condition |= Q(contents__resolve_failure__startswith=prefix)+ return condition+++@frozen+class _MissingSymbolsRule:+ reason: MissingSymbolsReason+ prefixes: tuple[str, ...]+ condition: Q = dataclasses.field(default_factory=Q)++ @property+ def query(self) -> Q:+ return _resolve_failure_starts_with(*self.prefixes) & self.condition+++# Each prefix matches the error text cymbal stores in `contents.resolve_failure` (the `Display`+# strings in rust/cymbal/src/core/error.rs), so a reworded error there silently drops out of this match.+# A JavaScript frame with no chunk ID still counts when we found no source map for it, because the+# CLI would inject a chunk ID into that file and upload its map. This also counts third-party+# scripts that will never have a source map, because a single frame cannot tell them apart.+MISSING_SYMBOLS_RULES: tuple[_MissingSymbolsRule, ...] = (+ # Cymbal looks up the chunk before it checks the column. A frame with no column has no position+ # to map, so an upload only passes it through unresolved.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.CHUNK_NOT_UPLOADED,+ prefixes=("No sourcemap uploaded for chunk id: ",),+ condition=Q(contents__has_key="column"),+ ),+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.NO_SOURCE_MAP_LINKED, prefixes=("Could not find sourcemap for source url: ",)+ ),+ # These 4xx codes are the server's final answer. A 400 or 407 is not: cymbal's egress proxy+ # answers 407 for localhost, and 400s come from third-party scripts.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.FILE_NOT_REACHABLE,+ prefixes=tuple(f"HTTP error {status} while fetching: " for status in (401, 403, 404, 410)),+ ),+ # A map that does not parse is most often a server that answers a missing `.map` with its HTML page.+ _MissingSymbolsRule(reason=MissingSymbolsReason.INVALID_SOURCE_MAP, prefixes=("Invalid source map: ",)),+ # The fetch limit is lower than the upload limit, so an upload resolves a file that is too big to fetch.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.TOO_LARGE_TO_FETCH,+ prefixes=("Network error while fetching: Response from ",),+ ),+ # A frame with no column has nothing to look up, `InternalBytecode.js` is the Hermes engine's own+ # code, and an http(s) source is a bundle from the Metro dev server.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.BUNDLE_NOT_INJECTED,+ prefixes=("No chunk id sent with frame",),+ condition=Q(contents__has_key="column")+ & ~Q(contents__source__endswith="InternalBytecode.js")+ & ~Q(contents__source__startswith="http://")+ & ~Q(contents__source__startswith="https://"),+ ),+ # Android framework classes live on the device, not in the app, so no uploaded mapping covers them.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.MAPPING_NOT_UPLOADED,+ prefixes=("No proguard map uploaded for id: ",),+ condition=~Q(+ contents__module__regex=r"^(android|java|javax|dalvik|libcore|sun|com\.android|org\.json|org\.xml|org\.w3c|org\.apache\.http)\."+ ),+ ),+ # System libraries miss debug symbols too, but nobody can upload those, and they are not in_app.+ # An Xcode `.debug.dylib` image is a dev build.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.DSYM_NOT_UPLOADED,+ prefixes=("No dSYM uploaded for debug_id: ",),+ condition=Q(contents__in_app=True)+ & (Q(contents__module__isnull=True) | ~Q(contents__module__endswith=".debug.dylib")),+ ),+ # A native frame with a line number is already readable, because the SDK resolved it on the client.+ _MissingSymbolsRule(+ reason=MissingSymbolsReason.DEBUG_SYMBOLS_NOT_UPLOADED,+ prefixes=("No debug symbols uploaded for debug_id: ",),+ condition=Q(contents__in_app=True) & ~Q(contents__has_key="line"),+ ),+)++MISSING_SYMBOLS = Q(resolved=False) & functools.reduce(operator.or_, (rule.query for rule in MISSING_SYMBOLS_RULES))++# Frames whose code needs symbols to be readable: the ones resolved with a symbol set, plus the ones+# missing it. Python frames and unminified JavaScript resolve without symbols, so they stay out. A+# resolved frame that kept a failure text resolved without symbols, even when it links to the failed set.+# A JavaScript frame that cymbal resolved through the URL fallback has no symbol set link, because+# cymbal stores that set under the URL and looks it up under the chunk ID. It has a column from the+# source map. A Node.js frame that cymbal passed through keeps its line but has no column, and a+# frame without location information has neither.+NEEDS_SYMBOLS = (+ Q(resolved=True)+ & ~Q(contents__has_key="resolve_failure")+ & (Q(symbol_set__isnull=False) | Q(contents__lang="javascript", contents__has_key="column"))+) | MISSING_SYMBOLS++# Each platform is scored on its own, so good coverage on one platform cannot hide missing symbols on another.+PLATFORM = Case(+ When(contents__lang="javascript", then=Value("javascript")),+ When(contents__lang="java", then=Value("java")),+ default=Value("native"),+)+++def frames_database() -> str:+ if READ_REPLICA_OPT_IN_KEY in settings.READ_REPLICA_OPT_IN and "replica" in settings.DATABASES:+ return "replica"+ return "default"+class SourceMapsRecommendation(Recommendation):type = "source_maps"refresh_interval = timedelta(hours=6)def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:- # `lang` is set on the resolved frame contents by cymbal — both browser JS- # and Node frames are tagged "javascript". TypeScript frames also surface- # as "javascript" pre-resolution; the source map is what would map them- # back to the original .ts source, so they're exactly the population we- # care about here.since = timezone.now() - timedelta(hours=LOOKBACK_HOURS)+ counts_by_team: dict[int, dict[str, dict[str, int]]] = {+ team_id: {platform: {"total": 0, "unresolved": 0} for platform in PLATFORM_LABELS} for team_id in team_ids+ }- # This aggregate must read no column outside et_frame_team_created_js_idx. A count over- # `id` pulls the heap row, which detoasts the wide `contents` column with it.+ # The rules read `contents`, so Postgres reads every frame of the window from the heap. No+ # covering index helps here: recent frames sit on pages that vacuum has not marked+ # all-visible yet, so an index-only scan fetches the heap for them anyway.rows = (- ErrorTrackingStackFrame.objects.filter(- team_id__in=team_ids,- created_at__gte=since,- contents__lang="javascript",- )- .values("team_id", "resolved")- .annotate(frames=Count("*"))+ ErrorTrackingStackFrame.objects.using(frames_database())+ .filter(NEEDS_SYMBOLS, team_id__in=team_ids, created_at__gte=since)+ .annotate(platform=PLATFORM)+ .values("team_id", "platform")+ .annotate(total=Count("id"), unresolved=Count("id", filter=Q(resolved=False))))-- counts_by_team: dict[int, dict[str, int]] = {}for row in rows:- counts = counts_by_team.setdefault(row["team_id"], {"total": 0, "unresolved": 0})- counts["total"] += row["frames"]- if not row["resolved"]:- counts["unresolved"] += row["frames"]+ counts_by_team[row["team_id"]][row["platform"]] = {"total": row["total"], "unresolved": row["unresolved"]}- return {team_id: self._build_meta(counts_by_team.get(team_id)) for team_id in team_ids}+ return {team_id: self._build_meta(counts_by_team[team_id]) for team_id in team_ids}@staticmethod- def _build_meta(counts: dict[str, Any] | None) -> dict[str, Any]:- total = (counts or {}).get("total") or 0- unresolved = (counts or {}).get("unresolved") or 0- unresolved_pct = (unresolved / total) if total > 0 else 0.0+ def _build_meta(counts_by_platform: dict[str, dict[str, int]]) -> dict[str, Any]:+ platforms = {+ platform: {+ "total_frames": counts["total"],+ "unresolved_frames": counts["unresolved"],+ "unresolved_pct": counts["unresolved"] / counts["total"] if counts["total"] else 0.0,+ }+ for platform, counts in counts_by_platform.items()+ }+ # The top-level counts are the worst platform with a meaningful sample, so `is_completed` and+ # every surface that shows one percentage report the platform that needs attention. With no+ # such platform, they fall back to the platform with the most frames.+ sampled = [platform for platform, stats in platforms.items() if stats["total_frames"] >= MIN_SAMPLE_FRAMES]+ with_frames = [platform for platform, stats in platforms.items() if stats["total_frames"]]+ worst = (+ max(sampled, key=lambda p: (platforms[p]["unresolved_pct"], platforms[p]["total_frames"]))+ if sampled+ else max(with_frames, key=lambda p: platforms[p]["total_frames"])+ if with_frames+ else None+ )+ top = platforms[worst] if worst else {"total_frames": 0, "unresolved_frames": 0, "unresolved_pct": 0.0}return {- "total_frames": total,- "unresolved_frames": unresolved,- "unresolved_pct": unresolved_pct,+ **top,+ "platform": worst,+ "platforms": platforms,"threshold_pct": UNRESOLVED_THRESHOLD,"min_sample_frames": MIN_SAMPLE_FRAMES,"lookback_hours": LOOKBACK_HOURS,diff --git a/products/error_tracking/backend/logic/recommendations/source_maps_examples.py b/products/error_tracking/backend/logic/recommendations/source_maps_examples.pynew file mode 100644index 000000000000..5f72be856e06--- /dev/null+++ b/products/error_tracking/backend/logic/recommendations/source_maps_examples.py@@ -0,0 +1,450 @@+import re+import json+from datetime import datetime, timedelta+from time import monotonic+from typing import Any+from uuid import UUID++from django.contrib.postgres.aggregates import ArrayAgg+from django.contrib.postgres.fields import ArrayField+from django.db.models import Count, Func, Max, TextField, Value+from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Cast, Concat+from django.utils import timezone++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import ClickHouseUser+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User++from products.access_control.backend.facade.api import (+ get_restricted_properties_with_group_type_index_for_team,+ split_restricted_property_names,+)+from products.error_tracking.backend.facade.contracts import (+ MissingSymbolsExample,+ MissingSymbolsExampleException,+ MissingSymbolsExamples,+ MissingSymbolsIssue,+ MissingSymbolsReason,+ MissingSymbolsStackFrame,+ SymbolsPlatform,+)+from products.error_tracking.backend.logic import split_stack_frame_raw_id+from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2, ErrorTrackingStackFrame++from .source_maps import LOOKBACK_HOURS, MISSING_SYMBOLS, MISSING_SYMBOLS_RULES, PLATFORM, frames_database++EXAMPLES_LIMIT = 10+# Ten examples of twenty frame IDs stay under ClickHouse's limit of 255 needles in one multi-search.+RAW_IDS_PER_EXAMPLE = 20+ISSUES_PER_EXAMPLE = 5+# Each example keeps at most this many fingerprints, so one busy file cannot push the others out.+FINGERPRINTS_PER_EXAMPLE = 100+FRAMES_PER_EXCEPTION = 30+EXCEPTIONS_QUERY_TIMEOUT_SECONDS = 15++_URL_PATTERN = re.compile(r"https?://[^\s)]+")+_HTTP_STATUS_PATTERN = re.compile(r"^HTTP error (\d{3}) ")+# The failure text of these reasons ends with the ID that the missing symbols must be uploaded under.+_REASONS_WITH_SYMBOL_ID = {+ MissingSymbolsReason.CHUNK_NOT_UPLOADED,+ MissingSymbolsReason.MAPPING_NOT_UPLOADED,+ MissingSymbolsReason.DSYM_NOT_UPLOADED,+ MissingSymbolsReason.DEBUG_SYMBOLS_NOT_UPLOADED,+}+++# nosemgrep: python.django.security.audit.extends-custom-expression.extends-custom-expression+class _FirstRawIds(Func):+ # Postgres still aggregates every frame ID, but only the first ones leave the database. The template+ # holds only a module constant, and the only expression is an aggregate of columns, so no input reaches the SQL.+ template = f"(%(expressions)s)[1:{RAW_IDS_PER_EXAMPLE}]"+ output_field = ArrayField(TextField())+++@frozen+class _ExampleKey:+ reason: MissingSymbolsReason+ location: str | None+ symbol_id: str | None+ http_status: int | None+++@frozen(frozen=False)+class _ExampleGroup:+ key: _ExampleKey+ frames: int+ # In the `hash/part` form that events use for frame IDs.+ raw_ids: list[str]+++@frozen+class _FingerprintMatch:+ example_index: int+ fingerprint: str+ occurrences: int+ event_uuid: UUID+ timestamp: datetime+++@frozen+class _Scan:+ matches: list[_FingerprintMatch]+ # True when ClickHouse stopped the scan at its time limit and returned the events it read until then.+ stopped_early: bool+++@frozen+class _ExampleIssues:+ top: list[MissingSymbolsIssue]+ count: int+ capped: bool+++@frozen+class _ParsedException:+ fingerprint: str+ timestamp: datetime+ type: str | None+ value: str | None+ # Stored order: the entry point first and the crash site last.+ frames: list[dict[str, Any]]+++def missing_symbols_examples(team_id: int, platform: SymbolsPlatform, user: User) -> MissingSymbolsExamples:+ """The files and builds with the most frames missing symbols on one platform, with the exceptions they appear in."""+ since = timezone.now() - timedelta(hours=LOOKBACK_HOURS)+ groups = _example_groups(team_id, platform, since)+ team = Team.objects.get(id=team_id)+ # Frames come from `$exception_list`. A user who cannot read it sees no paths or build IDs, and the+ # scans run as that user, so they would find no exceptions either.+ frames_hidden = _exception_list_restricted(team_id, user)++ try:+ scan = (+ _Scan(matches=[], stopped_early=False)+ if frames_hidden+ else _exceptions_containing(team, user, [group.raw_ids for group in groups], since)+ )+ representatives = _representatives(scan.matches)+ payloads = _exception_lists(team, user, list(representatives.values()))+ exceptions_loaded = True+ except Exception as error:+ # The examples stay useful without exceptions, so a failed scan only drops them.+ capture_exception(error)+ scan, representatives, payloads, exceptions_loaded = _Scan(matches=[], stopped_early=False), {}, {}, False+ matches = scan.matches++ issues = _issues_by_fingerprint(team_id, {match.fingerprint for match in matches})+ examples = [+ _parsed_example(group, representatives[index], payloads.get(representatives[index].event_uuid))+ if index in representatives+ else None+ for index, group in enumerate(groups)+ ]+ missing_raw_ids = _missing_raw_ids(+ team_id, [frame.get("raw_id") for example in examples if example for frame in example.frames]+ )++ results = []+ for index, (group, example) in enumerate(zip(groups, examples)):+ example_issues = _example_issues(+ index, matches, issues, scan_incomplete=scan.stopped_early or group.frames > len(group.raw_ids)+ )+ results.append(+ MissingSymbolsExample(+ reason=group.key.reason,+ location=None if frames_hidden else group.key.location,+ symbol_id=None if frames_hidden else group.key.symbol_id,+ http_status=group.key.http_status,+ frames=group.frames,+ issues=example_issues.top,+ issue_count=example_issues.count,+ issue_count_capped=example_issues.capped,+ example_exception=_example_exception(example, issues, missing_raw_ids) if example else None,+ )+ )+ return MissingSymbolsExamples(+ platform=platform, lookback_hours=LOOKBACK_HOURS, exceptions_loaded=exceptions_loaded, results=results+ )+++def _exception_list_restricted(team_id: int, user: User) -> bool:+ restrictions = get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team_id)+ return "$exception_list" in split_restricted_property_names(restrictions).event+++def _example_groups(team_id: int, platform: SymbolsPlatform, since: datetime) -> list[_ExampleGroup]:+ # A JavaScript failure names its script, so frames group per file. Android and native failures+ # name the build's mapping or debug ID, so frames group per build and the class or image is an example.+ location_field = "source" if platform == SymbolsPlatform.JAVASCRIPT else "module"+ group_by = ("failure", "location") if platform == SymbolsPlatform.JAVASCRIPT else ("failure",)+ frame_id = Concat("raw_id", Value("/"), Cast("part", TextField()), output_field=TextField())+ rows = (+ ErrorTrackingStackFrame.objects.using(frames_database())+ .filter(MISSING_SYMBOLS, team_id=team_id, created_at__gte=since)+ .alias(platform=PLATFORM)+ .filter(platform=platform.value)+ .annotate(+ failure=KeyTextTransform("resolve_failure", "contents"),+ location=KeyTextTransform(location_field, "contents"),+ )+ .values(*group_by)+ .annotate(+ frames=Count("id"),+ example_location=Max("location"),+ raw_ids=_FirstRawIds(ArrayAgg(frame_id, order_by="-created_at")),+ )+ .order_by("-frames")[: EXAMPLES_LIMIT * 5]+ )++ # Rows with different failure texts can name the same file, such as one script that failed to fetch+ # under several URLs, so merge them on what the user sees.+ groups: dict[_ExampleKey, _ExampleGroup] = {}+ for row in rows:+ failure: str = row["failure"]+ rule = next(rule for rule in MISSING_SYMBOLS_RULES if failure.startswith(rule.prefixes))+ prefix = next(prefix for prefix in rule.prefixes if failure.startswith(prefix))+ url = _URL_PATTERN.search(failure)+ status = _HTTP_STATUS_PATTERN.match(failure)+ key = _ExampleKey(+ reason=rule.reason,+ location=url.group(0) if url else row["example_location"],+ symbol_id=failure[len(prefix) :].strip() if rule.reason in _REASONS_WITH_SYMBOL_ID else None,+ http_status=int(status.group(1)) if status else None,+ )+ group = groups.setdefault(key, _ExampleGroup(key=key, frames=0, raw_ids=[]))+ group.frames += row["frames"]+ group.raw_ids = list(dict.fromkeys([*group.raw_ids, *row["raw_ids"]]))[:RAW_IDS_PER_EXAMPLE]++ return sorted(groups.values(), key=lambda group: -group.frames)[:EXAMPLES_LIMIT]+++def _exceptions_containing(team: Team, user: User, raw_ids_per_example: list[list[str]], since: datetime) -> _Scan:+ """Recent exceptions whose stack traces contain each example's frames, per example and fingerprint."""+ # The quotes make each needle match a whole JSON string, so `hash/1` cannot match `hash/10`.+ needles = [f'"{raw_id}"' for raw_ids in raw_ids_per_example for raw_id in raw_ids]+ needle_examples = [index for index, raw_ids in enumerate(raw_ids_per_example) for _ in raw_ids]+ if not needles:+ return _Scan(matches=[], stopped_early=False)++ started = monotonic()+ with tags_context(+ product=Product.ERROR_TRACKING, feature=Feature.QUERY, team_id=team.id, name="source_maps_examples"+ ):+ # Events keep no frame IDs outside `$exception_list`, so the scan reads each exception's properties.+ # It runs only when someone opens the examples, never in the hourly sweep.+ response = execute_hogql_query(+ query="""+ SELECT+ example_index,+ properties.$exception_fingerprint AS fingerprint,+ count() AS occurrences,+ argMax(uuid, timestamp) AS example_uuid,+ max(timestamp) AS last_seen+ FROM events+ ARRAY JOIN arrayDistinct(+ arrayFilter(+ (example, position) -> position > 0,+ {needle_examples},+ multiSearchAllPositions(properties, {needles})+ )+ ) AS example_index+ WHERE event = '$exception' AND timestamp >= {since}+ GROUP BY example_index, fingerprint+ ORDER BY occurrences DESC+ LIMIT {fingerprints_per_example} BY example_index+ LIMIT {max_rows}+ """,+ placeholders={+ "needles": ast.Constant(value=needles),+ "needle_examples": ast.Constant(value=needle_examples),+ "since": ast.Constant(value=since),+ "fingerprints_per_example": ast.Constant(value=FINGERPRINTS_PER_EXAMPLE),+ # Without a top-level limit, HogQL adds its default row limit and cuts off whole examples.+ "max_rows": ast.Constant(value=len(raw_ids_per_example) * FINGERPRINTS_PER_EXAMPLE),+ },+ team=team,+ user=user,+ ch_user=ClickHouseUser.ERROR_TRACKING,+ # A team with many exceptions can take longer than the limit. Stopping there still gives+ # examples, with counts that are lower bounds.+ settings=HogQLGlobalSettings(+ max_execution_time=EXCEPTIONS_QUERY_TIMEOUT_SECONDS, timeout_overflow_mode="break"+ ),+ )+ matches = [+ _FingerprintMatch(+ example_index=example_index,+ fingerprint=fingerprint,+ occurrences=occurrences,+ event_uuid=event_uuid,+ timestamp=timestamp,+ )+ for example_index, fingerprint, occurrences, event_uuid, timestamp in response.results or []+ if fingerprint+ ]+ # ClickHouse does not report a break, so a scan that ran to the limit counts as stopped early.+ return _Scan(matches=matches, stopped_early=monotonic() - started >= EXCEPTIONS_QUERY_TIMEOUT_SECONDS)+++def _representatives(matches: list[_FingerprintMatch]) -> dict[int, _FingerprintMatch]:+ """The latest event of each example's most frequent fingerprint."""+ representatives: dict[int, _FingerprintMatch] = {}+ for match in sorted(matches, key=lambda match: -match.occurrences):+ representatives.setdefault(match.example_index, match)+ return representatives+++def _exception_lists(team: Team, user: User, representatives: list[_FingerprintMatch]) -> dict[UUID, str]:+ if not representatives:+ return {}+ with tags_context(+ product=Product.ERROR_TRACKING, feature=Feature.QUERY, team_id=team.id, name="source_maps_examples"+ ):+ response = execute_hogql_query(+ query="""+ SELECT uuid, properties.$exception_list+ FROM events+ WHERE event = '$exception' AND timestamp >= {earliest} AND timestamp <= {latest} AND uuid IN {uuids}+ LIMIT {max_rows}+ """,+ placeholders={+ "earliest": ast.Constant(value=min(match.timestamp for match in representatives)),+ "latest": ast.Constant(value=max(match.timestamp for match in representatives)),+ "uuids": ast.Constant(value=[match.event_uuid for match in representatives]),+ "max_rows": ast.Constant(value=len(representatives)),+ },+ team=team,+ user=user,+ ch_user=ClickHouseUser.ERROR_TRACKING,+ settings=HogQLGlobalSettings(max_execution_time=EXCEPTIONS_QUERY_TIMEOUT_SECONDS),+ )+ return {event_uuid: exception_list for event_uuid, exception_list in response.results or [] if exception_list}+++def _issues_by_fingerprint(team_id: int, fingerprints: set[str]) -> dict[str, MissingSymbolsIssue]:+ rows = ErrorTrackingIssueFingerprintV2.objects.filter(team_id=team_id, fingerprint__in=fingerprints).values(+ "fingerprint", "issue_id", "issue__name", "issue__description"+ )+ return {+ row["fingerprint"]: MissingSymbolsIssue(+ id=row["issue_id"], name=row["issue__name"], description=row["issue__description"], occurrences=0+ )+ for row in rows+ }+++def _example_issues(+ example_index: int,+ matches: list[_FingerprintMatch],+ issues: dict[str, MissingSymbolsIssue],+ *,+ scan_incomplete: bool,+) -> _ExampleIssues:+ # Merged issues own several fingerprints, so their counts add up.+ occurrences: dict[UUID, int] = {}+ by_id: dict[UUID, MissingSymbolsIssue] = {}+ fingerprints = 0+ for match in matches:+ if match.example_index != example_index:+ continue+ fingerprints += 1+ issue = issues.get(match.fingerprint)+ if issue is None:+ continue+ occurrences[issue.id] = occurrences.get(issue.id, 0) + match.occurrences+ by_id[issue.id] = issue+ ranked = sorted(occurrences, key=lambda issue_id: -occurrences[issue_id])+ return _ExampleIssues(+ top=[+ MissingSymbolsIssue(+ id=issue_id,+ name=by_id[issue_id].name,+ description=by_id[issue_id].description,+ occurrences=occurrences[issue_id],+ )+ for issue_id in ranked[:ISSUES_PER_EXAMPLE]+ ],+ count=len(ranked),+ # The scan misses the issues of frames left out of the sample, of events past its time limit,+ # and of fingerprints past its row limit.+ capped=scan_incomplete or fingerprints >= FINGERPRINTS_PER_EXAMPLE,+ )+++def _parsed_example(+ group: _ExampleGroup, representative: _FingerprintMatch, exception_list: str | None+) -> _ParsedException | None:+ """The exception in the representative event that holds the example's frames."""+ if not exception_list:+ return None+ try:+ exceptions = json.loads(exception_list)+ except ValueError:+ return None+ if not isinstance(exceptions, list):+ return None+ raw_ids = set(group.raw_ids)+ for exception in exceptions:+ frames = ((exception or {}).get("stacktrace") or {}).get("frames") or []+ matching = [index for index, frame in enumerate(frames) if frame.get("raw_id") in raw_ids]+ if not matching:+ continue+ # Keep the frames nearest the crash site, unless that would drop every frame of the example.+ start = min(max(len(frames) - FRAMES_PER_EXCEPTION, 0), matching[-1])+ return _ParsedException(+ fingerprint=representative.fingerprint,+ timestamp=representative.timestamp,+ type=exception.get("type"),+ value=exception.get("value"),+ frames=frames[start : start + FRAMES_PER_EXCEPTION],+ )+ return None+++def _missing_raw_ids(team_id: int, raw_ids: list[str | None]) -> set[str]:+ """The `hash/part` frame IDs among these that an upload of symbols would resolve."""+ wanted = {raw_id for raw_id in raw_ids if raw_id}+ if not wanted:+ return set()+ rows = (+ ErrorTrackingStackFrame.objects.using(frames_database())+ .filter(+ MISSING_SYMBOLS,+ team_id=team_id,+ raw_id__in={split_stack_frame_raw_id(raw_id)[0] for raw_id in wanted},+ )+ .values_list("raw_id", "part")+ )+ return {f"{raw_id}/{part}" for raw_id, part in rows} & wanted+++def _example_exception(+ example: _ParsedException, issues: dict[str, MissingSymbolsIssue], missing_raw_ids: set[str]+) -> MissingSymbolsExampleException:+ issue = issues.get(example.fingerprint)+ return MissingSymbolsExampleException(+ issue_id=issue.id if issue else None,+ fingerprint=example.fingerprint,+ timestamp=example.timestamp,+ type=example.type,+ value=example.value,+ frames=[+ MissingSymbolsStackFrame(+ function=frame.get("resolved_name") or frame.get("mangled_name"),+ source=frame.get("source"),+ line=frame.get("line") if isinstance(frame.get("line"), int) else None,+ column=frame.get("column") if isinstance(frame.get("column"), int) else None,+ in_app=bool(frame.get("in_app")),+ missing_symbols=frame.get("raw_id") in missing_raw_ids,+ )+ for frame in reversed(example.frames)+ ],+ )diff --git a/products/error_tracking/backend/migrations/0044_remove_stackframe_js_frames_index.py b/products/error_tracking/backend/migrations/0044_remove_stackframe_js_frames_index.pynew file mode 100644index 000000000000..b86f17699a0a--- /dev/null+++ b/products/error_tracking/backend/migrations/0044_remove_stackframe_js_frames_index.py@@ -0,0 +1,18 @@+from django.db import migrations++from posthog.migration_helpers import SafeRemoveIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("error_tracking", "0043_errortrackingissue_active_created_idx"),+ ]++ operations = [+ SafeRemoveIndexConcurrently(+ model_name="errortrackingstackframe",+ name="et_frame_team_created_js_idx",+ ),+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex 71cf1a1636d7..155e0ecc9358 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0043_errortrackingissue_active_created_idx+0044_remove_stackframe_js_frames_indexdiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex de3fe92d9cec..2a0863f25df6 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -700,15 +700,6 @@ class ErrorTrackingStackFrame(UUIDTModel):# Recent-frames-per-team scans, such as the source maps recommendation. Without# created_at in the index, a 24h window has to visit every frame the team ever stored.models.Index(fields=["team", "created_at"], name="et_frame_team_created_at_idx"),- # Covers the source maps recommendation's count of recent JavaScript frames. The- # predicate holds the language test, so Postgres answers the count from the index- # and never detoasts the wide `contents` column.- models.Index(- fields=["team", "created_at"],- include=["resolved"],- condition=models.Q(contents__lang="javascript"),- name="et_frame_team_created_js_idx",- ),]constraints = [diff --git a/products/error_tracking/backend/presentation/views/recommendations.py b/products/error_tracking/backend/presentation/views/recommendations.pyindex bc0d4b98b8d2..27c961a82ae4 100644--- a/products/error_tracking/backend/presentation/views/recommendations.py+++ b/products/error_tracking/backend/presentation/views/recommendations.py@@ -1,14 +1,23 @@+from typing import cast+from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.user import User+from posthog.rate_limit import (+ ErrorTrackingSourceMapsExamplesBurstRateThrottle,+ ErrorTrackingSourceMapsExamplesSustainedRateThrottle,+)from products.error_tracking.backend.facade import recommendations as recommendations_facade+from products.error_tracking.backend.facade.contracts import MissingSymbolsReason, SymbolsPlatformclass ErrorTrackingRecommendationSerializer(serializers.Serializer):@@ -27,8 +36,100 @@ class ErrorTrackingRecommendationSerializer(serializers.Serializer):updated_at = serializers.DateTimeField(help_text="Timestamp the recommendation row was last updated.")+class MissingSymbolsExamplesQuerySerializer(serializers.Serializer):+ platform = serializers.ChoiceField(+ choices=SymbolsPlatform.choices,+ help_text="The platform to list examples for: 'javascript', 'java' (Android) or 'native' (iOS and native).",+ )+++class MissingSymbolsIssueSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="The issue ID.")+ name = serializers.CharField(allow_null=True, help_text="The issue name, usually the exception type.")+ description = serializers.CharField(allow_null=True, help_text="The issue description, usually the message.")+ occurrences = serializers.IntegerField(+ help_text="How many of the issue's exceptions in the lookback window contain these frames."+ )+++class MissingSymbolsStackFrameSerializer(serializers.Serializer):+ function = serializers.CharField(+ allow_null=True, help_text="The function name, resolved when symbols were available."+ )+ source = serializers.CharField( # type: ignore[assignment] # field named `source` shadows DRF Field.source+ allow_null=True, help_text="The file, script URL or module of the frame."+ )+ line = serializers.IntegerField(allow_null=True, help_text="The line number, when known.")+ column = serializers.IntegerField(allow_null=True, help_text="The column number, when known.")+ in_app = serializers.BooleanField(help_text="Whether the frame is the team's own code.")+ missing_symbols = serializers.BooleanField(help_text="Whether an upload of symbols would resolve this frame.")+++class MissingSymbolsExampleExceptionSerializer(serializers.Serializer):+ issue_id = serializers.UUIDField(+ allow_null=True, help_text="The issue the exception belongs to, or null when no issue owns its fingerprint."+ )+ fingerprint = serializers.CharField(help_text="The exception's fingerprint, which the issue page uses to find it.")+ timestamp = serializers.DateTimeField(help_text="When the exception happened.")+ type = serializers.CharField(allow_null=True, help_text="The exception type, such as TypeError.")+ value = serializers.CharField(allow_null=True, help_text="The exception message.")+ frames = MissingSymbolsStackFrameSerializer(+ many=True, help_text="The stack trace, most recent call first, cut to the frames nearest the crash."+ )+++class MissingSymbolsExampleSerializer(serializers.Serializer):+ reason = serializers.ChoiceField(+ choices=MissingSymbolsReason.choices,+ help_text="Why the frames miss symbols, as a code. Each code maps to one kind of setup gap.",+ )+ location = serializers.CharField(+ allow_null=True,+ help_text="Where the frames come from: the script URL or path, the bundle, or an example class or app image.",+ )+ symbol_id = serializers.CharField(+ allow_null=True,+ help_text="The chunk ID, mapping ID or debug ID that the missing symbols must be uploaded under, when known.",+ )+ http_status = serializers.IntegerField(+ allow_null=True, help_text="The HTTP status the script or source map returned, for 'file_not_reachable'."+ )+ frames = serializers.IntegerField(help_text="How many distinct stack frames in the lookback window this covers.")+ issues = MissingSymbolsIssueSerializer(+ many=True,+ help_text=(+ "Up to five issues whose exceptions in the lookback window contain these frames, most occurrences first."+ ),+ )+ issue_count = serializers.IntegerField(+ help_text="How many issues have exceptions in the lookback window that contain these frames."+ )+ issue_count_capped = serializers.BooleanField(+ help_text=(+ "True when the exception scan searched only a sample of the frames or stopped at its limit, "+ "so `issue_count` is a lower bound."+ )+ )+ example_exception = MissingSymbolsExampleExceptionSerializer(+ allow_null=True,+ help_text="A recent exception whose stack trace contains these frames, or null when none was found.",+ )+++class MissingSymbolsExamplesSerializer(serializers.Serializer):+ platform = serializers.ChoiceField(choices=SymbolsPlatform.choices, help_text="The platform the examples are for.")+ lookback_hours = serializers.IntegerField(help_text="How many hours of recent stack frames the examples cover.")+ exceptions_loaded = serializers.BooleanField(+ help_text="False when the exception lookup failed, so `issues` and `example_exception` are unknown, not empty."+ )+ results = MissingSymbolsExampleSerializer(+ many=True, help_text="The files and builds with the most frames missing symbols, most frames first."+ )++class ErrorTrackingRecommendationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "error_tracking"+ scope_object_read_actions = ["list", "retrieve", "source_maps_examples"]scope_object_write_actions = ["refresh", "dismiss", "restore"]serializer_class = ErrorTrackingRecommendationSerializer@@ -96,3 +197,28 @@ class ErrorTrackingRecommendationViewSet(TeamAndOrgViewSetMixin, viewsets.Generiexcept recommendations_facade.RecommendationNotFoundError:raise NotFound()return Response(self.get_serializer(recommendation).data, status=status.HTTP_200_OK)++ @validated_request(+ query_serializer=MissingSymbolsExamplesQuerySerializer,+ responses={200: OpenApiResponse(response=MissingSymbolsExamplesSerializer)},+ summary="List frames missing symbols",+ description=(+ "List the files and builds whose recent stack frames miss source maps, mapping files or debug "+ "symbols on one platform, with the reason and how many frames each covers."+ ),+ )+ @action(+ detail=False,+ methods=["get"],+ pagination_class=None,+ throttle_classes=[+ ErrorTrackingSourceMapsExamplesBurstRateThrottle,+ ErrorTrackingSourceMapsExamplesSustainedRateThrottle,+ ],+ )+ def source_maps_examples(self, request: ValidatedRequest, *args, **kwargs) -> Response:+ platform = SymbolsPlatform(request.validated_query_data["platform"])+ examples = recommendations_facade.list_missing_symbols_examples(+ self.team.id, platform, user=cast(User, request.user)+ )+ return Response(MissingSymbolsExamplesSerializer(examples).data)diff --git a/products/error_tracking/backend/temporal/health_checks/missing_source_maps.py b/products/error_tracking/backend/temporal/health_checks/missing_source_maps.pyindex fad852c1c6b3..aa8a848513bc 100644--- a/products/error_tracking/backend/temporal/health_checks/missing_source_maps.py+++ b/products/error_tracking/backend/temporal/health_checks/missing_source_maps.py@@ -5,7 +5,7 @@ from posthog.temporal.health_checks.detectors import HealthExecutionPolicyfrom posthog.temporal.health_checks.framework import AlertContent, HealthCheck, Remediationfrom posthog.temporal.health_checks.models import HealthCheckResult-from products.error_tracking.backend.logic.recommendations.source_maps import SourceMapsRecommendation+from products.error_tracking.backend.logic.recommendations.source_maps import PLATFORM_LABELS, SourceMapsRecommendationfrom products.error_tracking.backend.models import ErrorTrackingRecommendationRECOMMENDATIONS_PATH = "/error-tracking?activeTab=recommendations"@@ -15,7 +15,7 @@ WIZARD_COMMAND = "npx -y @posthog/wizard@latest upload-source-maps"class MissingSourceMapsCheck(HealthCheck):- """Flags teams whose JavaScript stack traces are mostly unresolved for lack of source maps.+ """Flags teams whose stack frames on any one platform mostly miss the symbols they need.Reads the persisted `source_maps` recommendation rows rather than recomputing, so theHealth page and the error tracking recommendations tab can never disagree — clicking@@ -46,12 +46,16 @@ class MissingSourceMapsCheck(HealthCheck):def render_alert(cls, issue: HealthIssue) -> AlertContent:pct = round((issue.payload.get("unresolved_pct") or 0) * 100)lookback_hours = issue.payload.get("lookback_hours") or 24+ # Payloads written before per-platform scoring counted JavaScript frames only.+ platform, symbols = PLATFORM_LABELS.get(+ issue.payload.get("platform") or "javascript", PLATFORM_LABELS["javascript"]+ )return AlertContent(title="Missing source maps",summary=(- f"{pct}% of JavaScript stack frames were unresolved in the last {lookback_hours} hours. "- "Unresolved frames also degrade issue grouping. Upload source maps so stack traces "- "show your original source code and errors group correctly."+ f"{pct}% of {platform} stack frames that need {symbols} were missing them in the last "+ f"{lookback_hours} hours. Unresolved frames also degrade issue grouping. Upload {symbols} so "+ "stack traces show your original source code and errors group correctly."),link=RECOMMENDATIONS_PATH,)diff --git a/products/error_tracking/backend/tests/api/test_recommendations.py b/products/error_tracking/backend/tests/api/test_recommendations.pyindex 023b1651bc09..4df48fa9f215 100644--- a/products/error_tracking/backend/tests/api/test_recommendations.py+++ b/products/error_tracking/backend/tests/api/test_recommendations.py@@ -2,21 +2,30 @@ from datetime import timedeltafrom uuid import uuid4import time_machine-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeature+from posthog.models import PropertyDefinition, Team++from products.access_control.backend.facade.api import upsert_property_access_control+from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInputfrom products.cdp.backend.facade.models import HogFunctionfrom products.error_tracking.backend.logic.recommendations.alerts import AlertsRecommendationfrom products.error_tracking.backend.logic.recommendations.rate_limits import RateLimitsRecommendationfrom products.error_tracking.backend.logic.recommendations.source_maps import SourceMapsRecommendationfrom products.error_tracking.backend.models import (+ ErrorTrackingIssue,+ ErrorTrackingIssueFingerprintV2,ErrorTrackingRecommendation,ErrorTrackingSettings,ErrorTrackingStackFrame,+ ErrorTrackingSymbolSet,)MOCK_ALERTS_META = {@@ -36,7 +45,42 @@ MOCK_ALERTS_META_UPDATED = {MOCK_SOURCE_MAPS_META = {"total_frames": 0, "unresolved_frames": 0, "unresolved_pct": 0.0}-class TestRecommendationsAPI(APIBaseTest):+class _StackFrameFactory:+ team: Team++ def _make_frame(+ self,+ contents: dict | None = None,+ resolved: bool = False,+ with_symbol_set: bool = False,+ created_hours_ago: int = 1,+ team: Team | None = None,+ ) -> ErrorTrackingStackFrame:+ team = team or self.team+ symbol_set = (+ ErrorTrackingSymbolSet.objects.create(team=team, ref=str(uuid4()), storage_ptr=str(uuid4()))+ if with_symbol_set+ else None+ )+ frame = ErrorTrackingStackFrame.objects.create(+ team=team,+ raw_id=str(uuid4()),+ contents={"lang": "javascript", **(contents or {})},+ resolved=resolved,+ symbol_set=symbol_set,+ )+ ErrorTrackingStackFrame.objects.filter(id=frame.id).update(+ created_at=timezone.now() - timedelta(hours=created_hours_ago)+ )+ return frame++ def _make_missing_symbols_frame(self, **kwargs) -> ErrorTrackingStackFrame:+ return self._make_frame(+ contents={"resolve_failure": "No sourcemap uploaded for chunk id: 0f1e2d", "column": 4321}, **kwargs+ )+++class TestRecommendationsAPI(_StackFrameFactory, APIBaseTest):def _list(self):return self.client.get(f"/api/environments/{self.team.id}/error_tracking/recommendations/")@@ -260,18 +304,6 @@ class TestRecommendationsAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_alerts.assert_not_called()- def _make_frame(self, lang: str, resolved: bool, created_hours_ago: int = 1) -> ErrorTrackingStackFrame:- frame = ErrorTrackingStackFrame.objects.create(- team=self.team,- raw_id=str(uuid4()),- contents={"lang": lang},- resolved=resolved,- )- ErrorTrackingStackFrame.objects.filter(id=frame.id).update(- created_at=timezone.now() - timedelta(hours=created_hours_ago)- )- return frame-def test_source_maps_compute_with_no_frames(self):meta = SourceMapsRecommendation().compute(self.team)@@ -279,31 +311,198 @@ class TestRecommendationsAPI(APIBaseTest):self.assertEqual(meta["unresolved_frames"], 0)self.assertEqual(meta["unresolved_pct"], 0.0)- def test_source_maps_compute_counts_unresolved_js_frames(self):+ def test_source_maps_compute_counts_frames_missing_symbols_among_frames_that_need_them(self):for _ in range(8):- self._make_frame(lang="javascript", resolved=True)+ self._make_frame(resolved=True, with_symbol_set=True)for _ in range(2):- self._make_frame(lang="javascript", resolved=False)+ self._make_missing_symbols_frame()+ self._make_frame(contents={"line": 12, "column": 4321}, resolved=True)+ self._make_frame(contents={"lang": "python"}, resolved=True)+ self._make_frame(contents={"line": 12}, resolved=True)+ self._make_frame(resolved=True)+ self._make_frame(+ contents={"resolve_failure": "Could not find sourcemap for source url: https://example.com/app.js"},+ resolved=True,+ with_symbol_set=True,+ )meta = SourceMapsRecommendation().compute(self.team)- self.assertEqual(meta["total_frames"], 10)+ self.assertEqual(meta["platform"], "javascript")+ self.assertEqual(meta["total_frames"], 11)self.assertEqual(meta["unresolved_frames"], 2)- self.assertEqual(meta["unresolved_pct"], 0.2)-- def test_source_maps_compute_ignores_non_js_frames(self):- self._make_frame(lang="python", resolved=False)- self._make_frame(lang="ruby", resolved=False)- self._make_frame(lang="javascript", resolved=True)+ self.assertEqual(meta["unresolved_pct"], 2 / 11)++ @parameterized.expand(+ [+ (+ "chunk_id_without_upload",+ {"resolve_failure": "No sourcemap uploaded for chunk id: 0f1e2d", "column": 4321},+ True,+ ),+ (+ "script_without_source_map",+ {"resolve_failure": "Could not find sourcemap for source url: https://example.com/app.js"},+ True,+ ),+ (+ "source_map_not_found",+ {"resolve_failure": "HTTP error 404 while fetching: https://example.com/app.js.map"},+ True,+ ),+ (+ "source_map_url_serves_html",+ {"resolve_failure": "Invalid source map: expected value at line 1 column 1"},+ True,+ ),+ (+ "source_map_over_fetch_limit",+ {+ "resolve_failure": "Network error while fetching: Response from https://example.com/app.js.map exceeded the 25000000 byte limit"+ },+ True,+ ),+ (+ "hermes_bundle_without_chunk_id",+ {"resolve_failure": "No chunk id sent with frame", "column": 1234, "source": "index.android.bundle"},+ True,+ ),+ (+ "proguard_map_missing",+ {"lang": "java", "module": "a.b.c", "resolve_failure": "No proguard map uploaded for id: 5d2c"},+ True,+ ),+ (+ "dsym_missing_for_app_code",+ {+ "lang": "swift",+ "in_app": True,+ "module": "Example",+ "resolve_failure": "No dSYM uploaded for debug_id: 8a9b-11",+ },+ True,+ ),+ (+ "dsym_missing_for_frame_without_module",+ {"lang": "swift", "in_app": True, "resolve_failure": "No dSYM uploaded for debug_id: 8a9b-11"},+ True,+ ),+ (+ "debug_symbols_missing_for_app_code",+ {"lang": "rust", "in_app": True, "resolve_failure": "No debug symbols uploaded for debug_id: 8a9b-11"},+ True,+ ),+ (+ "private_ip_address",+ {"resolve_failure": "Refusing to fetch from non-public address: http://127.0.0.1:5173/app.js"},+ False,+ ),+ (+ "localhost_unreachable",+ {+ "resolve_failure": "Network error while fetching: error sending request for url (http://localhost:3000/app.js)"+ },+ False,+ ),+ ("timeout", {"resolve_failure": "Request timed out while fetching: https://example.com/app.js"}, False),+ ("server_error", {"resolve_failure": "HTTP error 503 while fetching: https://example.com/app.js"}, False),+ ("rate_limited", {"resolve_failure": "HTTP error 429 while fetching: https://example.com/app.js"}, False),+ (+ "localhost_refused_by_egress_proxy",+ {"resolve_failure": "HTTP error 407 while fetching: http://localhost:3000/app.js"},+ False,+ ),+ ("bad_request", {"resolve_failure": "HTTP error 400 while fetching: https://example.com/gtm.js"}, False),+ ("unparseable_source_map_url", {"resolve_failure": "Invalid source url: https://[bad"}, False),+ ("source_map_without_token", {"resolve_failure": "Token not found for frame: a:1:5021"}, False),+ (+ "hermes_internal_bytecode",+ {"resolve_failure": "No chunk id sent with frame", "column": 12, "source": "InternalBytecode.js"},+ False,+ ),+ (+ "hermes_frame_without_column",+ {"resolve_failure": "No chunk id sent with frame", "source": "native"},+ False,+ ),+ (+ "chunk_id_without_upload_or_column",+ {"resolve_failure": "No sourcemap uploaded for chunk id: 0f1e2d", "source": "index.android.bundle"},+ False,+ ),+ (+ "hermes_metro_dev_server_bundle",+ {+ "resolve_failure": "No chunk id sent with frame",+ "column": 17,+ "source": "http://localhost:8081/index.bundle?platform=ios&dev=true",+ },+ False,+ ),+ (+ "android_framework_class",+ {+ "lang": "java",+ "module": "android.os.Handler",+ "resolve_failure": "No proguard map uploaded for id: 5d2c",+ },+ False,+ ),+ (+ "dsym_missing_for_system_framework",+ {"lang": "swift", "in_app": False, "resolve_failure": "No dSYM uploaded for debug_id: 8a9b-11"},+ False,+ ),+ (+ "dsym_missing_for_xcode_debug_build",+ {+ "lang": "swift",+ "in_app": True,+ "module": "Example.debug.dylib",+ "resolve_failure": "No dSYM uploaded for debug_id: 8a9b-11",+ },+ False,+ ),+ (+ "native_frame_already_readable",+ {+ "lang": "go",+ "in_app": True,+ "line": 42,+ "resolved_name": "main.handler",+ "resolve_failure": "No debug symbols uploaded for debug_id: 8a9b-11",+ },+ False,+ ),+ ]+ )+ def test_source_maps_compute_counts_only_failures_an_upload_fixes(self, _name, contents, counted):+ self._make_frame(contents=contents)meta = SourceMapsRecommendation().compute(self.team)- self.assertEqual(meta["total_frames"], 1)- self.assertEqual(meta["unresolved_frames"], 0)+ self.assertEqual(meta["unresolved_frames"], 1 if counted else 0)+ self.assertEqual(meta["total_frames"], 1 if counted else 0)++ def test_source_maps_compute_scores_each_platform_on_its_own(self):+ for _ in range(100):+ self._make_frame(contents={"lang": "java"}, resolved=True, with_symbol_set=True)+ for _ in range(25):+ self._make_missing_symbols_frame()+ for _ in range(5):+ self._make_frame(resolved=True, with_symbol_set=True)++ recommendation = SourceMapsRecommendation()+ meta = recommendation.compute(self.team)++ self.assertEqual(meta["platform"], "javascript")+ self.assertEqual((meta["total_frames"], meta["unresolved_frames"]), (30, 25))+ self.assertEqual(meta["platforms"]["java"]["total_frames"], 100)+ self.assertFalse(recommendation.is_completed(meta))def test_source_maps_compute_ignores_frames_outside_lookback(self):- self._make_frame(lang="javascript", resolved=False, created_hours_ago=48)- self._make_frame(lang="javascript", resolved=True, created_hours_ago=1)+ self._make_missing_symbols_frame(created_hours_ago=48)+ self._make_frame(resolved=True, with_symbol_set=True, created_hours_ago=1)meta = SourceMapsRecommendation().compute(self.team)@@ -311,13 +510,7 @@ class TestRecommendationsAPI(APIBaseTest):self.assertEqual(meta["unresolved_frames"], 0)def test_source_maps_compute_ignores_other_teams_frames(self):- other_team = self.organization.teams.create(name="other")- ErrorTrackingStackFrame.objects.create(- team=other_team,- raw_id=str(uuid4()),- contents={"lang": "javascript"},- resolved=False,- )+ self._make_missing_symbols_frame(team=self.organization.teams.create(name="other"))meta = SourceMapsRecommendation().compute(self.team)@@ -378,3 +571,208 @@ class TestRecommendationsAPI(APIBaseTest):source_maps.refresh_from_db()self.assertEqual(source_maps.status, ErrorTrackingRecommendation.Status.READY)mock_source_maps.assert_called_once()+++CHUNK_NOT_UPLOADED = "No sourcemap uploaded for chunk id: 0f1e2d"+NOT_FOUND = (+ "HTTP error 404 while fetching: HTTP status client error (404 Not Found) for url (https://example.com/app.js.map)"+)+++class TestSourceMapsExamplesAPI(_StackFrameFactory, ClickhouseTestMixin, APIBaseTest):+ def _issue(self, description: str, fingerprint: str) -> ErrorTrackingIssue:+ issue = ErrorTrackingIssue.objects.create(team=self.team, name="TypeError", description=description)+ ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=issue, fingerprint=fingerprint)+ return issue++ def _exception(self, fingerprint: str, value: str, frames: list[ErrorTrackingStackFrame]) -> None:+ _create_event(+ event="$exception",+ team=self.team,+ distinct_id="user",+ properties={+ "$exception_fingerprint": fingerprint,+ "$exception_list": [+ {+ "type": "TypeError",+ "value": value,+ "stacktrace": {+ "type": "resolved",+ "frames": [+ {"raw_id": f"{frame.raw_id}/{frame.part}", "resolved": frame.resolved, **frame.contents}+ for frame in frames+ ],+ },+ }+ ],+ },+ )++ @time_machine.travel("2026-10-20T12:00:00Z", tick=False)+ def test_source_maps_examples_group_missing_frames_with_the_exceptions_they_appear_in(self):+ chunk_contents = {+ "resolve_failure": CHUNK_NOT_UPLOADED,+ "source": "/assets/app.js",+ "mangled_name": "e",+ "line": 1,+ "column": 4321,+ "in_app": True,+ }+ # The examples search the 20 newest frames of each file, so the frame in the exceptions is the newest.+ crash_frame = self._make_frame(contents=chunk_contents)+ for _ in range(20):+ self._make_frame(contents=chunk_contents, created_hours_ago=2)+ not_found_frames = [+ self._make_frame(contents={"resolve_failure": NOT_FOUND, "source": "/app.js"}) for _ in range(2)+ ]+ entry = self._make_frame(+ contents={"source": "src/main.ts", "resolved_name": "main", "line": 3, "in_app": True},+ resolved=True,+ with_symbol_set=True,+ )+ self._make_frame(contents={"resolve_failure": "Request timed out while fetching: https://example.com/b.js"})+ for module in ("a.b", "a.c"):+ self._make_frame(+ contents={"lang": "java", "module": module, "resolve_failure": "No proguard map uploaded for id: 5d2c"}+ )+ type_error = self._issue("Cannot read properties of undefined", "fp-type-error")+ fetch_error = self._issue("Failed to fetch", "fp-fetch-error")+ for _ in range(2):+ self._exception("fp-type-error", "Cannot read properties of undefined", [entry, crash_frame])+ self._exception("fp-fetch-error", "Failed to fetch", [not_found_frames[0]])+ self._exception("fp-unrelated", "Unrelated", [entry])++ base = f"/api/environments/{self.team.id}/error_tracking/recommendations/source_maps_examples/"+ # A default row limit of 1 fails the test when a query relies on HogQL's default limit.+ with patch("posthog.hogql.constants.DEFAULT_RETURNED_ROWS", 1):+ javascript = self.client.get(f"{base}?platform=javascript")+ java = self.client.get(f"{base}?platform=java")++ self.assertEqual(javascript.status_code, status.HTTP_200_OK)+ self.assertEqual(+ javascript.json(),+ {+ "platform": "javascript",+ "lookback_hours": 24,+ "exceptions_loaded": True,+ "results": [+ {+ "reason": "chunk_not_uploaded",+ "location": "/assets/app.js",+ "symbol_id": "0f1e2d",+ "http_status": None,+ "frames": 21,+ "issues": [+ {+ "id": str(type_error.id),+ "name": "TypeError",+ "description": "Cannot read properties of undefined",+ "occurrences": 2,+ }+ ],+ "issue_count": 1,+ "issue_count_capped": True,+ "example_exception": {+ "issue_id": str(type_error.id),+ "fingerprint": "fp-type-error",+ "timestamp": "2026-10-20T12:00:00Z",+ "type": "TypeError",+ "value": "Cannot read properties of undefined",+ "frames": [+ {+ "function": "e",+ "source": "/assets/app.js",+ "line": 1,+ "column": 4321,+ "in_app": True,+ "missing_symbols": True,+ },+ {+ "function": "main",+ "source": "src/main.ts",+ "line": 3,+ "column": None,+ "in_app": True,+ "missing_symbols": False,+ },+ ],+ },+ },+ {+ "reason": "file_not_reachable",+ "location": "https://example.com/app.js.map",+ "symbol_id": None,+ "http_status": 404,+ "frames": 2,+ "issues": [+ {+ "id": str(fetch_error.id),+ "name": "TypeError",+ "description": "Failed to fetch",+ "occurrences": 1,+ }+ ],+ "issue_count": 1,+ "issue_count_capped": False,+ "example_exception": {+ "issue_id": str(fetch_error.id),+ "fingerprint": "fp-fetch-error",+ "timestamp": "2026-10-20T12:00:00Z",+ "type": "TypeError",+ "value": "Failed to fetch",+ "frames": [+ {+ "function": None,+ "source": "/app.js",+ "line": None,+ "column": None,+ "in_app": False,+ "missing_symbols": True,+ }+ ],+ },+ },+ ],+ },+ )+ self.assertEqual(+ [(r["reason"], r["symbol_id"], r["frames"], r["issues"]) for r in java.json()["results"]],+ [("mapping_not_uploaded", "5d2c", 2, [])],+ )++ def test_source_maps_examples_hide_exceptions_from_a_user_who_cannot_read_the_exception_list(self):+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ exception_list = PropertyDefinition.objects.create(+ team=self.team, name="$exception_list", type=PropertyDefinition.Type.EVENT+ )+ upsert_property_access_control(+ team_id=self.team.id,+ created_by_id=self.user.id,+ input=UpsertPropertyAccessControlInput(+ access_level=PropertyAccessLevel.NONE,+ property_definition_id=str(exception_list.id),+ organization_member_id=self.organization_membership.id,+ ),+ )+ frame = self._make_frame(+ contents={"resolve_failure": CHUNK_NOT_UPLOADED, "source": "/assets/app.js", "column": 4321}+ )+ self._issue("Cannot read properties of undefined", "fp-type-error")+ self._exception("fp-type-error", "Cannot read properties of undefined", [frame])+ flush_persons_and_events()++ response = self.client.get(+ f"/api/environments/{self.team.id}/error_tracking/recommendations/source_maps_examples/?platform=javascript"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [+ (r["frames"], r["location"], r["symbol_id"], r["issues"], r["issue_count"], r["example_exception"])+ for r in response.json()["results"]+ ],+ [(1, None, None, [], 0, None)],+ )diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex e93707b0ab0b..9e456e74f1c7 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -1810,6 +1810,167 @@ export interface PaginatedErrorTrackingRecommendationListApi {results: ErrorTrackingRecommendationApi[]}+/**+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native+ */+export type SymbolsPlatformEnumApi = (typeof SymbolsPlatformEnumApi)[keyof typeof SymbolsPlatformEnumApi]++export const SymbolsPlatformEnumApi = {+ Javascript: 'javascript',+ Java: 'java',+ Native: 'native',+} as const++/**+ * * `chunk_not_uploaded` - Source map not uploaded+ * * `no_source_map_linked` - Script links no source map+ * * `file_not_reachable` - Script or source map not reachable+ * * `invalid_source_map` - Source map URL returns something else+ * * `too_large_to_fetch` - Too large to fetch+ * * `bundle_not_injected` - Bundle not processed by the PostHog CLI+ * * `mapping_not_uploaded` - Mapping file not uploaded+ * * `dsym_not_uploaded` - dSYM not uploaded+ * * `debug_symbols_not_uploaded` - Debug symbols not uploaded+ */+export type MissingSymbolsReasonEnumApi = (typeof MissingSymbolsReasonEnumApi)[keyof typeof MissingSymbolsReasonEnumApi]++export const MissingSymbolsReasonEnumApi = {+ ChunkNotUploaded: 'chunk_not_uploaded',+ NoSourceMapLinked: 'no_source_map_linked',+ FileNotReachable: 'file_not_reachable',+ InvalidSourceMap: 'invalid_source_map',+ TooLargeToFetch: 'too_large_to_fetch',+ BundleNotInjected: 'bundle_not_injected',+ MappingNotUploaded: 'mapping_not_uploaded',+ DsymNotUploaded: 'dsym_not_uploaded',+ DebugSymbolsNotUploaded: 'debug_symbols_not_uploaded',+} as const++export interface MissingSymbolsIssueApi {+ /** The issue ID. */+ id: string+ /**+ * The issue name, usually the exception type.+ * @nullable+ */+ name: string | null+ /**+ * The issue description, usually the message.+ * @nullable+ */+ description: string | null+ /** How many of the issue's exceptions in the lookback window contain these frames. */+ occurrences: number+}++export interface MissingSymbolsStackFrameApi {+ /**+ * The function name, resolved when symbols were available.+ * @nullable+ */+ function: string | null+ /**+ * The file, script URL or module of the frame.+ * @nullable+ */+ source: string | null+ /**+ * The line number, when known.+ * @nullable+ */+ line: number | null+ /**+ * The column number, when known.+ * @nullable+ */+ column: number | null+ /** Whether the frame is the team's own code. */+ in_app: boolean+ /** Whether an upload of symbols would resolve this frame. */+ missing_symbols: boolean+}++export interface MissingSymbolsExampleExceptionApi {+ /**+ * The issue the exception belongs to, or null when no issue owns its fingerprint.+ * @nullable+ */+ issue_id: string | null+ /** The exception's fingerprint, which the issue page uses to find it. */+ fingerprint: string+ /** When the exception happened. */+ timestamp: string+ /**+ * The exception type, such as TypeError.+ * @nullable+ */+ type: string | null+ /**+ * The exception message.+ * @nullable+ */+ value: string | null+ /** The stack trace, most recent call first, cut to the frames nearest the crash. */+ frames: MissingSymbolsStackFrameApi[]+}++export interface MissingSymbolsExampleApi {+ /** Why the frames miss symbols, as a code. Each code maps to one kind of setup gap.+ *+ * * `chunk_not_uploaded` - Source map not uploaded+ * * `no_source_map_linked` - Script links no source map+ * * `file_not_reachable` - Script or source map not reachable+ * * `invalid_source_map` - Source map URL returns something else+ * * `too_large_to_fetch` - Too large to fetch+ * * `bundle_not_injected` - Bundle not processed by the PostHog CLI+ * * `mapping_not_uploaded` - Mapping file not uploaded+ * * `dsym_not_uploaded` - dSYM not uploaded+ * * `debug_symbols_not_uploaded` - Debug symbols not uploaded */+ reason: MissingSymbolsReasonEnumApi+ /**+ * Where the frames come from: the script URL or path, the bundle, or an example class or app image.+ * @nullable+ */+ location: string | null+ /**+ * The chunk ID, mapping ID or debug ID that the missing symbols must be uploaded under, when known.+ * @nullable+ */+ symbol_id: string | null+ /**+ * The HTTP status the script or source map returned, for 'file_not_reachable'.+ * @nullable+ */+ http_status: number | null+ /** How many distinct stack frames in the lookback window this covers. */+ frames: number+ /** Up to five issues whose exceptions in the lookback window contain these frames, most occurrences first. */+ issues: MissingSymbolsIssueApi[]+ /** How many issues have exceptions in the lookback window that contain these frames. */+ issue_count: number+ /** True when the exception scan searched only a sample of the frames or stopped at its limit, so `issue_count` is a lower bound. */+ issue_count_capped: boolean+ /** A recent exception whose stack trace contains these frames, or null when none was found. */+ example_exception: MissingSymbolsExampleExceptionApi | null+}++export interface MissingSymbolsExamplesApi {+ /** The platform the examples are for.+ *+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native */+ platform: SymbolsPlatformEnumApi+ /** How many hours of recent stack frames the examples cover. */+ lookback_hours: number+ /** False when the exception lookup failed, so `issues` and `example_exception` are unknown, not empty. */+ exceptions_loaded: boolean+ /** The files and builds with the most frames missing symbols, most frames first. */+ results: MissingSymbolsExampleApi[]+}+/*** @nullable*/@@ -2565,6 +2726,27 @@ export type ErrorTrackingRecommendationsRefreshCreateParams = {force?: boolean}+export type ErrorTrackingRecommendationsSourceMapsExamplesRetrieveParams = {+ /**+ * The platform to list examples for: 'javascript', 'java' (Android) or 'native' (iOS and native).+ *+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native+ * @minLength 1+ */+ platform: ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform+}++export type ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform =+ (typeof ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform)[keyof typeof ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform]++export const ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform = {+ Javascript: 'javascript',+ Java: 'java',+ Native: 'native',+} as const+export type ErrorTrackingReleasesListParams = {/*** Number of results to return per page.diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex 455f063aa85b..3f70f0d08b6b 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -60,6 +60,7 @@ import type {ErrorTrackingRecommendationApi,ErrorTrackingRecommendationsListParams,ErrorTrackingRecommendationsRefreshCreateParams,+ ErrorTrackingRecommendationsSourceMapsExamplesRetrieveParams,ErrorTrackingReleaseApi,ErrorTrackingReleaseCreateRequestApi,ErrorTrackingReleaseUpdateRequestApi,@@ -89,6 +90,7 @@ import type {ErrorTrackingSymbolSetFinishUploadApi,ErrorTrackingSymbolSetsListParams,GitProviderFileLinkResolveResponseApi,+ MissingSymbolsExamplesApi,PaginatedErrorTrackingAlertListApi,PaginatedErrorTrackingAssignmentRuleListApi,PaginatedErrorTrackingBypassRuleListApi,@@ -1367,6 +1369,43 @@ export const errorTrackingRecommendationsRestoreCreate = async (})}+export const getErrorTrackingRecommendationsSourceMapsExamplesRetrieveUrl = (+ projectId: string,+ params: ErrorTrackingRecommendationsSourceMapsExamplesRetrieveParams+) => {+ 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}/error_tracking/recommendations/source_maps_examples/?${stringifiedParams}`+ : `/api/projects/${projectId}/error_tracking/recommendations/source_maps_examples/`+}++/**+ * List the files and builds whose recent stack frames miss source maps, mapping files or debug symbols on one platform, with the reason and how many frames each covers.+ * @summary List frames missing symbols+ */+export const errorTrackingRecommendationsSourceMapsExamplesRetrieve = async (+ projectId: string,+ params: ErrorTrackingRecommendationsSourceMapsExamplesRetrieveParams,+ options?: RequestInit+): Promise<MissingSymbolsExamplesApi> => {+ return apiMutator<MissingSymbolsExamplesApi>(+ getErrorTrackingRecommendationsSourceMapsExamplesRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getErrorTrackingReleasesListUrl = (projectId: string, params?: ErrorTrackingReleasesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsBanner.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsBanner.tsxindex 928d3f20420b..ff3dae8ec2b8 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsBanner.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsBanner.tsx@@ -5,12 +5,15 @@ import { ReactNode } from 'react'import { IconMagicWand } from '@posthog/icons'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { Link } from 'lib/lemon-ui/Link'import { WizardHog } from 'scenes/onboarding/shared/wizardHog'import { BannerCallout } from './BannerCallout'import { errorTrackingBannersLogic } from './errorTrackingBannersLogic'+import { sourceMapsExamplesLogic } from './sourceMapsExamplesLogic'+import { SourceMapsExamplesModal } from './SourceMapsExamplesModal'import { SourceMapsFixModal } from './SourceMapsFixModal'-import { SOURCE_MAPS_DOCS_URL, sourceMapsFixWizardLogic } from './sourceMapsFixWizardLogic'+import { SOURCE_MAPS_DOCS_URL, SOURCE_MAPS_PLATFORM_LABELS, sourceMapsFixWizardLogic } from './sourceMapsFixWizardLogic'import type { SourceMapsRecommendation } from './types'// Mounts only while the banner is visible, so the "shown" event fires exactly when it was seen.@@ -22,13 +25,17 @@ export function SourceMapsBanner({navigation?: ReactNode}): JSX.Element {const { openModal } = useActions(sourceMapsFixWizardLogic)+ const { openExamples } = useActions(sourceMapsExamplesLogic)const { dismissBanner } = useActions(errorTrackingBannersLogic)+ const platform = recommendation.meta.platform ?? 'javascript'+ const labels = SOURCE_MAPS_PLATFORM_LABELS[platform]const percent = Math.round((recommendation.meta.unresolved_pct ?? 0) * 100)useOnMountEffect(() => {posthog.capture('error_tracking_source_maps_banner_shown', {unresolved_pct: percent,lookback_hours: recommendation.meta.lookback_hours,+ platform,})})@@ -36,8 +43,19 @@ export function SourceMapsBanner({<><BannerCalloutillustration={WizardHog}- title={`${percent}% of your stack traces aren't readable`}- description="Upload source maps to see your original code. Wizard's setup agent can add the uploads to your build."+ title={`${percent}% of ${labels.platform} frames that need ${labels.symbols} are missing them`}+ description={+ <>+ Upload {labels.symbols} to see your original code.{' '}+ <Link+ className="whitespace-nowrap"+ onClick={() => openExamples(platform)}+ data-attr="error-tracking-source-maps-banner-examples"+ >+ See examples+ </Link>+ </>+ }primaryAction={{label: 'Fix with Wizard',icon: <IconMagicWand />,@@ -56,6 +74,7 @@ export function SourceMapsBanner({onDismiss={() => dismissBanner('source_maps')}/><SourceMapsFixModal />+ <SourceMapsExamplesModal /></>)}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleDetail.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleDetail.tsxnew file mode 100644index 000000000000..12b7fccdbd2b--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleDetail.tsx@@ -0,0 +1,74 @@+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { Button, Text } from 'lib/ui/quill'+import { urls } from 'scenes/urls'++import type { MissingSymbolsExampleApi } from '../../../generated/api.schemas'+import { SourceMapsExampleStackTrace } from './SourceMapsExampleStackTrace'++export function SourceMapsExampleDetail({+ example,+ missingLabel,+ exceptionsLoaded,+ lookbackHours,+ onRetry,+ onOpenException,+}: {+ example: MissingSymbolsExampleApi+ missingLabel: string+ exceptionsLoaded: boolean+ lookbackHours: number+ onRetry: () => void+ onOpenException: () => void+}): JSX.Element {+ const exception = example.example_exception++ if (!exceptionsLoaded) {+ return (+ <Text size="xs" variant="muted">+ Couldn't load example exceptions.{' '}+ <Button variant="link" size="inline" onClick={onRetry}>+ Try again+ </Button>+ </Text>+ )+ }++ if (!exception) {+ return (+ <Text size="xs" variant="muted">+ {`No exceptions in the last ${lookbackHours} hours had these frames.`}+ </Text>+ )+ }++ return (+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex items-center gap-2">+ <Text size="xs" weight="medium" className="flex-1">+ Example exception+ </Text>+ {exception.issue_id ? (+ <Button+ variant="outline"+ render={+ <LinkPrimitive+ to={urls.errorTrackingIssue(exception.issue_id, {+ fingerprint: exception.fingerprint,+ timestamp: exception.timestamp,+ })}+ />+ }+ onClick={onOpenException}+ data-attr="error-tracking-source-maps-examples-open-exception"+ >+ Open exception+ </Button>+ ) : null}+ </div>+ <Text size="xs" className="break-words">+ {[exception.type, exception.value].filter(Boolean).join(': ')}+ </Text>+ <SourceMapsExampleStackTrace frames={exception.frames} missingLabel={missingLabel} />+ </div>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleStackTrace.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleStackTrace.tsxnew file mode 100644index 000000000000..5437b67a3ede--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExampleStackTrace.tsx@@ -0,0 +1,43 @@+import { Badge } from 'lib/ui/quill'+import { cn } from 'lib/utils/css-classes'++import type { MissingSymbolsStackFrameApi } from '../../../generated/api.schemas'++function frameLocation(frame: MissingSymbolsStackFrameApi): string {+ const position = [frame.line, frame.column].filter((part) => part !== null).join(':')+ return [frame.source ?? 'Unknown file', position].filter(Boolean).join(':')+}++export function SourceMapsExampleStackTrace({+ frames,+ missingLabel,+}: {+ frames: MissingSymbolsStackFrameApi[]+ missingLabel: string+}): JSX.Element {+ return (+ // A stack trace is machine data, so page translators leave it alone.+ <div className="flex flex-col overflow-hidden rounded-md border border-border" translate="no">+ {frames.map((frame, index) => (+ <div+ key={index}+ className={cn(+ 'flex items-center gap-2 px-2 py-1 font-mono text-xs',+ index > 0 && 'border-t border-border',+ frame.missing_symbols ? 'bg-warning text-warning-foreground' : 'text-muted-foreground'+ )}+ >+ <span className={cn('shrink-0', frame.missing_symbols ? 'font-semibold' : 'text-foreground')}>+ {frame.function ?? '?'}+ </span>+ <span className="min-w-0 truncate">{frameLocation(frame)}</span>+ {frame.missing_symbols ? (+ <Badge variant="warning" className="ml-auto shrink-0 font-sans">+ No {missingLabel}+ </Badge>+ ) : null}+ </div>+ ))}+ </div>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.stories.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.stories.tsxnew file mode 100644index 000000000000..0ce0b411b9e4--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.stories.tsx@@ -0,0 +1,132 @@+import { Meta } from '@storybook/react'+import { useState } from 'react'++import type { MissingSymbolsExamplesApi } from '../../../generated/api.schemas'+import { SourceMapsExamplesBrowser } from './SourceMapsExamplesBrowser'++const meta: Meta<typeof SourceMapsExamplesBrowser> = {+ title: 'ErrorTracking/SourceMapsExamplesBrowser',+ component: SourceMapsExamplesBrowser,+ parameters: {+ viewMode: 'story',+ },+}++export default meta++const EXAMPLES: MissingSymbolsExamplesApi = {+ platform: 'javascript',+ lookback_hours: 24,+ exceptions_loaded: true,+ results: [+ {+ reason: 'chunk_not_uploaded',+ location: '/assets/index-8b1d2e.js',+ symbol_id: '0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b',+ http_status: null,+ frames: 31,+ issues: [+ {+ id: '01933f1e-0000-7000-8000-000000000001',+ name: 'TypeError',+ description: "Cannot read properties of undefined (reading 'total')",+ occurrences: 212,+ },+ {+ id: '01933f1e-0000-7000-8000-000000000002',+ name: 'RangeError',+ description: 'Invalid time value',+ occurrences: 1,+ },+ ],+ issue_count: 2,+ issue_count_capped: false,+ example_exception: {+ issue_id: '01933f1e-0000-7000-8000-000000000001',+ fingerprint: 'example-fingerprint',+ timestamp: '2026-10-20T12:00:00Z',+ type: 'TypeError',+ value: "Cannot read properties of undefined (reading 'total')",+ frames: [+ {+ function: 'r',+ source: '/assets/index-8b1d2e.js',+ line: 1,+ column: 48213,+ in_app: true,+ missing_symbols: true,+ },+ {+ function: 'o',+ source: '/assets/index-8b1d2e.js',+ line: 1,+ column: 39177,+ in_app: true,+ missing_symbols: true,+ },+ {+ function: 'callCallback',+ source: 'react-dom/cjs/react-dom.production.js',+ line: 4164,+ column: null,+ in_app: false,+ missing_symbols: false,+ },+ ],+ },+ },+ {+ reason: 'file_not_reachable',+ location: 'https://cdn.example.com/assets/vendor-91ab.js.map',+ symbol_id: null,+ http_status: 404,+ frames: 6,+ issues: [],+ issue_count: 0,+ issue_count_capped: false,+ example_exception: null,+ },+ {+ reason: 'invalid_source_map',+ location: '/assets/admin-7c3d.js',+ symbol_id: null,+ http_status: null,+ frames: 4,+ issues: [],+ issue_count: 0,+ issue_count_capped: false,+ example_exception: null,+ },+ ],+}++function Browser(): JSX.Element {+ const [selectedIndex, setSelectedIndex] = useState(0)+ return (+ <SourceMapsExamplesBrowser+ examples={EXAMPLES}+ selectedIndex={selectedIndex}+ onSelect={setSelectedIndex}+ onRetry={() => {}}+ onOpenException={() => {}}+ />+ )+}++export function MasterDetail(): JSX.Element {+ return (+ // The wide dialog's body width, fixed so the visual baseline does not depend on the viewport.+ <div className="w-[1088px]">+ <Browser />+ </div>+ )+}++export function Narrow(): JSX.Element {+ return (+ // Below the container breakpoint the list stacks above the selected example.+ <div className="w-[520px]">+ <Browser />+ </div>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.tsxnew file mode 100644index 000000000000..2594107cf94a--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesBrowser.tsx@@ -0,0 +1,77 @@+import { Card, CardGroup, Text } from 'lib/ui/quill'+import { cn } from 'lib/utils/css-classes'+import { pluralize } from 'lib/utils/strings'++import type { MissingSymbolsExampleApi, MissingSymbolsExamplesApi } from '../../../generated/api.schemas'+import { SourceMapsExampleDetail } from './SourceMapsExampleDetail'+import { SOURCE_MAPS_PLATFORM_LABELS } from './sourceMapsFixWizardLogic'++function exampleSummary(example: MissingSymbolsExampleApi, exceptionsLoaded: boolean): string {+ const frames = pluralize(example.frames, 'frame')+ if (!exceptionsLoaded) {+ return frames+ }+ const issues =+ example.issue_count_capped && example.issue_count > 0+ ? `${example.issue_count}+ issues`+ : pluralize(example.issue_count, 'issue')+ return `${frames} · ${issues}`+}++export function SourceMapsExamplesBrowser({+ examples,+ selectedIndex,+ onSelect,+ onRetry,+ onOpenException,+}: {+ examples: MissingSymbolsExamplesApi+ selectedIndex: number+ onSelect: (index: number) => void+ onRetry: () => void+ onOpenException: () => void+}): JSX.Element {+ const selected = examples.results[selectedIndex] ?? examples.results[0]++ return (+ <div className="@container" data-quill>+ <div className="grid grid-cols-1 gap-4 @3xl:grid-cols-5">+ <CardGroup className="self-start @3xl:col-span-2">+ {examples.results.map((example, index) => (+ <Card key={index} size="sm" className="p-0">+ <button+ type="button"+ onClick={() => onSelect(index)}+ aria-pressed={example === selected}+ data-attr="error-tracking-source-maps-examples-item"+ className={cn(+ 'flex w-full flex-col gap-0.5 px-3 py-2 text-left hover:bg-fill-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',+ example === selected && 'bg-fill-selected'+ )}+ >+ <span className="truncate font-mono text-xs" translate="no">+ {example.location ?? 'Unknown file'}+ </span>+ <Text size="xs" variant="muted">+ {exampleSummary(example, examples.exceptions_loaded)}+ </Text>+ </button>+ </Card>+ ))}+ </CardGroup>+ {selected ? (+ <div className="@3xl:col-span-3">+ <SourceMapsExampleDetail+ example={selected}+ missingLabel={SOURCE_MAPS_PLATFORM_LABELS[examples.platform].symbol}+ exceptionsLoaded={examples.exceptions_loaded}+ lookbackHours={examples.lookback_hours}+ onRetry={onRetry}+ onOpenException={onOpenException}+ />+ </div>+ ) : null}+ </div>+ </div>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesModal.tsxnew file mode 100644index 000000000000..776451f915df--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/SourceMapsExamplesModal.tsx@@ -0,0 +1,105 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import { IconExternal, IconMagicWand } from '@posthog/icons'++import { LinkPrimitive } from 'lib/lemon-ui/Link'+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Skeleton,+ Text,+} from 'lib/ui/quill'++import { SourceMapsExamplesBrowser } from './SourceMapsExamplesBrowser'+import { sourceMapsExamplesLogic } from './sourceMapsExamplesLogic'+import { SOURCE_MAPS_DOCS_URL, SOURCE_MAPS_PLATFORM_LABELS, sourceMapsFixWizardLogic } from './sourceMapsFixWizardLogic'++export function SourceMapsExamplesModal(): JSX.Element {+ const { isOpen, platform, examples, examplesLoading, examplesFailed, selectedExampleIndex } =+ useValues(sourceMapsExamplesLogic)+ const { closeExamples, loadExamples, selectExample } = useActions(sourceMapsExamplesLogic)+ const { openModal } = useActions(sourceMapsFixWizardLogic)+ const wizardRef = useRef<HTMLButtonElement>(null)+ const labels = SOURCE_MAPS_PLATFORM_LABELS[platform ?? 'javascript']+ const lookbackHours = examples?.lookback_hours ?? 24+ const retry = (): void => {+ if (platform) {+ loadExamples(platform)+ }+ }++ return (+ <Dialog open={isOpen} onOpenChange={(open) => !open && closeExamples()}>+ <DialogContent size="wide" initialFocus={wizardRef}>+ <DialogHeader>+ <DialogTitle>{`${labels.platform} frames missing ${labels.symbols}`}</DialogTitle>+ <DialogDescription>+ {`The files and builds with the most frames missing ${labels.symbols} in the last ${lookbackHours} hours.`}+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ {examplesLoading || (examples === null && !examplesFailed) ? (+ <div className="flex flex-col gap-2">+ <Skeleton className="h-12" />+ <Skeleton className="h-12" />+ <Skeleton className="h-12" />+ </div>+ ) : examplesFailed || !examples ? (+ <Text size="xs" variant="destructive">+ Couldn't load the examples. If it keeps failing, contact support.{' '}+ <Button variant="link" size="inline" onClick={retry}>+ Try again+ </Button>+ </Text>+ ) : examples.results.length === 0 ? (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>{`No frames are missing ${labels.symbols}`}</EmptyTitle>+ <EmptyDescription>+ {`Nothing to upload from the last ${lookbackHours} hours.`}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <SourceMapsExamplesBrowser+ examples={examples}+ selectedIndex={selectedExampleIndex}+ onSelect={selectExample}+ onRetry={retry}+ onOpenException={closeExamples}+ />+ )}+ </DialogBody>+ <DialogFooter>+ <Button variant="outline" render={<LinkPrimitive to={SOURCE_MAPS_DOCS_URL} target="_blank" />}>+ Read docs+ <IconExternal />+ </Button>+ <Button+ ref={wizardRef}+ variant="primary"+ onClick={() => {+ closeExamples()+ openModal('source_maps_examples')+ }}+ data-attr="error-tracking-source-maps-examples-wizard"+ >+ <IconMagicWand />+ Fix with Wizard+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.test.tsnew file mode 100644index 000000000000..ae39efbf4dd6--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.test.ts@@ -0,0 +1,64 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { errorTrackingRecommendationsSourceMapsExamplesRetrieve } from '../../../generated/api'+import type { MissingSymbolsExamplesApi } from '../../../generated/api.schemas'+import { sourceMapsExamplesLogic } from './sourceMapsExamplesLogic'++jest.mock('../../../generated/api', () => ({+ errorTrackingRecommendationsSourceMapsExamplesRetrieve: jest.fn(),+}))++const mockRetrieve = jest.mocked(errorTrackingRecommendationsSourceMapsExamplesRetrieve)++function examplesFor(platform: MissingSymbolsExamplesApi['platform']): MissingSymbolsExamplesApi {+ return { platform, lookback_hours: 24, exceptions_loaded: true, results: [] }+}++describe('sourceMapsExamplesLogic', () => {+ let logic: ReturnType<typeof sourceMapsExamplesLogic.build>++ beforeEach(() => {+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, id: 2, project_id: 1 })+ mockRetrieve.mockReset()+ logic = sourceMapsExamplesLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('loads the examples of the current environment, not of its project', async () => {+ mockRetrieve.mockResolvedValue(examplesFor('javascript'))++ await expectLogic(logic, () => logic.actions.openExamples('javascript')).toDispatchActions([+ 'loadExamplesSuccess',+ ])++ expect(mockRetrieve).toHaveBeenCalledWith('2', { platform: 'javascript' })+ })++ it.each([+ ['succeeds', (): Promise<MissingSymbolsExamplesApi> => Promise.resolve(examplesFor('javascript'))],+ ['fails', (): Promise<MissingSymbolsExamplesApi> => Promise.reject(new Error('Gateway timeout'))],+ ])('ignores a superseded request that %s after the newer one', async (_, settleSuperseded) => {+ let releaseSuperseded: () => void = () => {}+ const superseded = new Promise<MissingSymbolsExamplesApi>((resolve, reject) => {+ releaseSuperseded = () => void settleSuperseded().then(resolve, reject)+ })+ mockRetrieve.mockReturnValueOnce(superseded).mockResolvedValueOnce(examplesFor('java'))++ await expectLogic(logic, () => {+ logic.actions.openExamples('javascript')+ logic.actions.closeExamples()+ logic.actions.openExamples('java')+ }).toDispatchActions(['loadExamplesSuccess'])+ releaseSuperseded()+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(logic.values.examples).toEqual(examplesFor('java'))+ expect(logic.values.examplesFailed).toBe(false)+ })+})diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.tsnew file mode 100644index 000000000000..516ba4b346de--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsExamplesLogic.ts@@ -0,0 +1,130 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { teamLogic } from 'scenes/teamLogic'++import { errorTrackingRecommendationsSourceMapsExamplesRetrieve } from '../../../generated/api'+import type { MissingSymbolsExamplesApi, SymbolsPlatformEnumApi } from '../../../generated/api.schemas'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sourceMapsExamplesLogicValues {+ currentTeamIdStrict: number | string // teamLogic+ examples: MissingSymbolsExamplesApi | null+ examplesFailed: boolean+ examplesLoading: boolean+ isOpen: boolean+ platform: SymbolsPlatformEnumApi | null+ selectedExampleIndex: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sourceMapsExamplesLogicActions {+ closeExamples: () => {+ value: true+ }+ loadExamples: (platform: SymbolsPlatformEnumApi) => SymbolsPlatformEnumApi+ loadExamplesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadExamplesSuccess: (+ examples: MissingSymbolsExamplesApi,+ payload?: SymbolsPlatformEnumApi+ ) => {+ examples: MissingSymbolsExamplesApi+ payload?: SymbolsPlatformEnumApi+ }+ openExamples: (platform: SymbolsPlatformEnumApi) => {+ platform: SymbolsPlatformEnumApi+ }+ selectExample: (index: number) => {+ index: number+ }+}++export type sourceMapsExamplesLogicType = MakeLogicType<sourceMapsExamplesLogicValues, sourceMapsExamplesLogicActions>++export const sourceMapsExamplesLogic = kea<sourceMapsExamplesLogicType>([+ path(['products', 'error_tracking', 'scenes', 'ErrorTrackingScene', 'banners', 'sourceMapsExamplesLogic']),++ connect(() => ({+ values: [teamLogic, ['currentTeamIdStrict']],+ })),++ actions({+ openExamples: (platform: SymbolsPlatformEnumApi) => ({ platform }),+ closeExamples: true,+ selectExample: (index: number) => ({ index }),+ }),++ loaders(({ values }) => ({+ examples: [+ null as MissingSymbolsExamplesApi | null,+ {+ loadExamples: async (platform: SymbolsPlatformEnumApi, breakpoint) => {+ // A newer request makes the breakpoint drop this result or error, so no stale rows show.+ try {+ return await errorTrackingRecommendationsSourceMapsExamplesRetrieve(+ String(values.currentTeamIdStrict),+ { platform }+ )+ } finally {+ breakpoint()+ }+ },+ },+ ],+ })),++ reducers({+ isOpen: [+ false,+ {+ openExamples: () => true,+ closeExamples: () => false,+ },+ ],+ platform: [+ null as SymbolsPlatformEnumApi | null,+ {+ openExamples: (_, { platform }) => platform,+ },+ ],+ // Clear the previous result on open, so a modal for another platform never shows stale rows.+ examples: {+ openExamples: () => null,+ },+ selectedExampleIndex: [+ 0,+ {+ selectExample: (_, { index }) => index,+ loadExamplesSuccess: () => 0,+ },+ ],+ examplesFailed: [+ false,+ {+ loadExamples: () => false,+ loadExamplesFailure: () => true,+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ openExamples: ({ platform }) => {+ posthog.capture('error_tracking_source_maps_examples_opened', { platform })+ actions.loadExamples(platform)+ },+ selectExample: ({ index }) => {+ posthog.capture('error_tracking_source_maps_example_selected', {+ platform: values.platform,+ position: index + 1,+ reason: values.examples?.results[index]?.reason,+ })+ },+ })),+])diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsFixWizardLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsFixWizardLogic.tsindex 98defcb76e9c..843f53325963 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsFixWizardLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/sourceMapsFixWizardLogic.ts@@ -8,12 +8,23 @@ import { getSurveyIdBasedResponseKey, getSurveyResponseKey } from 'scenes/surveyimport { SurveyEventName, SurveyEventProperties } from '~/types'import type { FeatureFlagsSet } from '../../../../../../frontend/src/lib/logic/featureFlagLogic'+import type { SourceMapsPlatform } from './types'export type WizardRating = 'good' | 'bad'-export type WizardOpenSource = 'issues_list'+// pinned: the `ui_source` value of the wizard opened event. Renaming one breaks dashboards.+export type WizardOpenSource = 'issues_list' | 'source_maps_examples'export const SOURCE_MAPS_DOCS_URL = 'https://posthog.com/docs/error-tracking/upload-source-maps'+export const SOURCE_MAPS_PLATFORM_LABELS: Record<+ SourceMapsPlatform,+ { platform: string; symbols: string; symbol: string }+> = {+ javascript: { platform: 'JavaScript', symbols: 'source maps', symbol: 'source map' },+ java: { platform: 'Android', symbols: 'mapping files', symbol: 'mapping file' },+ native: { platform: 'iOS and native', symbols: 'debug symbols', symbol: 'debug symbols' },+}+// Delay before we ask "how did the wizard do?" — long enough that the user has// actually had a chance to copy the command and kick the wizard off.const FEEDBACK_REVEAL_DELAY_MS = 1000@@ -49,7 +60,7 @@ export interface sourceMapsFixWizardLogicActions {value: true}openModal: (source: WizardOpenSource) => {- source: 'issues_list'+ source: WizardOpenSource}rateWizard: (rating: WizardRating) => {rating: WizardRatingdiff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/types.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/types.tsindex c0e8e1c549ea..cf807e8e96fb 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/types.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/banners/types.ts@@ -19,13 +19,21 @@ export interface AlertsRecommendationMeta {export type AlertsRecommendation = RecommendationWithMeta<'alerts', AlertsRecommendationMeta>-export interface SourceMapsRecommendationMeta {+export type SourceMapsPlatform = 'javascript' | 'java' | 'native'++export interface SourceMapsPlatformStats {total_frames: numberunresolved_frames: numberunresolved_pct: number+}++export interface SourceMapsRecommendationMeta extends SourceMapsPlatformStats {threshold_pct: numbermin_sample_frames: numberlookback_hours: number+ // The platform the top-level counts describe. Absent on rows computed before per-platform scoring.+ platform?: SourceMapsPlatform | null+ platforms?: Record<SourceMapsPlatform, SourceMapsPlatformStats>}export type SourceMapsRecommendation = RecommendationWithMeta<'source_maps', SourceMapsRecommendationMeta>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0d8673fdb78f..4b4c68964307 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -69344,6 +69344,169 @@ export namespace Schemas {readonly last_seen_at: string | null;}+ /**+ * * `chunk_not_uploaded` - Source map not uploaded+ * * `no_source_map_linked` - Script links no source map+ * * `file_not_reachable` - Script or source map not reachable+ * * `invalid_source_map` - Source map URL returns something else+ * * `too_large_to_fetch` - Too large to fetch+ * * `bundle_not_injected` - Bundle not processed by the PostHog CLI+ * * `mapping_not_uploaded` - Mapping file not uploaded+ * * `dsym_not_uploaded` - dSYM not uploaded+ * * `debug_symbols_not_uploaded` - Debug symbols not uploaded+ */+ export type MissingSymbolsReasonEnum = typeof MissingSymbolsReasonEnum[keyof typeof MissingSymbolsReasonEnum];+++ export const MissingSymbolsReasonEnum = {+ ChunkNotUploaded: 'chunk_not_uploaded',+ NoSourceMapLinked: 'no_source_map_linked',+ FileNotReachable: 'file_not_reachable',+ InvalidSourceMap: 'invalid_source_map',+ TooLargeToFetch: 'too_large_to_fetch',+ BundleNotInjected: 'bundle_not_injected',+ MappingNotUploaded: 'mapping_not_uploaded',+ DsymNotUploaded: 'dsym_not_uploaded',+ DebugSymbolsNotUploaded: 'debug_symbols_not_uploaded',+ } as const;++ export interface MissingSymbolsIssue {+ /** The issue ID. */+ id: string;+ /**+ * The issue name, usually the exception type.+ * @nullable+ */+ name: string | null;+ /**+ * The issue description, usually the message.+ * @nullable+ */+ description: string | null;+ /** How many of the issue's exceptions in the lookback window contain these frames. */+ occurrences: number;+ }++ export interface MissingSymbolsStackFrame {+ /**+ * The function name, resolved when symbols were available.+ * @nullable+ */+ function: string | null;+ /**+ * The file, script URL or module of the frame.+ * @nullable+ */+ source: string | null;+ /**+ * The line number, when known.+ * @nullable+ */+ line: number | null;+ /**+ * The column number, when known.+ * @nullable+ */+ column: number | null;+ /** Whether the frame is the team's own code. */+ in_app: boolean;+ /** Whether an upload of symbols would resolve this frame. */+ missing_symbols: boolean;+ }++ export interface MissingSymbolsExampleException {+ /**+ * The issue the exception belongs to, or null when no issue owns its fingerprint.+ * @nullable+ */+ issue_id: string | null;+ /** The exception's fingerprint, which the issue page uses to find it. */+ fingerprint: string;+ /** When the exception happened. */+ timestamp: string;+ /**+ * The exception type, such as TypeError.+ * @nullable+ */+ type: string | null;+ /**+ * The exception message.+ * @nullable+ */+ value: string | null;+ /** The stack trace, most recent call first, cut to the frames nearest the crash. */+ frames: MissingSymbolsStackFrame[];+ }++ export interface MissingSymbolsExample {+ /** Why the frames miss symbols, as a code. Each code maps to one kind of setup gap.+ *+ * * `chunk_not_uploaded` - Source map not uploaded+ * * `no_source_map_linked` - Script links no source map+ * * `file_not_reachable` - Script or source map not reachable+ * * `invalid_source_map` - Source map URL returns something else+ * * `too_large_to_fetch` - Too large to fetch+ * * `bundle_not_injected` - Bundle not processed by the PostHog CLI+ * * `mapping_not_uploaded` - Mapping file not uploaded+ * * `dsym_not_uploaded` - dSYM not uploaded+ * * `debug_symbols_not_uploaded` - Debug symbols not uploaded */+ reason: MissingSymbolsReasonEnum;+ /**+ * Where the frames come from: the script URL or path, the bundle, or an example class or app image.+ * @nullable+ */+ location: string | null;+ /**+ * The chunk ID, mapping ID or debug ID that the missing symbols must be uploaded under, when known.+ * @nullable+ */+ symbol_id: string | null;+ /**+ * The HTTP status the script or source map returned, for 'file_not_reachable'.+ * @nullable+ */+ http_status: number | null;+ /** How many distinct stack frames in the lookback window this covers. */+ frames: number;+ /** Up to five issues whose exceptions in the lookback window contain these frames, most occurrences first. */+ issues: MissingSymbolsIssue[];+ /** How many issues have exceptions in the lookback window that contain these frames. */+ issue_count: number;+ /** True when the exception scan searched only a sample of the frames or stopped at its limit, so `issue_count` is a lower bound. */+ issue_count_capped: boolean;+ /** A recent exception whose stack trace contains these frames, or null when none was found. */+ example_exception: MissingSymbolsExampleException | null;+ }++ /**+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native+ */+ export type SymbolsPlatformEnum = typeof SymbolsPlatformEnum[keyof typeof SymbolsPlatformEnum];+++ export const SymbolsPlatformEnum = {+ Javascript: 'javascript',+ Java: 'java',+ Native: 'native',+ } as const;++ export interface MissingSymbolsExamples {+ /** The platform the examples are for.+ *+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native */+ platform: SymbolsPlatformEnum;+ /** How many hours of recent stack frames the examples cover. */+ lookback_hours: number;+ /** False when the exception lookup failed, so `issues` and `example_exception` are unknown, not empty. */+ exceptions_loaded: boolean;+ /** The files and builds with the most frames missing symbols, most frames first. */+ results: MissingSymbolsExample[];+ }+/*** * `claude` - claude* * `codex` - codex@@ -128063,6 +128226,27 @@ export namespace Schemas {force?: boolean;};+ export type ErrorTrackingRecommendationsSourceMapsExamplesRetrieveParams = {+ /**+ * The platform to list examples for: 'javascript', 'java' (Android) or 'native' (iOS and native).+ *+ * * `javascript` - JavaScript+ * * `java` - Android+ * * `native` - iOS and native+ * @minLength 1+ */+ platform: ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform;+ };++ export type ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform = typeof ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform[keyof typeof ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform];+++ export const ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform = {+ Javascript: 'javascript',+ Java: 'java',+ Native: 'native',+ } as const;+export type ErrorTrackingReleasesListParams = {/*** Number of results to return per page.