From 833a875ea2ea828de5db49698d8ff84f38af9533 Mon Sep 17 00:00:00 2001 From: Jordi Enric <37541088+jordienr@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:03:33 +0100 Subject: [PATCH] fix(studio): friendly database metric errors DEBUG-155 (#52216) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem The Database section of Observability displays raw infrastructure API errors in metric cards, making failures confusing and repetitive. ## Fix Show one friendly alert with refresh, support, and service-status guidance when the infrastructure request fails. Keep Slow Queries visible, and show “Unable to load” only on affected cards for partial failures while preserving healthy metrics. The Overview Refresh button now invalidates the active project’s connection-limit query. Previously it used a cache key that matched no active query, so Peak Connections could stay on “Unable to load” while the other cards refreshed. Consolidates and supersedes #47491 and #47495, adapted to the current batched metrics implementation. ## How to test - Open Observability and verify that successful database metrics still render. - Simulate a failed infrastructure request. Expect one friendly alert, no raw backend message, and Slow Queries still visible. - Simulate an individual metric or connection-limit failure. Expect only the affected card to show “Unable to load”. - With the connection-limit request failing, click **Refresh** and confirm that Peak Connections shows “Unable to load”. Restore the response and click **Refresh** again. The card should show the peak and limit without a browser reload. ## QA results - **Hosted Refresh recovery passed on `ee646999af`.** After the connection-limit request recovered, one click sent a new request and replaced “Unable to load” with `6/90`. The other five hosted cases passed on `dbf78487f5`. [Automated QA review](https://github.com/supabase/supabase/pull/52216#pullrequestreview-6169329677) - **Local Chromium recovery passed on the same commit.** With a simulated HTTP 500 followed by success, Refresh retried the query and displayed `12/100`. CPU, Memory, and Disk remained healthy. - All 52 focused tests passed with retries disabled and shuffled order. The recovery test failed with the original Refresh handler. Studio typecheck passed. GitHub reported 38 successful checks and six skipped checks. Fixes https://linear.app/supabase/issue/DEBUG-155/frontend-should-render-nice-error-message-on-infra-monitoring-api ## QA screenshots ### Peak Connections before and after the Refresh fix **Before · `dbf78487f5`.** Peak Connections still showed “Unable to load” after two Refresh clicks, even as the other metrics reloaded. ![Peak Connections stuck on Unable to load after Refresh](https://k6dwnfm8zepsmdni.public.blob.vercel-storage.com/qa/wrun_41M8XTANCW0GQ8139AY6ECPK81/1796297469653-screenshot-1796297456016.png) **After · `ee646999af`.** Once the connection-limit request could succeed, the next Refresh click restored Peak Connections to `6/90`. ![Peak Connections showing 6/90 after in-app Refresh](https://k6dwnfm8zepsmdni.public.blob.vercel-storage.com/qa/wrun_41M8XTANCW0GQ8139AY6ECPK81/1796299167534-screenshot-1796299160944.png) ### Local browser with HTTP overrides Actual PR component at `dbf78487f5`, rendered in a local fixture harness at a 1440 × 900 viewport. Playwright intercepted the infrastructure API request; these are local simulated error states, not hosted-preview captures. **Full request failure:** one friendly alert; raw backend details are hidden and Slow Queries remains visible. ![Full request failure — local HTTP override](https://github.com/user-attachments/assets/f9b85b1d-f836-47ce-ad48-bab13e558079) **Partial failure:** only Disk IO Budget shows “Unable to load”; healthy metrics and Slow Queries remain visible. ![Partial metric failure — local HTTP override](https://github.com/user-attachments/assets/f7dbc088-d505-4f20-8a55-45d832b828a8) **Recovery:** after restoring a successful response and reloading, all metric cards render normally. ![Healthy recovery — local HTTP override](https://github.com/user-attachments/assets/34d3332e-717b-47ff-ba56-e00128fa474c) ### Verified hosted preview Studio staging deployment for `dbf78487f5`, 1440 × 900. All database metric cards and Slow Queries return after Refresh. ![Overview after Refresh](https://github.com/user-attachments/assets/67304cac-3dfd-4afe-b717-0a1fa12a30ba) The CPU card opens the Database report and preserves Last 24 hours. ![Database report opened from a metric card](https://github.com/user-attachments/assets/c70eb7c8-4151-4080-ba6c-69efb675d7ab) --- .../DatabaseInfrastructureMetric.test.tsx | 105 +++++++++++++++--- .../DatabaseInfrastructureMetric.tsx | 8 +- .../DatabaseInfrastructureSection.tsx | 35 ++++-- .../Observability/ObservabilityOverview.tsx | 3 +- 4 files changed, 117 insertions(+), 34 deletions(-) diff --git a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx index e5fc7de2be4..d2d329d5769 100644 --- a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx +++ b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx @@ -1,15 +1,23 @@ import { QueryClient } from '@tanstack/react-query' -import { screen, waitFor, within } from '@testing-library/react' +import { fireEvent, screen, waitFor, within } from '@testing-library/react' import { HttpResponse } from 'msw' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { DatabaseInfrastructureSection } from './DatabaseInfrastructureSection' +import { ObservabilityOverview } from './ObservabilityOverview' import type { InfraMonitoringMultiResponse } from '@/data/analytics/infra-monitoring-query' +import { configKeys } from '@/data/config/keys' import { databaseKeys } from '@/data/database/keys' +import { miscKeys } from '@/data/misc/keys' import { projectKeys } from '@/data/projects/keys' import { customRender } from '@/tests/lib/custom-render' import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw' +vi.mock('./ServiceHealthTable', () => ({ ServiceHealthTable: () => null })) +vi.mock('@/components/ui/Logs/ChartIntervalDropdown', () => ({ + ChartIntervalDropdown: () => null, +})) + const values: Record = { avg_cpu_usage: 25, ram_usage: 60, @@ -65,7 +73,7 @@ function mockMetrics(failedAttribute?: string, includeErrors = true) { return requests } -function renderMetrics() { +function renderMetrics({ hasMaxConnections = true, showOverview = false } = {}) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } }, }) @@ -74,14 +82,23 @@ function renderMetrics() { status: 'ACTIVE_HEALTHY', connectionString: 'postgresql://localhost/postgres', }) - queryClient.setQueryData(databaseKeys.maxConnections('default'), { maxConnections: 100 }) + if (hasMaxConnections) { + queryClient.setQueryData(databaseKeys.maxConnections('default'), { maxConnections: 100 }) + } + queryClient.setQueryData(configKeys.postgrest('default'), { db_schema: 'public' }) + queryClient.setQueryData(miscKeys.enabledFeaturesOverride(), { disabled_features: [] }) customRender( - , + showOverview ? ( + + ) : ( + + ), { queryClient } ) } @@ -113,10 +130,11 @@ describe('DatabaseInfrastructureSection batched metrics', () => { const requests = mockMetrics(attribute) renderMetrics() - expect(await card(label).findByText('Metric is not supported')).toBeInTheDocument() + expect(await card(label).findByText('Unable to load')).toBeInTheDocument() expect(await card('CPU').findByText('25%')).toBeInTheDocument() expect(await card('Memory').findByText('60%')).toBeInTheDocument() - expect(screen.getAllByText('Metric is not supported')).toHaveLength(1) + expect(screen.getAllByText('Unable to load')).toHaveLength(1) + expect(screen.queryByText('Metric is not supported')).not.toBeInTheDocument() expect(card(label).queryByText('0%')).not.toBeInTheDocument() expect(requests).toHaveLength(1) }) @@ -124,18 +142,59 @@ describe('DatabaseInfrastructureSection batched metrics', () => { it('shows every affected card error when all results fail', async () => { const requests = mockMetrics('*') renderMetrics() - await waitFor(() => expect(screen.getAllByText('Metric is not supported')).toHaveLength(5)) + await waitFor(() => expect(screen.getAllByText('Unable to load')).toHaveLength(5)) expect(requests).toHaveLength(1) }) it('does not display missing series as zero', async () => { mockMetrics('disk_io_budget', false) renderMetrics() - expect(await card('Disk IO balance').findByText('Error loading data')).toBeInTheDocument() + expect(await card('Disk IO balance').findByText('Unable to load')).toBeInTheDocument() expect(await card('CPU').findByText('25%')).toBeInTheDocument() }) - it('shows request-wide failures on every infrastructure card', async () => { + it('retries the failed connection limit when the overview Refresh button is clicked', async () => { + mockMetrics() + addAPIMock({ + method: 'get', + path: '/platform/projects/:ref/analytics/endpoints/service-health', + response: { result: [] }, + }) + let hasConnectionLimitFailed = false + addAPIMock({ + method: 'post', + path: '/platform/pg-meta/:ref/query', + response: ({ request }) => { + const key = new URL(request.url).searchParams.get('key') + if (key !== 'max-connections') { + return HttpResponse.json<{ slow_queries_count: number }[]>([{ slow_queries_count: 7 }]) + } + if (!hasConnectionLimitFailed) { + hasConnectionLimitFailed = true + return HttpResponse.json( + { message: 'Connection limit query failed' }, + { status: 500 } + ) + } + return HttpResponse.json<{ max_connections: string }[]>([{ max_connections: '100' }]) + }, + }) + renderMetrics({ hasMaxConnections: false, showOverview: true }) + + expect(await card('Peak Connections').findByText('Unable to load')).toBeInTheDocument() + expect(await card('CPU').findByText('25%')).toBeInTheDocument() + expect(await card('Memory').findByText('60%')).toBeInTheDocument() + expect(screen.getAllByText('Unable to load')).toHaveLength(1) + expect(screen.queryByText('Connection limit query failed')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: 'Refresh' })) + + expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument() + expect(card('Peak Connections').queryByText('Unable to load')).not.toBeInTheDocument() + expect(await card('CPU').findByText('25%')).toBeInTheDocument() + }, 15000) + + it('shows one friendly request-wide failure and preserves slow queries', async () => { addAPIMock({ method: 'get', path: '/platform/projects/:ref/infra-monitoring', @@ -143,6 +202,20 @@ describe('DatabaseInfrastructureSection batched metrics', () => { HttpResponse.json({ message: 'Project not found' }, { status: 404 }), }) renderMetrics() - await waitFor(() => expect(screen.getAllByText('Project not found')).toHaveLength(5)) + expect(await screen.findByText('Failed to load database metrics')).toBeInTheDocument() + expect(screen.getAllByText('Failed to load database metrics')).toHaveLength(1) + expect(screen.queryByText('Project not found')).not.toBeInTheDocument() + expect(screen.queryByText('Unable to load')).not.toBeInTheDocument() + expect(screen.queryByRole('link', { name: /CPU/ })).not.toBeInTheDocument() + expect(card('Slow Queries').getByText('7')).toBeInTheDocument() + expect(screen.getByText(/Try refreshing your browser/)).toBeInTheDocument() + expect(screen.getByRole('link', { name: 'contact support' })).toHaveAttribute( + 'href', + expect.stringContaining('projectRef=default') + ) + expect(screen.getByRole('link', { name: 'Supabase status page' })).toHaveAttribute( + 'href', + 'https://status.supabase.com/' + ) }) }) diff --git a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.tsx b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.tsx index a2ea02427ae..7f3534a8949 100644 --- a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.tsx +++ b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.tsx @@ -88,10 +88,6 @@ export const DatabaseInfrastructureMetric = ({ metricError ?? (isConnections ? maxConnectionsQuery.error : null) ?? (hasMissingSeries ? { message: 'Error loading data' } : null) - const errorMessage = - error && typeof error === 'object' && 'message' in error - ? String(error.message) - : 'Error loading data' let value = '--' if (data) { @@ -112,9 +108,7 @@ export const DatabaseInfrastructureMetric = ({ {label} - {!!error && ( -
{errorMessage}
- )} + {!!error &&
Unable to load
} {!error && {value}}
diff --git a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx index b3164179e6f..4c30820b2db 100644 --- a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx +++ b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx @@ -14,6 +14,8 @@ import { DatabaseInfrastructureMetric, INFRASTRUCTURE_METRIC_ATTRIBUTES, } from './DatabaseInfrastructureMetric' +import { AlertError } from '@/components/ui/AlertError' +import { InlineLink } from '@/components/ui/InlineLink' import { useInfraMonitoringAttributesQuery } from '@/data/analytics/infra-monitoring-query' import { useMaxConnectionsQuery } from '@/data/database/max-connections-query' import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' @@ -119,7 +121,19 @@ export const DatabaseInfrastructureSection = ({ return (

