Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(telemetry): dedupe funnel toast error events (#47802)

Pamela Chia9858562b8bff
diff --git a/apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsx b/apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsx
index a094881fb62..42da3e95cbe 100644
--- a/apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsx
+++ b/apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsx
@@ -3,6 +3,7 @@
import { ErrorDisplay, SupportFormParams } from 'ui-patterns/ErrorDisplay/ErrorDisplay'
import { getMappingForError } from './ErrorMatcher.utils'
+import { isDashboardErrorSampled } from '@/lib/telemetry/error-sampling'
import { useTrack } from '@/lib/telemetry/track'
interface ErrorMatcherProps {
@@ -26,7 +27,7 @@ export function ErrorMatcher({ title, error, supportFormParams, className }: Err
supportFormParams={supportFormParams}
className={className}
onRender={() => {
- if (Math.random() < 0.1) {
+ if (isDashboardErrorSampled()) {
track('dashboard_error_created', {
source: 'error_display',
errorType: mapping?.id,
diff --git a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
index 8deba853795..64443884b40 100644
--- a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
+++ b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
@@ -253,8 +253,8 @@ export const NewOrgForm = ({
}
},
onError: (data) => {
- toast.error(data.message, { duration: 10_000 })
- trackFunnelError('org_creation', classifyApiError('org_creation', data), 'toast')
+ const toastId = toast.error(data.message, { duration: 10_000 })
+ trackFunnelError('org_creation', classifyApiError('org_creation', data), 'toast', toastId)
setNewOrgLoading(false)
},
})
@@ -266,8 +266,8 @@ export const NewOrgForm = ({
}
},
onError: (error) => {
- toast.error(error.message, { dismissible: true, duration: 10_000 })
- trackFunnelError('org_creation', classifyApiError('org_creation', error), 'toast')
+ const toastId = toast.error(error.message, { dismissible: true, duration: 10_000 })
+ trackFunnelError('org_creation', classifyApiError('org_creation', error), 'toast', toastId)
},
})
@@ -283,15 +283,17 @@ export const NewOrgForm = ({
size: form.getValues('size'),
})
} else {
+ // If the payment intent is not successful, we reset the payment method and show an error
+ const toastId = toast.error(
+ `Could not confirm payment. Please try again or use a different card.`,
+ { duration: 10_000 }
+ )
trackFunnelError(
'org_creation',
classifyStripeError(paymentIntentConfirmation.error),
- 'toast'
+ 'toast',
+ toastId
)
- // If the payment intent is not successful, we reset the payment method and show an error
- toast.error(`Could not confirm payment. Please try again or use a different card.`, {
- duration: 10_000,
- })
resetPaymentMethod()
setNewOrgLoading(false)
}
@@ -591,11 +593,12 @@ export const NewOrgForm = ({
}
onLoadingChange={(loading) => setPaymentConfirmationLoading(loading)}
onError={(err) => {
- toast.error(err.message, { duration: 10_000 })
+ const toastId = toast.error(err.message, { duration: 10_000 })
trackFunnelError(
'org_creation',
{ errorCategory: 'payment', errorReason: 'payment_error' },
- 'toast'
+ 'toast',
+ toastId
)
setNewOrgLoading(false)
resetPaymentMethod()
diff --git a/apps/studio/components/interfaces/SignIn/SignUpForm.tsx b/apps/studio/components/interfaces/SignIn/SignUpForm.tsx
index 14cbcbf82c4..26cd71e1fcb 100644
--- a/apps/studio/components/interfaces/SignIn/SignUpForm.tsx
+++ b/apps/studio/components/interfaces/SignIn/SignUpForm.tsx
@@ -79,8 +79,8 @@ export const SignUpForm = () => {
onError: (error) => {
setCaptchaToken(null)
captchaRef.current?.resetCaptcha()
- toast.error(`Failed to sign up: ${error.message}`)
- trackFunnelError('signup', classifyApiError('signup', error), 'toast')
+ const toastId = toast.error(`Failed to sign up: ${error.message}`)
+ trackFunnelError('signup', classifyApiError('signup', error), 'toast', toastId)
},
})
diff --git a/apps/studio/components/ui/AlertError.tsx b/apps/studio/components/ui/AlertError.tsx
index 96746430a20..9c521678ff6 100644
--- a/apps/studio/components/ui/AlertError.tsx
+++ b/apps/studio/components/ui/AlertError.tsx
@@ -4,6 +4,7 @@ import { Button } from 'ui'
import { Admonition } from 'ui-patterns/admonition'
import { SupportLink } from '@/components/interfaces/Support/SupportLink'
+import { isDashboardErrorSampled } from '@/lib/telemetry/error-sampling'
import { useTrack } from '@/lib/telemetry/track'
export interface AlertErrorProps {
@@ -70,7 +71,7 @@ export const AlertError = ({
useEffect(() => {
if (!hasTrackedRef.current) {
hasTrackedRef.current = true
- if (Math.random() < 0.1) {
+ if (isDashboardErrorSampled()) {
track('dashboard_error_created', {
source: 'admonition',
})
diff --git a/apps/studio/lib/telemetry/error-sampling.ts b/apps/studio/lib/telemetry/error-sampling.ts
new file mode 100644
index 00000000000..cbfeb97729c
--- /dev/null
+++ b/apps/studio/lib/telemetry/error-sampling.ts
@@ -0,0 +1,8 @@
+// dashboard_error_created is emitted from several sources (toast, form, admonition,
+// error_display) that must share one capture rate — downstream analysis assumes a uniform
+// sampling multiplier when comparing volumes across sources.
+export const DASHBOARD_ERROR_SAMPLE_RATE = 0.1
+
+export function isDashboardErrorSampled() {
+ return Math.random() < DASHBOARD_ERROR_SAMPLE_RATE
+}
diff --git a/apps/studio/lib/telemetry/use-track-funnel-error.ts b/apps/studio/lib/telemetry/use-track-funnel-error.ts
index 3aa00091a55..3226e8ef5a8 100644
--- a/apps/studio/lib/telemetry/use-track-funnel-error.ts
+++ b/apps/studio/lib/telemetry/use-track-funnel-error.ts
@@ -1,27 +1,52 @@
import { useCallback } from 'react'
+import { isDashboardErrorSampled } from '@/lib/telemetry/error-sampling'
import type { FunnelErrorClassification, FunnelOrigin } from '@/lib/telemetry/funnel-errors'
import { useTrack } from '@/lib/telemetry/track'
+import { registerFunnelErrorToast } from '@/lib/toast-errors'
-// Matches the existing dashboard_error_created capture rate; keeps PostHog volume bounded.
-const SAMPLE_RATE = 0.1
+interface TrackFunnelError {
+ /**
+ * Toast-sourced errors are emitted by ToastErrorTracker as a single enriched
+ * dashboard_error_created event. Pass the id returned by toast.error() so the tracker
+ * attaches the funnel properties instead of firing an untagged duplicate.
+ *
+ * Call this in the same synchronous block that created the toast — the tracker processes
+ * new toasts in an effect on the next render, so registering after an await could be too
+ * late and the event would go out untagged.
+ */
+ (
+ origin: FunnelOrigin,
+ classification: FunnelErrorClassification,
+ source: 'toast',
+ toastId: string | number
+ ): void
+ (origin: FunnelOrigin, classification: FunnelErrorClassification, source: 'form'): void
+}
export function useTrackFunnelError() {
const track = useTrack()
- return useCallback(
+ return useCallback<TrackFunnelError>(
(
origin: FunnelOrigin,
classification: FunnelErrorClassification,
- source: 'toast' | 'form' = 'toast'
+ source: 'toast' | 'form',
+ toastId?: string | number
) => {
- if (Math.random() >= SAMPLE_RATE) return
- track('dashboard_error_created', {
- source,
+ const properties = {
origin,
errorCategory: classification.errorCategory,
errorReason: classification.errorReason,
...(classification.errorCode !== undefined && { errorCode: classification.errorCode }),
- })
+ }
+ if (source === 'toast') {
+ if (toastId !== undefined) registerFunnelErrorToast(toastId, properties)
+ return
+ }
+ // Form-sourced events are sampled here — toast-sourced events are sampled once by
+ // ToastErrorTracker, which is the sole emitter for them.
+ if (!isDashboardErrorSampled()) return
+ track('dashboard_error_created', { source, ...properties })
},
[track]
)
diff --git a/apps/studio/lib/toast-errors.test.tsx b/apps/studio/lib/toast-errors.test.tsx
new file mode 100644
index 00000000000..07e0971d3ad
--- /dev/null
+++ b/apps/studio/lib/toast-errors.test.tsx
@@ -0,0 +1,101 @@
+import { act, render, renderHook, waitFor } from '@testing-library/react'
+import { toast } from 'sonner'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { registerFunnelErrorToast, ToastErrorTracker } from './toast-errors'
+import { useTrackFunnelError } from '@/lib/telemetry/use-track-funnel-error'
+
+const { mockTrack } = vi.hoisted(() => ({ mockTrack: vi.fn() }))
+
+vi.mock('@/lib/telemetry/track', () => ({ useTrack: () => mockTrack }))
+
+describe('ToastErrorTracker', () => {
+ beforeEach(() => {
+ mockTrack.mockReset()
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('tracks an unregistered error toast without funnel properties', async () => {
+ render(<ToastErrorTracker />)
+ act(() => {
+ toast.error('request failed')
+ })
+ await waitFor(() =>
+ expect(mockTrack).toHaveBeenCalledWith('dashboard_error_created', { source: 'toast' })
+ )
+ expect(mockTrack).toHaveBeenCalledTimes(1)
+ })
+
+ it('fires a single enriched event for a registered funnel toast', async () => {
+ render(<ToastErrorTracker />)
+ act(() => {
+ registerFunnelErrorToast(toast.error('funnel error'), {
+ origin: 'signup',
+ errorCategory: 'api',
+ errorReason: 'other',
+ errorCode: 500,
+ })
+ })
+ await waitFor(() =>
+ expect(mockTrack).toHaveBeenCalledWith('dashboard_error_created', {
+ source: 'toast',
+ origin: 'signup',
+ errorCategory: 'api',
+ errorReason: 'other',
+ errorCode: 500,
+ })
+ )
+ expect(mockTrack).toHaveBeenCalledTimes(1)
+ })
+
+ it('routes toast-sourced funnel errors from useTrackFunnelError into one enriched event', async () => {
+ render(<ToastErrorTracker />)
+ const { result } = renderHook(() => useTrackFunnelError())
+ act(() => {
+ const toastId = toast.error('funnel failure')
+ result.current(
+ 'project_creation',
+ { errorCategory: 'api', errorReason: 'rate_limited', errorCode: 429 },
+ 'toast',
+ toastId
+ )
+ })
+ await waitFor(() =>
+ expect(mockTrack).toHaveBeenCalledWith('dashboard_error_created', {
+ source: 'toast',
+ origin: 'project_creation',
+ errorCategory: 'api',
+ errorReason: 'rate_limited',
+ errorCode: 429,
+ })
+ )
+ expect(mockTrack).toHaveBeenCalledTimes(1)
+ })
+
+ it('ignores non-error toasts', async () => {
+ render(<ToastErrorTracker />)
+ act(() => {
+ toast.success('all good')
+ })
+ act(() => {
+ toast.error('unmarked sentinel')
+ })
+ await waitFor(() => expect(mockTrack).toHaveBeenCalledTimes(1))
+ })
+
+ it('skips error toasts that lose the sampling draw', async () => {
+ vi.spyOn(Math, 'random').mockReturnValueOnce(0.5)
+ render(<ToastErrorTracker />)
+ act(() => {
+ toast.error('sampled out')
+ })
+ act(() => {
+ toast.error('sampled in')
+ })
+ await waitFor(() => expect(mockTrack).toHaveBeenCalledTimes(1))
+ })
+})
diff --git a/apps/studio/lib/toast-errors.tsx b/apps/studio/lib/toast-errors.tsx
index 8dd031588f3..a51cc0df8b1 100644
--- a/apps/studio/lib/toast-errors.tsx
+++ b/apps/studio/lib/toast-errors.tsx
@@ -1,22 +1,39 @@
import { useEffect, useRef } from 'react'
import { useSonner } from 'sonner'
+import { isDashboardErrorSampled } from '@/lib/telemetry/error-sampling'
+import type { FunnelErrorClassification, FunnelOrigin } from '@/lib/telemetry/funnel-errors'
import { useTrack } from '@/lib/telemetry/track'
+type FunnelErrorProperties = { origin: FunnelOrigin } & FunnelErrorClassification
+
+// Funnel call sites register their toast id (via useTrackFunnelError) so the tracker emits a
+// single enriched event for that toast instead of an untagged duplicate.
+const funnelErrorToasts = new Map<string | number, FunnelErrorProperties>()
+
+export function registerFunnelErrorToast(
+ toastId: string | number,
+ properties: FunnelErrorProperties
+) {
+ funnelErrorToasts.set(toastId, properties)
+}
+
export const ToastErrorTracker = () => {
const track = useTrack()
const { toasts } = useSonner()
- const trackRef = useRef(new Set<string | number>())
+ const seenToastIds = useRef(new Set<string | number>())
useEffect(() => {
toasts.forEach((toast) => {
- if (toast.type === 'error' && !trackRef.current.has(toast.id)) {
- trackRef.current.add(toast.id)
- if (Math.random() < 0.1) {
- track('dashboard_error_created', {
- source: 'toast',
- })
- }
+ if (toast.type !== 'error' || seenToastIds.current.has(toast.id)) return
+ seenToastIds.current.add(toast.id)
+ const funnelProperties = funnelErrorToasts.get(toast.id)
+ funnelErrorToasts.delete(toast.id)
+ if (isDashboardErrorSampled()) {
+ track('dashboard_error_created', {
+ source: 'toast',
+ ...funnelProperties,
+ })
}
})
}, [toasts, track])
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index f4d2b74a564..4212349eae1 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -322,8 +322,13 @@ const Wizard: NextPageWithLayout = () => {
router.push(`/project/${res.ref}`)
},
onError: (error) => {
- toast.error(`Failed to create new project: ${error.message}`)
- trackFunnelError('project_creation', classifyApiError('project_creation', error), 'toast')
+ const toastId = toast.error(`Failed to create new project: ${error.message}`)
+ trackFunnelError(
+ 'project_creation',
+ classifyApiError('project_creation', error),
+ 'toast',
+ toastId
+ )
},
})
@@ -364,12 +369,14 @@ const Wizard: NextPageWithLayout = () => {
} = values
if (useOrioleDb && !availableOrioleVersion) {
+ const toastId = toast.error('No available OrioleDB image found, only Postgres is available')
trackFunnelError(
'project_creation',
{ errorCategory: 'validation', errorReason: 'oriole_unavailable' },
- 'toast'
+ 'toast',
+ toastId
)
- return toast.error('No available OrioleDB image found, only Postgres is available')
+ return
}
const { postgresEngine, releaseChannel } =
diff --git a/apps/studio/routes/__root.tsx b/apps/studio/routes/__root.tsx
index 79468e6559b..3e99c476146 100644
--- a/apps/studio/routes/__root.tsx
+++ b/apps/studio/routes/__root.tsx
@@ -77,6 +77,7 @@ import { API_URL, BASE_PATH, IS_PLATFORM, useDefaultProvider } from '@/lib/const
import { NuqsAdapter } from '@/lib/nuqs-tanstack-adapter'
import { ProfileProvider } from '@/lib/profile'
import { Telemetry } from '@/lib/telemetry'
+import { ToastErrorTracker } from '@/lib/toast-errors'
import { Toaster } from '@/lib/toaster'
import Error404 from '@/pages/404'
import Error500 from '@/pages/500'
@@ -340,6 +341,7 @@ function RootComponent() {
</FeaturePreviewContextProvider>
</BannerStackProvider>
<Toaster />
+ <ToastErrorTracker />
<MonacoThemeProvider />
</CommandProvider>
</AiAssistantStateContextProvider>