Skip to content

chore(query-perf): better error handling and sentry tracking - #41278

Merged
jordienr merged 8 commits into
masterfrom
jordi/fe-2234-add-error-handling-and-sentry-tracking-to-query-performance
Dec 15, 2025
Merged

jordienr merged 8 commits into
masterfrom
jordi/fe-2234-add-error-handling-and-sentry-tracking-to-query-performance

Conversation

@jordienr

@jordienr jordienr commented Dec 11, 2025 •

Copy link
Copy Markdown
Member

https://linear.app/supabase/issue/FE-2234/add-error-handling-and-sentry-tracking-to-query-performance-page

Summary by CodeRabbit

  • New Features

    • Show descriptive error banners for query performance issues with a "Try again" retry option.
    • Prevent page rendering for missing or invalid project references with a clear error banner.
  • Bug Fixes

    • Consolidate and surface errors from multiple query sources so failures are visible and actionable in the UI.
    • Improve error reporting flow to capture contextual details for troubleshooting.
  • Tests

    • Added unit tests for robust extraction of human-readable error messages.
  • UI

    • Clarified compute-size advisory text to show both max and baseline IOPS.

✏️ Tip: You can customize this high-level summary in your review settings.

@jordienr
jordienr requested a review from a team as a code owner December 11, 2025 18:06
@vercel

vercel Bot commented Dec 11, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Dec 15, 2025 5:59pm
studio-staging Ready Ready Preview, Comment Dec 15, 2025 5:59pm
6 Skipped Deployments
Project Deployment Review Updated (UTC)
studio Ignored Ignored Dec 15, 2025 5:59pm
cms Skipped Skipped Dec 15, 2025 5:59pm
design-system Skipped Skipped Dec 15, 2025 5:59pm
docs Skipped Skipped Dec 15, 2025 5:59pm
ui-library Skipped Skipped Dec 15, 2025 5:59pm
zone-www-dot-com Skipped Skipped Dec 15, 2025 5:59pm

@supabase

supabase Bot commented Dec 11, 2025

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a getErrorMessage helper and Sentry-backed captureQueryPerformanceError, and surfaces structured error reporting and UI error banners with retry across Query Performance components and the page guard for invalid project refs.

Changes