Database

- {/* First row: Metrics */} + {infraQuery.isError && ( + +

+ Check the{' '} + Supabase status page for + service updates. +

+
+ )}
- {(['connections', 'disk', 'diskIo', 'ram', 'cpu'] as const).map((metric) => ( - - ))} + {!infraQuery.isError && + (['connections', 'disk', 'diskIo', 'ram', 'cpu'] as const).map((metric) => ( + + ))}
) diff --git a/apps/studio/components/interfaces/Observability/ObservabilityOverview.tsx b/apps/studio/components/interfaces/Observability/ObservabilityOverview.tsx index 6a7fb8fed37..1e174ee1341 100644 --- a/apps/studio/components/interfaces/Observability/ObservabilityOverview.tsx +++ b/apps/studio/components/interfaces/Observability/ObservabilityOverview.tsx @@ -23,6 +23,7 @@ import { DocsButton } from '@/components/ui/DocsButton' import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown' import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils' import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip' +import { databaseKeys } from '@/data/database/keys' import { useIsDataApiEnabled } from '@/hooks/misc/useIsDataApiEnabled' import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled' import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization' @@ -68,7 +69,7 @@ export const ObservabilityOverview = () => { queryClient.invalidateQueries({ queryKey: ['projects', projectRef, 'service-health'] }) queryClient.invalidateQueries({ queryKey: ['project-metrics'] }) queryClient.invalidateQueries({ queryKey: ['infra-monitoring'] }) - queryClient.invalidateQueries({ queryKey: ['max-connections'] }) + queryClient.invalidateQueries({ queryKey: databaseKeys.maxConnections(projectRef) }) }, [queryClient, projectRef]) useShortcut(SHORTCUT_IDS.OBSERVABILITY_REFRESH, handleRefresh)