Repository navigation
feat: initial supamonitor changes - #42313
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds Supamonitor support to Query Performance: new Supamonitor UI (grid + chart), parsing/aggregation utilities, data fetching and DB check for the Supamonitor extension, a hook to expose feature status, and wiring to render the Supamonitor view when enabled. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant QueryPerfPage
participant useSupamonitorStatus
participant useSupamonitorEnabledQuery
participant Database
participant WithSupamonitor
participant useLogsQuery
participant SupamonitorUtils
User->>QueryPerfPage: Open Query Performance page
QueryPerfPage->>useSupamonitorStatus: request supamonitor status
useSupamonitorStatus->>useSupamonitorEnabledQuery: run enabled check
useSupamonitorEnabledQuery->>Database: query shared_preload_libraries
Database-->>useSupamonitorEnabledQuery: return libraries
useSupamonitorEnabledQuery-->>useSupamonitorStatus: isSupamonitorEnabled
useSupamonitorStatus-->>QueryPerfPage: status flag
alt supamonitor enabled
QueryPerfPage->>WithSupamonitor: render Supamonitor view
WithSupamonitor->>WithSupamonitor: compute date range
WithSupamonitor->>useLogsQuery: fetch logs with generated SQL
useLogsQuery->>Database: execute Supamonitor SQL
Database-->>useLogsQuery: raw log rows
useLogsQuery-->>WithSupamonitor: raw logs
WithSupamonitor->>SupamonitorUtils: parse & transform logs
SupamonitorUtils-->>WithSupamonitor: parsed/aggregated data
WithSupamonitor-->>User: render SupamonitorGrid + SupamonitorChart
else supamonitor disabled
QueryPerfPage->>QueryPerfPage: render existing PgStatMonitor UI
QueryPerfPage-->>User: render standard Query Performance UI
end
Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
🎭 Playwright Test ResultsDetails
Flaky testsFeatures › cron-jobs.spec.ts › High Query Cost Banner › shows banner and still displays cron jobs when query cost exceeds threshold Skipped testsFeatures › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In
`@apps/studio/components/interfaces/QueryPerformance/WithSupamonitor/WithSupamonitor.tsx`:
- Around line 62-89: Remove all debug console.log calls in the WithSupamonitor
component: delete the console.log lines around queryWithTimeRange and
supamonitorLogs, and the logs inside the parsedLogs, chartData, and
aggregatedGridData useMemo blocks (the console.log calls that show '🔍 logData',
'🔍 parsedLogs', '🔍 First parsed log structure', '📊 chartData', '📊 chartData
length', and '📋 aggregatedGridData'). If you need runtime diagnostics keep them
behind a configurable debug/logging facility instead of console.log (e.g., use a
logger.debug or a feature-flag guard) and ensure useLogsQuery,
parseSupamonitorLogs, transformLogsToChartData, and aggregateLogsByQuery remain
unchanged.
In `@apps/studio/data/database/supamonitor-enabled-query.ts`:
- Around line 14-19: The getSupamonitorEnabled function currently duplicates
validation by checking projectRef; remove the explicit guard (the "if
(!projectRef) throw new Error('Project ref is required')" check) and rely on
executeSql's existing validation instead so callers follow the repo standard;
locate getSupamonitorEnabled in supamonitor-enabled-query.ts and delete that
conditional before the call to executeSql.
🧹 Nitpick comments (7)
apps/studio/components/interfaces/QueryPerformance/WithSupamonitor/SupamonitorChart.tsx (3)
12-24: UnuseddateRangeprop and loose typing.The
dateRangeprop is declared in the interface but never used in the component. Either remove it or use it for display purposes.Additionally,
errorandparsedLogsare typed asany/any[], which loses type safety. Consider using specific types.Suggested type improvements
interface SupamonitorChartProps { - dateRange?: { - period_start: { date: string; time_period: string } - period_end: { date: string; time_period: string } - interval: string - } onDateRangeChange?: (from: string, to: string) => void chartData: ChartDataPoint[] isLoading: boolean - error: any + error: Error | string | null currentSelectedQuery: string | null - parsedLogs: any[] + parsedLogs: ParsedLogEntry[] }Import
ParsedLogEntryfrom./WithSupamonitor.utils.
41-43: Consider handling edge cases in number formatting.
toLocaleString()onNaNorInfinityreturns the string"NaN"or"Infinity". If such values could appear, consider adding a guard.Optional defensive improvement
const formatNumberValue = (value: number): string => { + if (!Number.isFinite(value)) return '–' return value.toLocaleString() }
69-73: Duplicate query normalization logic.The query normalization (
replace(/\s+/g, ' ').trim()) is duplicated here and inWithSupamonitor.utils.ts(normalizeQueryfunction). Consider importing and reusing that helper.Reuse normalizeQuery helper
+import { normalizeQuery } from './WithSupamonitor.utils' // ... const querySpecificData = useMemo(() => { if (!currentSelectedQuery || !parsedLogs.length) return null - const normalizedSelected = currentSelectedQuery.replace(/\s+/g, ' ').trim() + const normalizedSelected = normalizeQuery(currentSelectedQuery) const queryLogs = parsedLogs.filter((log) => { - const normalized = (log.query || '').replace(/\s+/g, ' ').trim() + const normalized = normalizeQuery(log.query || '') return normalized === normalizedSelected })Note: You'll need to export
normalizeQueryfrom the utils file.apps/studio/components/interfaces/QueryPerformance/WithSupamonitor/SupamonitorGrid.tsx (1)
51-60: Unusedrolesfilter state.The
rolesquery state is parsed but never used in thereportDatafiltering logic (lines 169-208). Either implement the roles filtering or remove this unused state to avoid confusion.Remove unused state or implement filtering
If roles filtering is not needed:
- const [{ search, roles, callsFilter }] = useQueryStates({ + const [{ search, callsFilter }] = useQueryStates({ search: parseAsString.withDefault(''), - roles: parseAsArrayOf(parseAsString).withDefault([]), callsFilter: parseAsJson<NumericFilter | null>(Also update the useEffect dependency:
useEffect(() => { setSelectedRow(undefined) - }, [search, roles, urlSort, order, callsFilter]) + }, [search, urlSort, order, callsFilter])apps/studio/components/interfaces/QueryPerformance/WithSupamonitor/WithSupamonitor.tsx (1)
63-67: Type assertion on potentially undefinedref.The
ref as stringassertion could mask issues ifrefis undefined. Consider adding a guard or handling the undefined case.Optional: Add early return for missing ref
export const WithSupamonitor = ({ dateRange, onDateRangeChange }: WithSupamonitorProps) => { const { ref } = useParams() + + if (!ref) { + return null // or a loading/error state + } + const { data: project } = useSelectedProjectQuery()Or ensure
useLogsQueryhandles undefined gracefully (per the hook's implementation).apps/studio/components/interfaces/QueryPerformance/WithSupamonitor/WithSupamonitor.utils.ts (2)
94-96: Consider exportingnormalizeQueryfor reuse.This helper is duplicated in
SupamonitorChart.tsx. Exporting it would enable consistent query normalization across the codebase.Export the helper
-const normalizeQuery = (query: string): string => { +export const normalizeQuery = (query: string): string => { return query.replace(/\s+/g, ' ').trim() }
81-87: Placeholder values for unpopulated fields.Several
ChartDataPointfields are hardcoded to0(stddev_time,p50_time,p95_time,rows_read,cache_hits,cache_misses). This is fine for the initial implementation, but consider adding a comment or TODO if these are expected to be populated later.
| export async function getSupamonitorEnabled({ | ||
| projectRef, | ||
| connectionString, | ||
| }: SupamonitorEnabledVariables) { | ||
| if (!projectRef) throw new Error('Project ref is required') | ||
|
|
There was a problem hiding this comment.
Remove duplicate projectRef guard — executeSql already validates.
This extra check duplicates validation and diverges from the repo standard for callers of executeSql.
🔧 Proposed change
export async function getSupamonitorEnabled({
projectRef,
connectionString,
}: SupamonitorEnabledVariables) {
- if (!projectRef) throw new Error('Project ref is required')
-
const { result } = await executeSql<{ libraries: string }[]>({
projectRef,
connectionString,
sql: `SELECT current_setting('shared_preload_libraries', true) AS libraries`,
})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export async function getSupamonitorEnabled({ | |
| projectRef, | |
| connectionString, | |
| }: SupamonitorEnabledVariables) { | |
| if (!projectRef) throw new Error('Project ref is required') | |
| export async function getSupamonitorEnabled({ | |
| projectRef, | |
| connectionString, | |
| }: SupamonitorEnabledVariables) { | |
| const { result } = await executeSql<{ libraries: string }[]>({ | |
| projectRef, | |
| connectionString, | |
| sql: `SELECT current_setting('shared_preload_libraries', true) AS libraries`, | |
| }) |
🤖 Prompt for AI Agents
In `@apps/studio/data/database/supamonitor-enabled-query.ts` around lines 14 - 19,
The getSupamonitorEnabled function currently duplicates validation by checking
projectRef; remove the explicit guard (the "if (!projectRef) throw new
Error('Project ref is required')" check) and rely on executeSql's existing
validation instead so callers follow the repo standard; locate
getSupamonitorEnabled in supamonitor-enabled-query.ts and delete that
conditional before the call to executeSql.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceChart.tsx (2)
139-139:⚠️ Potential issue | 🟠 MajorMissing
parsedLogsin dependency array.The
currentMetricsuseMemo usesparsedLogs(lines 67-87) to compute the histogram-based p95 value, butparsedLogsis not included in the dependency array. This will cause stale values whenparsedLogsupdates without changes tochartDataorselectedMetric.🐛 Proposed fix
- }, [chartData, selectedMetric]) + }, [chartData, selectedMetric, parsedLogs])
154-154:⚠️ Potential issue | 🟡 MinorPotential runtime error if
parsedLogsis undefined.Line 154 accesses
parsedLogs.lengthwithout first checking ifparsedLogsis truthy. This is inconsistent with line 68 which guards against falsyparsedLogs. IfparsedLogsisundefinedornull, this will throw.🛡️ Proposed fix
- if (!currentSelectedQuery || !parsedLogs.length) return null + if (!currentSelectedQuery || !parsedLogs?.length) return null
🧹 Nitpick comments (1)
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceChart.tsx (1)
366-371: Consider simplifying theshowLegendcondition.The condition covers all four metric types defined in the component, making it effectively always
true. This could be simplified.♻️ Optional simplification
showLegend={ - selectedMetric === 'query_latency' || - selectedMetric === 'cache_hits' || - selectedMetric === 'rows_read' || - selectedMetric === 'calls' + true }Alternatively, if all metrics should show the legend, you could remove this prop entirely if
trueis the default.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/studio/pages/project/[ref]/observability/query-performance.tsx (1)
104-115:⚠️ Potential issue | 🟠 MajorFix boolean precedence so the date picker renders for pg_stat_monitor.
At Line 104,
||has lower precedence than&&, so whenisPgStatMonitorEnabledis true the expression returnstrue(renders nothing). Wrap the OR condition so the picker renders for either flag.✅ Proposed fix
- {isPgStatMonitorEnabled || isSupamonitorEnabled && ( + {(isPgStatMonitorEnabled || isSupamonitorEnabled) && ( <LogsDatePicker value={datePickerValue} helpers={datePickerHelpers.filter( (h) => h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES || h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_3_HOURS || h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_24_HOURS )} onSubmit={handleDatePickerChange} /> )}
awaseem
left a comment
There was a problem hiding this comment.
Minor changes, not blocking
| showLegend={ | ||
| selectedMetric === 'query_latency' || | ||
| selectedMetric === 'cache_hits' || | ||
| selectedMetric === 'rows_read' || | ||
| selectedMetric === 'calls' | ||
| } | ||
| showLegend={true} |
There was a problem hiding this comment.
Does this effect the original view in query performance?
There was a problem hiding this comment.
It shouldn't affect it since selectedMetric is always one of these 4
cd3fb3c to
b90d777
Compare
|
(force pushed to exclude changes on marketing pages) |
Braintrust eval report
|
Add a Query Performance page implementation powered by supamonitor. Context
This looks largely the same as the pg_stat_monitor implementation:
Only available on projects on custom AMI - existing users are unaffected
Summary by CodeRabbit
New Features
Bug Fixes
Documentation