Cohort / File(s) Summary
Error message helper
apps/studio/lib/get-error-message.ts, apps/studio/lib/get-error-message.test.ts
New getErrorMessage(error) utility plus unit tests to normalize human-readable messages from various error shapes.
Sentry capture utility
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
Adds QueryPerformanceErrorContext type and captureQueryPerformanceError(error, context) which sets Sentry scope/tags, attaches truncated SQL and context, normalizes the message via getErrorMessage, and captures the exception (wrapping non-Error values).
Grid: UI error display & retry
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
Extends QueryPerformanceGridProps with `error?: string
Monitor: logs error capture & retry
apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx
Reports logs errors via captureQueryPerformanceError, computes a user-facing message, provides onRetry to re-run the logs query, and surfaces error state into the grid.
Statements: aggregate/report errors & UI banner
apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
Extracts errors from main/hit-rate/metrics queries; reports each with captureQueryPerformanceError (useEffect hooks), aggregates messages, displays a destructive Admonition, and passes error/onRetry into the grid.
Page guards
apps/studio/pages/project/[ref]/observability/query-performance.tsx
Adds early guards rendering destructive Admonitions for missing/invalid project refs before main page render.
Minor UI copy tweak
apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
Adjusts Admonition title to show both max IOPS for compute size and baseline IOPS (copy change only).

Sequence Diagram(s)

sequenceDiagram
  participant UI as Client UI (WithStatements/WithMonitor/Grid)
  participant Queries as Query Layer (main/hitRate/metrics/logs)
  participant Sentry as Sentry

  UI->>Queries: execute queries (main, hitRate, metrics, logs)
  alt any query returns error
    Queries-->>UI: error (unknown)
    UI->>Sentry: captureQueryPerformanceError(error, context)
    Sentry-->>UI: acknowledgement
    UI->>UI: normalize message (getErrorMessage) & set error state
    UI->>UI: render destructive Admonition in Page/Grid with optional "Try again"
    UI->>Queries: (onRetry) re-run affected query
  else all succeed
    Queries-->>UI: results
    UI-->>UI: render grid/visuals
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40–60 minutes

  • Review focus:
    • WithStatements.tsx — multiple useEffect hooks, error aggregation, retry wiring.
    • QueryPerformance.utils.ts — Sentry scope/tags, context selection, SQL truncation, error wrapping/cause usage.
    • Prop propagation of error and onRetry into QueryPerformanceGrid.
    • Tests: get-error-message.test.ts coverage for edge cases.

Suggested reviewers

  • joshenlim
  • kemaldotearth
  • ecktoteckto

Poem

🐰 I nibble at traces in the log,
I tidy the message through mist and fog.
I tag the clues and send them on,
A retry button — hop, try once more, come dawn. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete. It only contains a Linear issue link but is missing all required template sections like change type, current behavior, new behavior, and additional context. Fill out all required sections from the description template: confirm CONTRIBUTING.md was read, specify change type, describe current/new behavior, and add context about the improvements made.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main changes: improved error handling and Sentry tracking integration in the query performance page.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jordi/fe-2234-add-error-handling-and-sentry-tracking-to-query-performance

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6cff891 and 3136e46.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
🧠 Learnings (3)
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions

Applied to files:

  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Place Admonition at the top of page contents (below page title) or at the top of the related ScaffoldSection below ScaffoldTitle

Applied to files:

  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
🧬 Code graph analysis (1)
apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx (1)
apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx (1)
  • COMPUTE_BASELINE_IOPS (63-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: test (1)

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (6)
apps/studio/pages/project/[ref]/observability/query-performance.tsx (1)

63-75: Move computed value after guard clauses.

isPgStatMonitorEnabled accesses project?.dbVersion at Line 63, but this happens before the guard clauses that handle missing project data. While the optional chaining prevents a crash, this creates an unnecessary computation when the component will early-return anyway.

Consider moving the computation after the guards:

-  const isPgStatMonitorEnabled = project?.dbVersion === '17.4.1.076-psml-1'
-
   if (!ref) {
     return (
       <div className="h-full flex flex-col p-6">
         <Admonition
           type="destructive"
           title="Invalid project reference"
           description="Unable to load query performance data. Please ensure you have selected a valid project."
         />
       </div>
     )
   }
+
+  if (!isLoadingProject && !project) {
+    return (
+      <div className="h-full flex flex-col p-6">
+        <Admonition
+          type="destructive"
+          title="Project not found"
+          description="Unable to load project data. Please check your project reference and try again."
+        />
+      </div>
+    )
+  }
+
+  const isPgStatMonitorEnabled = project?.dbVersion === '17.4.1.076-psml-1'
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1)

465-485: Consider using Admonition's actions prop for the retry button.

The Admonition component provides an actions prop specifically for action buttons, which ensures consistent styling and layout. Currently the button is placed as a child with manual margin.

   if (error) {
     return (
       <div className="relative flex flex-grow bg-alternative min-h-0">
         <div className="flex-1 min-w-0 p-6">
           <Admonition
             type="destructive"
             title="Failed to load query performance data"
             description={error}
+            actions={
+              onRetry && (
+                <Button type="default" onClick={onRetry}>
+                  Try again
+                </Button>
+              )
+            }
-          >
-            {onRetry && (
-              <div className="mt-4">
-                <Button type="default" onClick={onRetry}>
-                  Try again
-                </Button>
-              </div>
-            )}
-          </Admonition>
+          />
         </div>
       </div>
     )
   }
apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx (1)

132-137: Consider memoizing the error message to avoid duplicate computation.

getErrorMessage(logsError) is called both in the useEffect (Line 94) and here when computing the error prop. While not a performance concern, this could be extracted to a memoized value for consistency.

+  const logsErrorMessage = useMemo(() => getErrorMessage(logsError), [logsError])
+
   useEffect(() => {
     if (logsError) {
-      const errorMessage = getErrorMessage(logsError)
       captureQueryPerformanceError(logsError, {
         projectRef: ref,
         databaseIdentifier: state.selectedDatabaseId,
         queryPreset: 'pg_stat_monitor',
         queryType: 'monitor',
         postgresVersion: project?.dbVersion,
         databaseType: state.selectedDatabaseId === ref ? 'primary' : 'read-replica',
         sql: queryWithTimeRange,
-        errorMessage: errorMessage || undefined,
+        errorMessage: logsErrorMessage || undefined,
       })
     }
-  }, [logsError, ref, state.selectedDatabaseId, project?.dbVersion, queryWithTimeRange])
+  }, [logsError, logsErrorMessage, ref, state.selectedDatabaseId, project?.dbVersion, queryWithTimeRange])

Then use logsErrorMessage in the grid prop:

       <QueryPerformanceGrid
         aggregatedData={aggregatedGridData}
         isLoading={isLogsLoading}
-        error={
-          logsError ? getErrorMessage(logsError) || 'Failed to load query performance data' : null
-        }
+        error={logsError ? logsErrorMessage || 'Failed to load query performance data' : null}
apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (2)

128-135: Avoid nested ternaries; use early returns or helper function.

Per coding guidelines, nested ternaries in JSX should be avoided. Consider extracting this to a function for clarity.

+  const getDisplayErrorMessage = (): string | null => {
+    if (mainQueryError) {
+      return getErrorMessage(mainQueryError) || 'Failed to load query performance data'
+    }
+    if (hitRateError) {
+      return getErrorMessage(hitRateError) || 'Failed to load cache hit rate data'
+    }
+    if (metricsError) {
+      return getErrorMessage(metricsError) || 'Failed to load query metrics'
+    }
+    return null
+  }
+
   const hasError = mainQueryError || hitRateError || metricsError
-  const errorMessage = mainQueryError
-    ? getErrorMessage(mainQueryError) || 'Failed to load query performance data'
-    : hitRateError
-      ? getErrorMessage(hitRateError) || 'Failed to load cache hit rate data'
-      : metricsError
-        ? getErrorMessage(metricsError) || 'Failed to load query metrics'
-        : null
+  const errorMessage = getDisplayErrorMessage()

75-126: Consider consolidating error capture into a single useEffect or custom hook.

The three separate useEffects share nearly identical logic with only different query types and error sources. This repetitive pattern could be consolidated.

const errorConfigs = useMemo(() => [
  { error: mainQueryError, queryPreset: 'unified', queryType: 'mainQuery' as const, sql: queryPerformanceQuery.resolvedSql },
  { error: hitRateError, queryPreset: 'queryHitRate', queryType: 'hitRate' as const },
  { error: metricsError, queryPreset: 'queryMetrics', queryType: 'metrics' as const },
], [mainQueryError, hitRateError, metricsError, queryPerformanceQuery.resolvedSql])

useEffect(() => {
  errorConfigs.forEach(({ error, queryPreset, queryType, sql }) => {
    if (error) {
      const errorMessage = getErrorMessage(error)
      captureQueryPerformanceError(error, {
        projectRef: ref,
        databaseIdentifier: state.selectedDatabaseId,
        queryPreset,
        queryType,
        postgresVersion: project?.dbVersion,
        databaseType: isPrimaryDatabase ? 'primary' : 'read-replica',
        sql,
        errorMessage: errorMessage || undefined,
      })
    }
  })
}, [errorConfigs, ref, state.selectedDatabaseId, project?.dbVersion, isPrimaryDatabase])
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (1)

42-51: Consider runtime validation for robustness.

The type definition is clear and well-structured. However, consider adding runtime validation using a zod schema to ensure context data is valid before sending to Sentry, which can help catch issues earlier and improve error report quality.

Example validation:

import { z } from 'zod'

const QueryPerformanceErrorContextSchema = z.object({
  projectRef: z.string().optional(),
  databaseIdentifier: z.string().optional(),
  queryPreset: z.string().optional(),
  queryType: z.enum(['hitRate', 'metrics', 'mainQuery', 'monitor', 'slowQueriesCount']).optional(),
  sql: z.string().optional(),
  errorMessage: z.string().optional(),
  postgresVersion: z.string().optional(),
  databaseType: z.enum(['primary', 'read-replica']).optional(),
})

export type QueryPerformanceErrorContext = z.infer<typeof QueryPerformanceErrorContextSchema>

As per coding guidelines, prefer runtime validation over type casting.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 511229f and c5d6f3c.

📒 Files selected for processing (7)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (2 hunks)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (4 hunks)
  • apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx (5 hunks)
  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (5 hunks)
  • apps/studio/lib/get-error-message.test.ts (1 hunks)
  • apps/studio/lib/get-error-message.ts (1 hunks)
  • apps/studio/pages/project/[ref]/observability/query-performance.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/studio/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/unit-integration-testing.mdc)

Follow the guidelines in apps/studio/tests/README.md when writing tests

Files:

  • apps/studio/lib/get-error-message.test.ts
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/lib/get-error-message.test.ts
  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
  • apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx
  • apps/studio/pages/project/[ref]/observability/query-performance.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
  • apps/studio/lib/get-error-message.ts
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
  • apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx
  • apps/studio/pages/project/[ref]/observability/query-performance.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
🧠 Learnings (8)
📚 Learning: 2025-12-11T16:46:03.665Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.665Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Always include descriptive messages in assertion expectations to provide context on test failures

Applied to files:

  • apps/studio/lib/get-error-message.test.ts
📚 Learning: 2025-12-11T02:40:15.148Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/unit-integration-testing.mdc:0-0
Timestamp: 2025-12-11T02:40:15.148Z
Learning: Applies to apps/studio/**/*.test.{ts,tsx} : Follow the guidelines in apps/studio/tests/README.md when writing tests

Applied to files:

  • apps/studio/lib/get-error-message.test.ts
📚 Learning: 2025-12-11T02:39:45.932Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/docs-graphql.mdc:0-0
Timestamp: 2025-12-11T02:39:45.932Z
Learning: Applies to apps/docs/app/api/graphql/tests/**/*.test.ts : Test files for GraphQL queries should be located at `apps/docs/app/api/graphql/tests/{queryName}.test.ts` and include tests for: (1) requesting all fields including nested fields with assertion for no errors and proper field returns, and (2) error triggering with assertion for proper GraphQL error response

Applied to files:

  • apps/studio/lib/get-error-message.test.ts
📚 Learning: 2025-12-11T16:46:03.665Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.665Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Always import from the custom test utility at '../utils/test.js' for consistent fixtures in E2E tests

Applied to files:

  • apps/studio/lib/get-error-message.test.ts
📚 Learning: 2025-12-11T16:46:03.665Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.665Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Check if test data exists before attempting to delete it to handle existing state gracefully

Applied to files:

  • apps/studio/lib/get-error-message.test.ts
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
  • apps/studio/pages/project/[ref]/observability/query-performance.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Place Admonition at the top of page contents (below page title) or at the top of the related ScaffoldSection below ScaffoldTitle

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
  • apps/studio/pages/project/[ref]/observability/query-performance.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
📚 Learning: 2025-12-11T17:04:40.001Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.001Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Import primitive UI components from packages/ui package for use across apps, not from individual component files

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
🧬 Code graph analysis (7)
apps/studio/lib/get-error-message.test.ts (1)
apps/studio/lib/get-error-message.ts (1)
  • getErrorMessage (4-12)
apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (4)
apps/studio/lib/get-error-message.ts (1)
  • getErrorMessage (4-12)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (1)
  • captureQueryPerformanceError (53-75)
packages/ui-patterns/src/admonition.tsx (1)
  • Admonition (83-180)
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1)
  • QueryPerformanceGrid (73-633)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (1)
apps/studio/lib/get-error-message.ts (1)
  • getErrorMessage (4-12)
apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx (3)
apps/studio/hooks/misc/useSelectedProject.ts (1)
  • useSelectedProjectQuery (5-17)
apps/studio/lib/get-error-message.ts (1)
  • getErrorMessage (4-12)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (1)
  • captureQueryPerformanceError (53-75)
apps/studio/pages/project/[ref]/observability/query-performance.tsx (2)
apps/studio/hooks/misc/useSelectedProject.ts (1)
  • useSelectedProjectQuery (5-17)
packages/ui-patterns/src/admonition.tsx (1)
  • Admonition (83-180)
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1)
packages/ui-patterns/src/admonition.tsx (1)
  • Admonition (83-180)
apps/studio/lib/get-error-message.ts (1)
apps/studio/data/graphql/graphql.ts (1)
  • Error (49-59)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: test (1)
  • GitHub Check: format
  • GitHub Check: test
  • GitHub Check: typecheck
🔇 Additional comments (8)
apps/studio/pages/project/[ref]/observability/query-performance.tsx (1)

65-87: LGTM! Good use of early returns for guard clauses.

The guard clauses correctly handle invalid project references and missing project data, following the coding guidelines for early returns. The Admonition placement at the top of the page content follows the established UI patterns.

apps/studio/lib/get-error-message.test.ts (1)

1-46: LGTM! Comprehensive test coverage.

The test suite thoroughly covers all code paths of getErrorMessage: null/undefined handling, string pass-through, Error instance extraction, objects with message properties, and fallback string conversion. Good edge case coverage including empty strings, nested objects, and various primitive types.

apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1)

42-49: LGTM! Well-defined props extension for error handling.

The interface extension with error?: string | null and onRetry?: () => void is clean and provides a clear API for error display and retry capabilities.

apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx (2)

92-106: LGTM! Proper error capture with comprehensive context.

The useEffect correctly captures errors to Sentry with relevant context including project reference, database identifier, query metadata, and Postgres version. The dependency array is complete.


88-90: LGTM! Simple and effective retry handler.

The retry handler correctly triggers a re-run of the query.

apps/studio/lib/get-error-message.ts (1)

1-12: LGTM! Clean and robust error message extraction.

The implementation correctly handles various error types with appropriate fallbacks. The order of checks (null/undefined → string → Error instance → object with message → string conversion) ensures comprehensive coverage.

apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (1)

139-150: LGTM! Admonition correctly placed at top of content.

Following the learnings, the Admonition is placed at the top of page contents below the page title area, which provides consistent error visibility. The destructive type appropriately signals an error state.

apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (1)

1-1: LGTM - imports are appropriate.

The Sentry and getErrorMessage imports are correctly added to support the new error capture functionality.

Also applies to: 5-6

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (3)

75-126: Reduce duplication across the three Sentry capture effects.

All three useEffect blocks share nearly identical logic and context fields, differing only by the error variable and the queryPreset / queryType (and sql for the main query). Consider extracting a small helper like reportQueryPerformanceError(error, contextOverrides) or a custom hook to encapsulate this pattern so future changes to the context shape only need to be done in one place.


128-136: Normalize hasError to a boolean and simplify message selection.

hasError currently holds an Error | null value rather than a boolean, which works in a boolean context but is slightly misleading given the name and can make types noisier. You could instead do:

const hasError = Boolean(mainQueryError || hitRateError || metricsError)

let errorMessage: string | null = null
if (mainQueryError) {
  errorMessage = getErrorMessage(mainQueryError) ?? 'Failed to load query performance data'
} else if (hitRateError) {
  errorMessage = getErrorMessage(hitRateError) ?? 'Failed to load cache hit rate data'
} else if (metricsError) {
  errorMessage = getErrorMessage(metricsError) ?? 'Failed to load query metrics'
}

This keeps hasError truly boolean and avoids the nested conditional chain while preserving current behavior.


8-8: Admonition usage and placement look good; minor copy tweak optional.

Using Admonition at the top of the content when hasError is true aligns nicely with the studio UI guidance for prominent error messaging, and wiring it to the derived errorMessage keeps the copy specific. If you want to polish further, you could consider varying the title slightly when only hit-rate or metrics fail (e.g. “Error loading cache hit rate” or “Error loading query metrics”) to better match the fallback descriptions, but the current generic title is acceptable.

Based on learnings, this follows the recommended Admonition placement pattern.

Also applies to: 139-150

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8530cc1 and 6cff891.

📒 Files selected for processing (2)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts (2 hunks)
  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
🧠 Learnings (2)
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Place Admonition at the top of page contents (below page title) or at the top of the related ScaffoldSection below ScaffoldTitle

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: test (1)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: format
🔇 Additional comments (3)
apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx (3)

26-28: Good separation of concerns with shared error utilities.

Importing captureQueryPerformanceError and getErrorMessage keeps Sentry reporting and message extraction centralized instead of reimplementing them locally; this makes the error handling in this component much easier to maintain and reason about.


43-50: Clean derivation of per-source errors.

Pulling queryError out of queryPerformanceQuery and normalizing hitRateError / metricsError into mainQueryError, hitRateError, and metricsError gives you a clear single source per query for both UI and telemetry; this is a good pattern to keep error handling predictable.


182-191: Grid error wiring and retry behavior are consistent with main query state.

Passing only the main query’s error (with a safe fallback message) to QueryPerformanceGrid, alongside an onRetry={handleRefresh} callback, gives the grid clear, focused responsibility while the top-level Admonition handles aggregated errors from all queries; this separation of concerns looks solid.

@coveralls

coveralls commented Dec 11, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 68.722% (+0.3%) from 68.471%
when pulling 8e725fa on jordi/fe-2234-add-error-handling-and-sentry-tracking-to-query-performance
into 511229f on master.

@github-actions

github-actions Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  66 passed
flaky  1 flaky
skipped  4 skipped

Details

stats  71 tests across 12 suites
duration  8 minutes, 50 seconds
commit  8e725fa

Flaky tests

Features › auth-users.spec.ts › auth users list refresh › should automatically refresh users list after creating multiple users

Skipped tests

Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@awaseem awaseem left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants