Skip to content

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

feat(studio): clarify memory commitment risk thresholds FE-4467 (#51799)

Jordi Enric8ba2f0a63bc6
diff --git a/apps/studio/components/ui/Charts/ChartHeader.test.tsx b/apps/studio/components/ui/Charts/ChartHeader.test.tsx
new file mode 100644
index 00000000000..fad87313628
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ChartHeader.test.tsx
@@ -0,0 +1,29 @@
+import { render, screen } from '@testing-library/react'
+import { TooltipProvider } from 'ui'
+import { expect, it } from 'vitest'
+
+import { ChartHeader } from './ChartHeader'
+import { memoryCommitmentThresholds } from './Charts.test-fixtures'
+
+it.each(['Warning', 'Problematic', 'Severe'])(
+ 'shows %s so the commitment risk is readable without opening details',
+ (expectedLabel) => {
+ const threshold = memoryCommitmentThresholds.find((zone) => zone.badgeLabel === expectedLabel)
+ if (!threshold) throw new Error(`Missing memory commitment threshold: ${expectedLabel}`)
+
+ render(
+ <TooltipProvider>
+ <ChartHeader
+ title="Memory commitment"
+ hideChartType
+ highlightedValue="6 GB"
+ thresholdZoneWarning={threshold}
+ />
+ </TooltipProvider>
+ )
+
+ const badge = screen.getByLabelText(`Warning: ${threshold.label}`)
+ expect(badge).toHaveTextContent(expectedLabel)
+ expect(badge).toHaveAttribute('tabindex', '0')
+ }
+)
diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsx
index 114403ea1f6..65a1c9e7b1d 100644
--- a/apps/studio/components/ui/Charts/ChartHeader.tsx
+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx
@@ -37,6 +37,14 @@ export interface ChartHeaderProps {
data?: any[]
xAxisKey?: string
yAxisKey?: string
+ thresholdZoneAttribute?: string
+ thresholdZoneWarning?: {
+ label: string
+ color: string
+ textColor?: string
+ badgeLabel?: string
+ tooltip: string
+ }
xAxisIsDate?: boolean
valuePrecision?: number
shouldFormatBytes?: boolean
@@ -67,6 +75,8 @@ export const ChartHeader = ({
data,
xAxisKey,
yAxisKey,
+ thresholdZoneAttribute,
+ thresholdZoneWarning,
xAxisIsDate = true,
displayDateInUtc,
customDateFormat,
@@ -123,10 +133,13 @@ export const ChartHeader = ({
if (activeDataPoint) {
// For stacked charts, we need to calculate the total of all attributes
// that should be included in the total (excluding reference lines, max values, etc.)
- let newValue = activeDataPoint[yAxisKey]
+ const isThresholdValueMissing =
+ thresholdZoneAttribute !== undefined &&
+ !Number.isFinite(activeDataPoint[thresholdZoneAttribute])
+ let newValue = isThresholdValueMissing ? 'Unavailable' : activeDataPoint[yAxisKey]
// If this is a stacked chart with multiple attributes, calculate the total
- if (attributes && attributes.length > 1) {
+ if (!isThresholdValueMissing && attributes && attributes.length > 1) {
const attributesToIgnore =
attributes
?.filter((a) => a.omitFromTotal || a.isMaxValue || a.provider === 'reference-line')
@@ -175,6 +188,7 @@ export const ChartHeader = ({
data,
xAxisKey,
yAxisKey,
+ thresholdZoneAttribute,
xAxisIsDate,
displayDateInUtc,
customDateFormat,
@@ -294,6 +308,30 @@ export const ChartHeader = ({
</ButtonTooltip>
) : null}
+ {thresholdZoneWarning && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge
+ tabIndex={0}
+ className="cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={`Warning: ${thresholdZoneWarning.label}`}
+ style={{
+ color: thresholdZoneWarning.textColor ?? thresholdZoneWarning.color,
+ borderColor: thresholdZoneWarning.color,
+ backgroundColor: `color-mix(in srgb, ${thresholdZoneWarning.color} 10%, transparent)`,
+ }}
+ >
+ {thresholdZoneWarning.badgeLabel ?? 'Warning'}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs" side="top">
+ <p className="font-medium">
+ {thresholdZoneWarning.label} threshold crossed in this time range.
+ </p>
+ <p>{thresholdZoneWarning.tooltip}</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
{!hideChartType && onChartStyleChange && (
<ButtonTooltip
className="px-1.5"
diff --git a/apps/studio/components/ui/Charts/Charts.test-fixtures.ts b/apps/studio/components/ui/Charts/Charts.test-fixtures.ts
new file mode 100644
index 00000000000..4a8010e62ff
--- /dev/null
+++ b/apps/studio/components/ui/Charts/Charts.test-fixtures.ts
@@ -0,0 +1,26 @@
+import type { Project } from '@/data/projects/project-detail-query'
+import { getReportAttributesV2 } from '@/data/reports/database-charts'
+import { createMockProject } from '@/tests/helpers'
+
+const project: Project = {
+ ...createMockProject({}),
+ status: 'ACTIVE_HEALTHY',
+ inserted_at: '2026-01-01T00:00:00Z',
+ is_physical_backups_enabled: false,
+ subscription_id: 'subscription-1',
+ connectionString: '',
+ db_host: '',
+ dbVersion: 'supabase-postgres-15.1.0',
+ high_availability: false,
+ infra_compute_size: 'micro',
+ integration_source: null,
+ restUrl: '',
+ updated_at: '2026-01-01T00:00:00Z',
+}
+const report = getReportAttributesV2(['database'], project).find(
+ (chart) => chart.id === 'memory-commitment'
+)
+
+if (!report?.thresholdZones) throw new Error('Missing memory commitment thresholds')
+
+export const memoryCommitmentThresholds = report.thresholdZones
diff --git a/apps/studio/components/ui/Charts/Charts.utils.test.ts b/apps/studio/components/ui/Charts/Charts.utils.test.ts
index 0a5a3da8f49..fce3d758b60 100644
--- a/apps/studio/components/ui/Charts/Charts.utils.test.ts
+++ b/apps/studio/components/ui/Charts/Charts.utils.test.ts
@@ -3,16 +3,51 @@ import { describe, expect, it } from 'vitest'
import { computeYAxisDomain, normalizeStackedSeriesData } from './Charts.utils'
const IOPS_DATA = [
- { timestamp: 1, disk_iops_write: 1200, disk_iops_read: 24203, disk_iops_max: 25000 },
- { timestamp: 2, disk_iops_write: 400, disk_iops_read: 3200, disk_iops_max: 25000 },
- { timestamp: 3, disk_iops_write: 100, disk_iops_read: 900, disk_iops_max: 25000 },
+ { timestamp: 1, disk_iops_write: 40, disk_iops_read: 80, disk_iops_max: 100 },
+ { timestamp: 2, disk_iops_write: 10, disk_iops_read: 20, disk_iops_max: 100 },
+ { timestamp: 3, disk_iops_write: 5, disk_iops_read: 5, disk_iops_max: 100 },
]
const IOPS_VISIBLE = ['disk_iops_write', 'disk_iops_read']
describe('computeYAxisDomain', () => {
- describe('percentage charts with max line hidden', () => {
- it('returns [0, yMaxFromVisible] to zoom in on the data', () => {
+ describe('memory commitment axis', () => {
+ const GIB = 1024 ** 3
+ const memoryBelowCapacity = {
+ isPercentage: false,
+ showMaxValue: false,
+ yMaxFromVisible: 2 * GIB,
+ thresholdZoneMax: 8 * GIB,
+ maxAttributeKey: undefined,
+ showMaxLine: false,
+ data: [{ ram_commit_used: 2 * GIB }],
+ visibleAttributeNames: ['ram_commit_used'],
+ }
+
+ it('shows commitment against full capacity so low usage does not appear near the limit', () => {
+ expect(computeYAxisDomain(memoryBelowCapacity)).toEqual([0, 8 * GIB])
+ })
+
+ it('keeps the capacity scale when Committed is hidden', () => {
+ expect(computeYAxisDomain({ ...memoryBelowCapacity, visibleAttributeNames: [] })).toEqual([
+ 0,
+ 8 * GIB,
+ ])
+ })
+
+ it('keeps above-capacity commitment visible', () => {
+ expect(
+ computeYAxisDomain({
+ ...memoryBelowCapacity,
+ data: [{ ram_commit_used: 10 * GIB }],
+ visibleAttributeNames: ['ram_commit_used'],
+ })
+ ).toEqual([0, 10 * GIB])
+ })
+ })
+
+ describe('CPU percentage axis with the maximum hidden', () => {
+ it('scales from zero to the observed 75% instead of the 100% limit', () => {
expect(
computeYAxisDomain({
isPercentage: true,
@@ -26,7 +61,7 @@ describe('computeYAxisDomain', () => {
).toEqual([0, 75])
})
- it('still zooms in even when a maxAttributeKey is present', () => {
+ it('keeps the observed 60% scale even when the maximum series exists', () => {
expect(
computeYAxisDomain({
isPercentage: true,
@@ -41,13 +76,13 @@ describe('computeYAxisDomain', () => {
})
})
- describe('no max reference line', () => {
- it('returns auto when maxAttributeKey is undefined', () => {
+ describe('disk operations without a visible limit', () => {
+ it('uses automatic scaling when no limit metric is configured', () => {
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: false,
- yMaxFromVisible: 5000,
+ yMaxFromVisible: 80,
maxAttributeKey: undefined,
showMaxLine: false,
data: IOPS_DATA,
@@ -56,12 +91,12 @@ describe('computeYAxisDomain', () => {
).toEqual(['auto', 'auto'])
})
- it('returns auto when showMaxLine is false', () => {
+ it('uses automatic scaling when the limit line is hidden', () => {
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: true,
- yMaxFromVisible: 5000,
+ yMaxFromVisible: 80,
maxAttributeKey: 'disk_iops_max',
showMaxLine: false,
data: IOPS_DATA,
@@ -71,14 +106,14 @@ describe('computeYAxisDomain', () => {
})
})
- describe('max reference line not yet loaded (value is 0)', () => {
- it('returns auto when diskConfig has not loaded and reference line value is 0', () => {
+ describe('disk operations before the limit loads', () => {
+ it('uses automatic scaling while the limit is zero', () => {
const dataWithZeroMax = IOPS_DATA.map((p) => ({ ...p, disk_iops_max: 0 }))
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: true,
- yMaxFromVisible: 5000,
+ yMaxFromVisible: 80,
maxAttributeKey: 'disk_iops_max',
showMaxLine: true,
data: dataWithZeroMax,
@@ -88,54 +123,39 @@ describe('computeYAxisDomain', () => {
})
})
- describe('explicit domain with reference line', () => {
- it('uses the reference line value when bars stay below it', () => {
- // All stacked bar totals (1000, 500) are well below maxRefValue (25000)
+ describe('charts with a visible limit', () => {
+ it('shows the 100-operation limit when stacked reads and writes stay below it', () => {
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: true,
- yMaxFromVisible: 800,
+ yMaxFromVisible: 40,
maxAttributeKey: 'disk_iops_max',
showMaxLine: true,
data: [
- { disk_iops_write: 400, disk_iops_read: 600, disk_iops_max: 25000 },
- { disk_iops_write: 200, disk_iops_read: 300, disk_iops_max: 25000 },
+ { disk_iops_write: 30, disk_iops_read: 40, disk_iops_max: 100 },
+ { disk_iops_write: 20, disk_iops_read: 30, disk_iops_max: 100 },
],
visibleAttributeNames: IOPS_VISIBLE,
})
- ).toEqual([0, 25000])
+ ).toEqual([0, 100])
})
- it('uses the stacked bar total when it exceeds the reference line', () => {
- // Stacked total at first point: 24203 + 1200 = 25403 > 25000
+ it('expands to 120 operations when 40 writes plus 80 reads exceed the 100-operation limit', () => {
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: true,
- yMaxFromVisible: 24203,
+ yMaxFromVisible: 80,
maxAttributeKey: 'disk_iops_max',
showMaxLine: true,
data: IOPS_DATA,
visibleAttributeNames: IOPS_VISIBLE,
})
- ).toEqual([0, 25403])
+ ).toEqual([0, 120])
})
- it('domain min is always 0', () => {
- const [min] = computeYAxisDomain({
- isPercentage: false,
- showMaxValue: true,
- yMaxFromVisible: 100,
- maxAttributeKey: 'disk_iops_max',
- showMaxLine: true,
- data: IOPS_DATA,
- visibleAttributeNames: IOPS_VISIBLE,
- }) as [number, number]
- expect(min).toBe(0)
- })
-
- it('works for database connections chart (single bar series, no stacking)', () => {
+ it('shows the 60-connection limit when one connection series peaks at 52', () => {
const data = [
{ pg_stat_database_num_backends: 45, max_db_connections: 60 },
{ pg_stat_database_num_backends: 52, max_db_connections: 60 },
@@ -153,42 +173,40 @@ describe('computeYAxisDomain', () => {
).toEqual([0, 60])
})
- it('handles non-numeric values in data gracefully', () => {
+ it('ignores missing or invalid reads and writes without losing the limit', () => {
const data = [
- { disk_iops_write: 'bad', disk_iops_read: null, disk_iops_max: 25000 },
- { disk_iops_write: 500, disk_iops_read: 1000, disk_iops_max: 25000 },
+ { disk_iops_write: 'bad', disk_iops_read: null, disk_iops_max: 100 },
+ { disk_iops_max: 100 },
+ { disk_iops_write: 20, disk_iops_read: 30, disk_iops_max: 100 },
]
expect(
computeYAxisDomain({
isPercentage: false,
showMaxValue: true,
- yMaxFromVisible: 1000,
+ yMaxFromVisible: 30,
maxAttributeKey: 'disk_iops_max',
showMaxLine: true,
- data: data as Record<string, unknown>[],
+ data,
visibleAttributeNames: IOPS_VISIBLE,
})
- ).toEqual([0, 25000])
+ ).toEqual([0, 100])
})
})
})
describe('normalizeStackedSeriesData', () => {
- it('normalizes each stacked point to 100%', () => {
+ it('shows fractional CPU shares accurately', () => {
const normalized = normalizeStackedSeriesData({
- data: [{ system: 25, user: 25, idle: 100 }],
+ data: [{ system: 1, user: 1, idle: 4 }],
attributeNames: ['system', 'user', 'idle'],
})
- expect(normalized[0].system).toBeCloseTo(16.6666666667)
- expect(normalized[0].user).toBeCloseTo(16.6666666667)
- expect(normalized[0].idle).toBeCloseTo(66.6666666666)
- expect(
- Number(normalized[0].system) + Number(normalized[0].user) + Number(normalized[0].idle)
- ).toBeCloseTo(100)
+ expect(normalized[0].system).toBeCloseTo(100 / 6)
+ expect(normalized[0].user).toBeCloseTo(100 / 6)
+ expect(normalized[0].idle).toBeCloseTo(400 / 6)
})
- it('leaves empty stacks unchanged', () => {
+ it('keeps zero CPU usage at zero', () => {
const empty = [{ system: 0, user: 0, idle: 0 }]
expect(
@@ -199,7 +217,7 @@ describe('normalizeStackedSeriesData', () => {
).toEqual(empty)
})
- it('leaves data unchanged when attributeNames is empty', () => {
+ it('leaves unselected series unchanged', () => {
const data = [{ system: 50, user: 30, timestamp: 1000 }]
expect(
@@ -210,7 +228,7 @@ describe('normalizeStackedSeriesData', () => {
).toEqual(data)
})
- it('preserves non-stacked keys (timestamps, metadata) unchanged', () => {
+ it('keeps normalized CPU history at its original timestamps', () => {
const data = [{ system: 60, user: 80, period_start: '2024-01-01', timestamp: 1000 }]
const normalized = normalizeStackedSeriesData({
data,
diff --git a/apps/studio/components/ui/Charts/Charts.utils.tsx b/apps/studio/components/ui/Charts/Charts.utils.tsx
index 82f228e88d1..21e1c8f9a46 100644
--- a/apps/studio/components/ui/Charts/Charts.utils.tsx
+++ b/apps/studio/components/ui/Charts/Charts.utils.tsx
@@ -158,6 +158,7 @@ export function computeYAxisDomain({
isPercentage,
showMaxValue,
yMaxFromVisible,
+ thresholdZoneMax = 0,
maxAttributeKey,
showMaxLine,
data,
@@ -166,20 +167,22 @@ export function computeYAxisDomain({
isPercentage: boolean
showMaxValue: boolean
yMaxFromVisible: number
+ thresholdZoneMax?: number
maxAttributeKey: string | undefined
showMaxLine: boolean
data: Record<string, unknown>[]
visibleAttributeNames: string[]
}): [number, number] | ['auto', 'auto'] {
if (isPercentage && !showMaxValue) return [0, yMaxFromVisible]
- if (!maxAttributeKey || !showMaxLine) return ['auto', 'auto']
+ const hasThresholdZones = Number.isFinite(thresholdZoneMax) && thresholdZoneMax > 0
+ if (!hasThresholdZones && (!maxAttributeKey || !showMaxLine)) return ['auto', 'auto']
const maxRefValue = data.reduce((max, point) => {
- const val = point[maxAttributeKey]
+ const val = maxAttributeKey && showMaxLine ? point[maxAttributeKey] : undefined
return typeof val === 'number' ? Math.max(max, val) : max
}, 0)
- if (maxRefValue <= 0) return ['auto', 'auto']
+ if (!hasThresholdZones && maxRefValue <= 0) return ['auto', 'auto']
const maxStackedTotal = data.reduce((max, point) => {
const total = visibleAttributeNames.reduce((sum, name) => {
@@ -189,7 +192,7 @@ export function computeYAxisDomain({
return Math.max(max, total)
}, 0)
- return [0, Math.max(maxRefValue, maxStackedTotal)]
+ return [0, Math.max(maxRefValue, maxStackedTotal, hasThresholdZones ? thresholdZoneMax : 0)]
}
export function normalizeStackedSeriesData<T extends Record<string, unknown>>({
diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsx
index b5274738ec7..466a13d61f1 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx
@@ -42,8 +42,15 @@ import {
getStackId,
MultiAttribute,
resolveChartColor,
+ ThresholdZone,
} from './ComposedChart.utils'
+import {
+ getThresholdZoneChart,
+ getThresholdZoneXBounds,
+ getThresholdZoneYBounds,
+} from './ComposedChartThresholdZones.utils'
import NoDataPlaceholder from './NoDataPlaceholder'
+import { ThresholdZoneLine } from './ThresholdZoneLine'
import { ChartHighlight } from './useChartHighlight'
import { useChartHoverState } from './useChartHoverState'
import { formatDateTime, useFormatDateTime } from '@/lib/datetime'
@@ -52,6 +59,8 @@ import { formatBytes, formatBytesMinMB } from '@/lib/helpers'
export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
chartId?: string
attributes: MultiAttribute[]
+ thresholdZones?: ThresholdZone[]
+ thresholdZoneAttribute?: string
yAxisKey: string
xAxisKey: string
displayDateInUtc?: boolean
@@ -103,6 +112,8 @@ export function ComposedChart({
chartId,
data,
attributes,
+ thresholdZones,
+ thresholdZoneAttribute,
yAxisKey,
xAxisKey,
format,
@@ -252,6 +263,11 @@ export function ComposedChart({
}
function computeHighlightedValue() {
+ const activePoint = data[focusDataIndex ?? data.length - 1]
+ if (thresholdZoneAttribute && !Number.isFinite(activePoint?.[thresholdZoneAttribute])) {
+ return 'Unavailable'
+ }
+
const referenceLines = attributes.filter(
(attribute) => attribute?.provider === 'reference-line'
)
@@ -327,9 +343,16 @@ export function ComposedChart({
chartHighlight?.coordinates.right &&
chartHighlight?.coordinates.left !== chartHighlight?.coordinates.right
+ const firstChartPoint = { ...data[0] }
+ if (thresholdZoneAttribute && !(thresholdZoneAttribute in firstChartPoint)) {
+ const firstMetricPoint = data.find((point) => thresholdZoneAttribute in point)
+ if (firstMetricPoint)
+ firstChartPoint[thresholdZoneAttribute] = firstMetricPoint[thresholdZoneAttribute]
+ }
+
const chartData =
data && !!data[0]
- ? Object.entries(data[0])
+ ? Object.entries(firstChartPoint)
?.map(([key, value]) => ({
name: key,
value: value,
@@ -376,6 +399,11 @@ export function ComposedChart({
[data, normalizeVisibleStackToPercent, visibleAttributes]
)
+ const thresholdZoneChart = useMemo(
+ () => getThresholdZoneChart(data, thresholdZones, thresholdZoneAttribute),
+ [data, thresholdZones, thresholdZoneAttribute]
+ )
+
const isPercentage = format === '%'
const isRamChart =
!chartData?.some((att: any) => att.name.toLowerCase() === 'ram_usage') &&
@@ -403,6 +431,7 @@ export function ComposedChart({
isPercentage,
showMaxValue,
yMaxFromVisible,
+ thresholdZoneMax: thresholdZoneChart.maxValue,
maxAttributeKey: maxAttribute?.attribute,
showMaxLine: _showMaxValue,
data,
@@ -412,6 +441,7 @@ export function ComposedChart({
isPercentage,
showMaxValue,
yMaxFromVisible,
+ thresholdZoneChart.maxValue,
maxAttribute,
_showMaxValue,
data,
@@ -438,6 +468,8 @@ export function ComposedChart({
return (
<div className={cn('flex flex-col gap-y-3', className)}>
<ChartHeader
+ thresholdZoneAttribute={thresholdZoneAttribute}
+ thresholdZoneWarning={thresholdZoneChart.selectedZone}
hideHighlightedValue={hideHighlightedValue}
title={title}
showNewBadge={showNewBadge}
@@ -594,6 +626,28 @@ export function ComposedChart({
activeDot={false}
/>
))}
+ {thresholdZoneChart.zones.flatMap((zone) =>
+ zone.runs.map((run, index) => {
+ const yBounds = getThresholdZoneYBounds(run, zone.runs[index - 1])
+ const hasVisibleBars = chartStyle === 'bar' && visibleAttributes.length > 0
+ return (
+ <ReferenceArea
+ key={`${zone.label}-${run.startIndex}`}
+ {...getThresholdZoneXBounds(run, data, hasVisibleBars, _XAxisProps.dataKey)}
+ {...yBounds}
+ fill="none"
+ stroke={zone.color}
+ shape={
+ <ThresholdZoneLine
+ isRising={yBounds.y1 > yBounds.y2}
+ label={zone.isAlwaysVisible ? zone.label : undefined}
+ />
+ }
+ />
+ )
+ })
+ )}
+
{/* Max value, if available */}
{maxAttribute && _showMaxValue && (
<Line
@@ -649,6 +703,7 @@ export function ComposedChart({
<CustomTooltip
{...props}
data={data}
+ thresholdZones={thresholdZoneChart.zones}
format={format}
isPercentage={isPercentage}
label={resolvedHighlightedLabel}
diff --git a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
index 60690c6bdb2..6fff75eb885 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
@@ -4,7 +4,9 @@ import { useState } from 'react'
import { cn, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from 'ui'
import { CHART_COLORS, DateTimeFormats } from './Charts.constants'
+import type { Datum } from './Charts.types'
import { formatPercentage, numberFormatter } from './Charts.utils'
+import { getThresholdZoneValues } from './ComposedChartThresholdZones.utils'
import { useFormatDateTime, useTimezone } from '@/lib/datetime'
import { formatBytes, formatBytesMinMB } from '@/lib/helpers'
@@ -13,6 +15,8 @@ export interface ReportAttributes {
titleTooltip?: string
label: string
attributes?: (MultiAttribute | false)[]
+ thresholdZones?: ThresholdZone[]
+ thresholdZoneAttribute?: string
defaultChartStyle?: 'bar' | 'line' | 'stackedAreaLine'
hide?: boolean
entitlement?: string
@@ -38,6 +42,17 @@ export interface ReportAttributes {
hideHighlightedValue?: boolean
}
+export type ThresholdZone = {
+ label: string
+ color: string
+ textColor?: string
+ badgeLabel?: string
+ tooltipLabel?: string
+ isAlwaysVisible?: boolean
+ tooltip: string
+ getRanges: (data: Datum[]) => ([number, number] | null)[]
+}
+
export type Provider = 'infra-monitoring' | 'daily-stats' | 'mock' | 'reference-line' | 'logs'
export type ThemedColor = {
@@ -122,7 +137,8 @@ interface TooltipProps {
payload?: any[]
label?: string | number
attributes?: MultiAttribute[]
- data?: Record<string, unknown>[]
+ data?: Datum[]
+ thresholdZones?: ThresholdZone[]
xAxisKey?: string
isPercentage?: boolean
format?: string | ((value: unknown) => string)
@@ -173,6 +189,7 @@ export const CustomTooltip = ({
label: _label,
attributes,
data,
+ thresholdZones,
xAxisKey = 'period_start',
isPercentage,
format,
@@ -192,6 +209,7 @@ export const CustomTooltip = ({
const rawDataPoint = data?.find(
(point) => point[xAxisKey] === timestamp || point[timestampKey] === timestamp
)
+ const thresholdValues = getThresholdZoneValues(rawDataPoint, thresholdZones)
const maxValueAttribute = isMaxAttribute(attributes)
const maxValue =
maxValueAttribute && rawDataPoint
@@ -304,6 +322,15 @@ export const CustomTooltip = ({
{[...payload].reverse().map((entry: any, index: number) => (
<LabelItem key={`${entry.name}-${index}`} entry={entry} />
))}
+ {thresholdValues?.map((threshold) => (
+ <div key={threshold.label} className="flex items-center w-full">
+ <MaxConnectionsIcon color={threshold.color} />
+ <span className="text-foreground-lighter ml-1 grow cursor-default select-none">
+ {threshold.label}
+ </span>
+ <span className="ml-3.5">{formatNumeric(threshold.value)}</span>
+ </div>
+ ))}
{active && showTotal && (
<div className="flex md:flex-col gap-1 md:gap-0 text-foreground mt-1">
<span className="grow text-foreground-lighter">Total</span>
diff --git a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
index 9026603bfe4..adacf9337ec 100644
--- a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
@@ -7,7 +7,7 @@ import { Card, cn, WarningIcon } from 'ui'
import type { ChartHighlightAction } from './ChartHighlightActions'
import type { ChartData } from './Charts.types'
import { ComposedChart } from './ComposedChart'
-import { MultiAttribute } from './ComposedChart.utils'
+import { MultiAttribute, ThresholdZone } from './ComposedChart.utils'
import { useChartHighlight } from './useChartHighlight'
import Panel from '@/components/ui/Panel'
import { AnalyticsInterval, DataPoint } from '@/data/analytics/constants'
@@ -27,6 +27,8 @@ export interface ComposedChartHandlerProps {
id?: string
label: string
attributes: MultiAttribute[]
+ thresholdZones?: ThresholdZone[]
+ thresholdZoneAttribute?: string
startDate: string
endDate: string
interval?: string
@@ -109,6 +111,7 @@ const LazyChartWrapper = ({ id, children }: PropsWithChildren<{ id: string }>) =
const ComposedChartHandler = ({
label,
attributes,
+ thresholdZoneAttribute,
startDate,
endDate,
interval,
@@ -149,7 +152,8 @@ const ComposedChartHandler = ({
interval as AnalyticsInterval,
databaseIdentifier,
Array.isArray(data) ? undefined : data,
- isVisible
+ isVisible,
+ thresholdZoneAttribute
)
const combinedData = useMemo(() => {
@@ -191,6 +195,8 @@ const ComposedChartHandler = ({
const queryData = attributeQueries[index]?.data?.data
const matchingPoint = queryData?.find((p: any) => p.period_start === timestamp)
+ if (attr.attribute === thresholdZoneAttribute && matchingPoint?.[attr.attribute] == null)
+ return
let value = matchingPoint?.[attr.attribute] ?? 0
if (attr.manipulateValue && typeof attr.manipulateValue === 'function') {
@@ -216,9 +222,12 @@ const ComposedChartHandler = ({
})
return combined as DataPoint[]
- }, [data, attributeQueries, attributes])
+ }, [data, attributeQueries, attributes, thresholdZoneAttribute])
- const loading = isLoading || attributeQueries.some((query: any) => query.isLoading)
+ const loading =
+ data !== undefined
+ ? isLoading
+ : isLoading || attributeQueries.some((query: any) => query.isLoading)
const _highlightedValue = useMemo(() => {
if (highlightedValue !== undefined) return highlightedValue
@@ -298,6 +307,7 @@ const ComposedChartHandler = ({
<div className="absolute right-6 z-50 flex justify-between scroll-mt-16">{children}</div>
<ComposedChart
attributes={attributes}
+ thresholdZoneAttribute={thresholdZoneAttribute}
data={combinedData as DataPoint[]}
format={format}
// [Joshen] This is where it's messing up
@@ -333,7 +343,8 @@ const useAttributeQueries = (
interval: AnalyticsInterval,
databaseIdentifier: string | undefined,
data: ChartData | undefined,
- isVisible: boolean
+ isVisible: boolean,
+ thresholdZoneAttribute?: string
) => {
const infraAttributes = attributes
.filter((attr) => attr?.provider === 'infra-monitoring')
@@ -351,7 +362,8 @@ const useAttributeQueries = (
interval,
databaseIdentifier,
data,
- isVisible
+ isVisible,
+ thresholdZoneAttribute
)
const dailyStatsQueries = useProjectDailyStatsQueries(
dailyStatsAttributes,
diff --git a/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.test.ts b/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.test.ts
new file mode 100644
index 00000000000..8cddc14f957
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.test.ts
@@ -0,0 +1,243 @@
+import { describe, expect, it } from 'vitest'
+
+import type { ThresholdZone } from './ComposedChart.utils'
+import {
+ getHighestCrossedThresholdZone,
+ getThresholdZoneChart,
+ getThresholdZoneMaximum,
+ getThresholdZoneRuns,
+ getThresholdZoneValues,
+ getThresholdZoneXBounds,
+ getThresholdZoneYBounds,
+ type ThresholdZoneRun,
+} from './ComposedChartThresholdZones.utils'
+
+function boundsAtSamples(runs: ThresholdZoneRun[], count: number) {
+ return Array.from({ length: count }, (_, index) => {
+ const run = runs.find((run) => run.startIndex <= index && run.endIndex >= index)
+ return [run?.lower, run?.upper]
+ })
+}
+
+describe('historical threshold segments', () => {
+ it('keeps a stable threshold continuous across the displayed history', () => {
+ const runs = getThresholdZoneRuns([
+ [2, 4],
+ [2, 4],
+ [2, 4],
+ ])
+
+ expect(boundsAtSamples(runs, 3)).toEqual([
+ [2, 4],
+ [2, 4],
+ [2, 4],
+ ])
+ })
+
+ it('moves the threshold when infrastructure capacity changes', () => {
+ const runs = getThresholdZoneRuns([
+ [2, 4],
+ [2, 4],
+ [4, 8],
+ [4, 8],
+ ])
+
+ expect(boundsAtSamples(runs, 4)).toEqual([
+ [2, 4],
+ [2, 4],
+ [4, 8],
+ [4, 8],
+ ])
+ })
+})
+
+describe('threshold alignment with chart edges', () => {
+ const data = [1000, 2000, 3000, 4000].map((timestamp) => ({ timestamp }))
+
+ it.each([true, false])(
+ 'draws thresholds to both chart edges when bars are visible: %s',
+ (hasVisibleBars) => {
+ const run = { startIndex: 0, endIndex: 3, lower: 2, upper: 4 }
+ expect(getThresholdZoneXBounds(run, data, hasVisibleBars)).toEqual({
+ x1: undefined,
+ x2: undefined,
+ })
+ }
+ )
+
+ it('ends bar thresholds at the infrastructure resize boundary', () => {
+ const run = { startIndex: 1, endIndex: 2, lower: 2, upper: 4 }
+ expect(getThresholdZoneXBounds(run, data, true)).toEqual({ x1: 1, x2: 2 })
+ })
+
+ it('steps line thresholds at the infrastructure resize timestamp', () => {
+ const run = { startIndex: 1, endIndex: 1, lower: 2, upper: 4 }
+ expect(getThresholdZoneXBounds(run, data, false)).toEqual({ x1: 1, x2: 2 })
+ })
+
+ it('aligns thresholds with the configured timestamp axis', () => {
+ const run = { startIndex: 1, endIndex: 2, lower: 2, upper: 4 }
+ expect(getThresholdZoneXBounds(run, data, true, 'timestamp')).toEqual({ x1: 2000, x2: 3000 })
+ expect(getThresholdZoneXBounds(run, data, false, 'timestamp')).toEqual({ x1: 2000, x2: 4000 })
+ })
+})
+
+describe('highest risk crossed during the selected range', () => {
+ const WARNING = 0
+ const PROBLEMATIC = 1
+ const SEVERE = 2
+ const makeRiskZones = (thresholds: number[], endIndex = 0) =>
+ thresholds.map((lower) => ({
+ runs: [{ startIndex: 0, endIndex, lower, upper: 100 }],
+ }))
+ const zones = makeRiskZones([50, 80, 90])
+
+ it.each([
+ { value: 0, expected: undefined },
+ { value: 49, expected: undefined },
+ { value: 50, expected: undefined },
+ { value: 51, expected: WARNING },
+ { value: 80, expected: WARNING },
+ { value: 81, expected: PROBLEMATIC },
+ { value: 90, expected: PROBLEMATIC },
+ { value: 91, expected: SEVERE },
+ ])(
+ 'shows only the highest threshold exceeded by a commitment of $value',
+ ({ value, expected }) => {
+ expect(getHighestCrossedThresholdZone([{ memory: value }], zones, 'memory')).toBe(expected)
+ }
+ )
+
+ it('keeps a historical Severe warning visible after commitment recovers', () => {
+ const data = [{ memory: 95 }, { memory: 40 }]
+ expect(getHighestCrossedThresholdZone(data, makeRiskZones([50, 80, 90], 1), 'memory')).toBe(
+ SEVERE
+ )
+ })
+
+ it('evaluates historical risk against capacity at that timestamp', () => {
+ const historicalZones = [50, 80, 90].map((lower) => ({
+ runs: [
+ { startIndex: 0, endIndex: 0, lower, upper: 200 },
+ { startIndex: 1, endIndex: 1, lower: lower * 2, upper: 200 },
+ ],
+ }))
+ expect(
+ getHighestCrossedThresholdZone([{ memory: 45 }, { memory: 125 }], historicalZones, 'memory')
+ ).toBe(WARNING)
+ })
+
+ it('never treats the gray capacity line as a risk warning', () => {
+ const zones = [50, 80, 90, 100].map((lower) => ({
+ runs: [{ startIndex: 0, endIndex: 0, lower, upper: lower }],
+ isAlwaysVisible: lower === 100,
+ }))
+
+ expect(getHighestCrossedThresholdZone([{ memory: 125 }], zones, 'memory')).toBe(SEVERE)
+ expect(getHighestCrossedThresholdZone([{ memory: 125 }], [zones[3]], 'memory')).toBeUndefined()
+ })
+})
+
+describe('axis capacity and observed peaks', () => {
+ const zones = [
+ { runs: [{ startIndex: 0, endIndex: 0, lower: 50, upper: 80 }] },
+ { runs: [{ startIndex: 0, endIndex: 0, lower: 80, upper: 90 }] },
+ { runs: [{ startIndex: 0, endIndex: 0, lower: 90, upper: 100 }] },
+ ]
+
+ it('keeps earlier high-capacity history visible after downsizing', () => {
+ expect(
+ getThresholdZoneMaximum([
+ {
+ runs: [
+ { startIndex: 0, endIndex: 0, lower: 180, upper: 200 },
+ { startIndex: 1, endIndex: 1, lower: 90, upper: 100 },
+ ],
+ },
+ ])
+ ).toBe(200)
+ })
+
+ it('keeps above-capacity commitment peaks visible', () => {
+ expect(
+ getThresholdZoneMaximum([
+ ...zones,
+ { runs: [{ startIndex: 0, endIndex: 0, lower: 90, upper: 120 }] },
+ ])
+ ).toBe(120)
+ })
+})
+
+describe('visible threshold selection', () => {
+ const data = [{ memory: 60 }]
+ const zones: ThresholdZone[] = [50, 80, 90, 100].map((threshold) => ({
+ label: threshold === 100 ? 'Full commitment capacity' : `${threshold}% threshold`,
+ color: 'var(--chart-reference)',
+ tooltip: '',
+ isAlwaysVisible: threshold === 100,
+ getRanges: () => [[threshold, threshold]],
+ }))
+
+ it('shows the crossed threshold and gray capacity line without shrinking the scale', () => {
+ const chart = getThresholdZoneChart(data, zones, 'memory')
+
+ expect(chart.zones.map((zone) => zone.label)).toEqual([
+ '50% threshold',
+ 'Full commitment capacity',
+ ])
+ expect(chart.selectedZone?.label).toBe('50% threshold')
+ expect(chart.maxValue).toBe(100)
+ })
+})
+
+describe('values for a single sample', () => {
+ const threshold: ThresholdZone = {
+ label: 'Problematic',
+ tooltipLabel: '80% threshold',
+ color: 'var(--color-orange-900)',
+ tooltip: '',
+ getRanges: (data) =>
+ data.map((point) => [Number(point.capacity) * 0.8, Number(point.capacity)]),
+ }
+ const capacity: ThresholdZone = {
+ label: 'Full commitment capacity',
+ color: 'var(--chart-reference)',
+ tooltip: '',
+ getRanges: (data) => data.map((point) => [Number(point.capacity), Number(point.capacity)]),
+ }
+
+ it.each([
+ { capacityValue: 100, expectedThreshold: 80 },
+ { capacityValue: 200, expectedThreshold: 160 },
+ ])(
+ 'shows the timestamp-specific threshold value after capacity changes to $capacityValue',
+ ({ capacityValue, expectedThreshold }) => {
+ expect(getThresholdZoneValues({ capacity: capacityValue }, [threshold, capacity])).toEqual([
+ { label: '80% threshold', color: threshold.color, value: expectedThreshold },
+ { label: 'Full commitment capacity', color: capacity.color, value: capacityValue },
+ ])
+ }
+ )
+})
+
+describe('threshold connections at infrastructure changes', () => {
+ it.each([
+ { before: 8, after: 2 },
+ { before: 2, after: 8 },
+ ])(
+ 'connects adjacent capacity levels from $before to $after so resizing stays visible',
+ ({ before, after }) => {
+ const previous = { startIndex: 0, endIndex: 1, lower: before, upper: before }
+ const current = { startIndex: 2, endIndex: 3, lower: after, upper: after }
+
+ expect(getThresholdZoneYBounds(current, previous)).toEqual({ y1: after, y2: before })
+ }
+ )
+
+ it('leaves a real gap disconnected instead of implying continuous capacity history', () => {
+ const previous = { startIndex: 0, endIndex: 1, lower: 8, upper: 8 }
+ const current = { startIndex: 3, endIndex: 4, lower: 2, upper: 2 }
+
+ expect(getThresholdZoneYBounds(current, previous)).toEqual({ y1: 2, y2: 2 })
+ })
+})
diff --git a/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.ts b/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.ts
new file mode 100644
index 00000000000..ef07560f95c
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ComposedChartThresholdZones.utils.ts
@@ -0,0 +1,140 @@
+import type { DataKey } from 'recharts/types/util/types'
+
+import type { Datum } from './Charts.types'
+import type { ThresholdZone } from './ComposedChart.utils'
+
+export type ThresholdZoneRun = {
+ startIndex: number
+ endIndex: number
+ lower: number
+ upper: number
+}
+
+export function getThresholdZoneRuns(ranges: ([number, number] | null)[]): ThresholdZoneRun[] {
+ return ranges.reduce<ThresholdZoneRun[]>((runs, range, index) => {
+ if (!range) return runs
+
+ const previous = runs[runs.length - 1]
+ if (
+ previous?.endIndex === index - 1 &&
+ previous.lower === range[0] &&
+ previous.upper === range[1]
+ ) {
+ previous.endIndex = index
+ return runs
+ }
+
+ runs.push({ startIndex: index, endIndex: index, lower: range[0], upper: range[1] })
+ return runs
+ }, [])
+}
+
+export function getThresholdZoneXBounds(
+ run: ThresholdZoneRun,
+ data: Datum[],
+ hasVisibleBars: boolean,
+ dataKey?: DataKey<Datum>
+) {
+ const getValue = (index: number): string | number | undefined => {
+ if (dataKey === undefined) return index
+ if (typeof dataKey === 'function') return dataKey(data[index])
+ return data[index]?.[dataKey]
+ }
+
+ const endIndex = hasVisibleBars ? run.endIndex : run.endIndex + 1
+ return {
+ x1: run.startIndex === 0 ? undefined : getValue(run.startIndex),
+ x2: run.endIndex === data.length - 1 ? undefined : getValue(endIndex),
+ }
+}
+
+export function getThresholdZoneYBounds(run: ThresholdZoneRun, previousRun?: ThresholdZoneRun) {
+ if (!previousRun || previousRun.endIndex !== run.startIndex - 1) {
+ return { y1: run.lower, y2: run.lower }
+ }
+ return { y1: run.lower, y2: previousRun.lower }
+}
+
+export function getHighestCrossedThresholdZone(
+ data: Datum[],
+ zones: { runs: ThresholdZoneRun[]; isAlwaysVisible?: boolean }[],
+ attribute?: string
+): number | undefined {
+ if (!attribute) return undefined
+
+ for (let zoneIndex = zones.length - 1; zoneIndex >= 0; zoneIndex--) {
+ if (zones[zoneIndex].isAlwaysVisible) continue
+ for (const run of zones[zoneIndex].runs) {
+ if (!Number.isFinite(run.lower)) continue
+ for (let sampleIndex = run.startIndex; sampleIndex <= run.endIndex; sampleIndex++) {
+ const value = data[sampleIndex]?.[attribute]
+ if (
+ typeof value === 'number' &&
+ Number.isFinite(value) &&
+ value >= 0 &&
+ value > run.lower
+ ) {
+ return zoneIndex
+ }
+ }
+ }
+ }
+ return undefined
+}
+
+export function getThresholdZoneMaximum(zones: { runs: ThresholdZoneRun[] }[]): number {
+ return zones.reduce(
+ (maximum, zone) =>
+ zone.runs.reduce(
+ (zoneMaximum, run) =>
+ Number.isFinite(run.upper) ? Math.max(zoneMaximum, run.upper) : zoneMaximum,
+ maximum
+ ),
+ 0
+ )
+}
+
+export function getThresholdZoneChart(
+ data: Datum[],
+ thresholdZones?: ThresholdZone[],
+ thresholdZoneAttribute?: string
+) {
+ const zones =
+ thresholdZones?.map((zone) => ({
+ ...zone,
+ runs: getThresholdZoneRuns(zone.getRanges(data)),
+ })) ?? []
+ const selectedIndex = getHighestCrossedThresholdZone(data, zones, thresholdZoneAttribute)
+ const selectedZone = selectedIndex === undefined ? undefined : zones[selectedIndex]
+ let visibleZones = zones
+ if (thresholdZoneAttribute) {
+ visibleZones = zones.filter((zone) => zone.isAlwaysVisible || zone === selectedZone)
+ }
+ const maxValue = getThresholdZoneMaximum(zones)
+ return { zones: visibleZones, maxValue, selectedZone }
+}
+
+type ThresholdZoneValue = {
+ label: string
+ color: string
+ value: number
+}
+
+export function getThresholdZoneValues(
+ point: Datum | undefined,
+ zones: ThresholdZone[] | undefined
+): ThresholdZoneValue[] {
+ if (!point || !zones) return []
+
+ const values: ThresholdZoneValue[] = []
+ for (const zone of zones) {
+ const range = zone.getRanges([point])[0]
+ if (!range) continue
+
+ const [value] = range
+ if (!Number.isFinite(value)) continue
+
+ values.push({ label: zone.tooltipLabel ?? zone.label, color: zone.color, value })
+ }
+ return values
+}
diff --git a/apps/studio/components/ui/Charts/ThresholdZoneLine.test.tsx b/apps/studio/components/ui/Charts/ThresholdZoneLine.test.tsx
new file mode 100644
index 00000000000..f6f4d8fc437
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ThresholdZoneLine.test.tsx
@@ -0,0 +1,20 @@
+import { render } from '@testing-library/react'
+import { expect, it } from 'vitest'
+
+import { ThresholdZoneLine } from './ThresholdZoneLine'
+
+it.each([
+ { isRising: false, expectedPath: 'M 100 20 V 80 H 300' },
+ { isRising: true, expectedPath: 'M 100 80 V 20 H 300' },
+])(
+ 'draws a vertical resize connection before continuing right when rising is $isRising',
+ ({ isRising, expectedPath }) => {
+ const { container } = render(
+ <svg>
+ <ThresholdZoneLine x={100} y={20} width={200} height={60} isRising={isRising} />
+ </svg>
+ )
+
+ expect(container.querySelector('path')).toHaveAttribute('d', expectedPath)
+ }
+)
diff --git a/apps/studio/components/ui/Charts/ThresholdZoneLine.tsx b/apps/studio/components/ui/Charts/ThresholdZoneLine.tsx
new file mode 100644
index 00000000000..2a8fcd1e710
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ThresholdZoneLine.tsx
@@ -0,0 +1,26 @@
+import type { Props as RectangleProps } from 'recharts/types/shape/Rectangle'
+
+export const ThresholdZoneLine = ({
+ x = 0,
+ y = 0,
+ width = 0,
+ height = 0,
+ stroke,
+ strokeOpacity,
+ clipPath,
+ label,
+ isRising = false,
+}: RectangleProps & { label?: string; isRising?: boolean }) => (
+ <path
+ clipPath={clipPath}
+ d={`M ${x} ${isRising ? y + height : y} V ${isRising ? y : y + height} H ${x + width}`}
+ fill="none"
+ stroke={stroke}
+ strokeOpacity={strokeOpacity}
+ strokeWidth={1}
+ pointerEvents="none"
+ strokeDasharray="4 4"
+ >
+ {label && <title>{label}</title>}
+ </path>
+)
diff --git a/apps/studio/components/ui/DevToolbar/MetricsTab.test.tsx b/apps/studio/components/ui/DevToolbar/MetricsTab.test.tsx
new file mode 100644
index 00000000000..cfa22199e51
--- /dev/null
+++ b/apps/studio/components/ui/DevToolbar/MetricsTab.test.tsx
@@ -0,0 +1,38 @@
+import { act, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterAll, expect, it, vi } from 'vitest'
+
+import { MetricsTab } from './MetricsTab'
+import { setMemoryCommitmentPreview } from '@/state/metrics-preview'
+
+vi.hoisted(() => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'local')
+})
+
+afterAll(() => vi.unstubAllEnvs())
+
+it('keeps the simulation selected when reopening the toolbar and lets users return to Default', async () => {
+ const user = userEvent.setup()
+ const first = render(<MetricsTab />)
+
+ try {
+ expect(screen.getByRole('combobox', { name: 'Memory commitment' })).toHaveTextContent(
+ 'Default (real data)'
+ )
+ await user.click(screen.getByRole('combobox', { name: 'Memory commitment' }))
+ await user.click(screen.getByRole('option', { name: 'Warn' }))
+ expect(screen.getByText('Simulated data is active for this project.')).toBeInTheDocument()
+
+ first.unmount()
+ render(<MetricsTab />)
+ expect(screen.getByRole('combobox', { name: 'Memory commitment' })).toHaveTextContent('Warn')
+ await user.click(screen.getByRole('combobox', { name: 'Memory commitment' }))
+ await user.click(screen.getByRole('option', { name: 'Default (real data)' }))
+ expect(screen.getByRole('combobox', { name: 'Memory commitment' })).toHaveTextContent(
+ 'Default (real data)'
+ )
+ expect(screen.queryByText('Simulated data is active for this project.')).not.toBeInTheDocument()
+ } finally {
+ act(() => setMemoryCommitmentPreview('default', 'default'))
+ }
+})
diff --git a/apps/studio/components/ui/DevToolbar/MetricsTab.tsx b/apps/studio/components/ui/DevToolbar/MetricsTab.tsx
new file mode 100644
index 00000000000..b397da36720
--- /dev/null
+++ b/apps/studio/components/ui/DevToolbar/MetricsTab.tsx
@@ -0,0 +1,55 @@
+'use client'
+
+import { useParams } from 'common'
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from 'ui'
+
+import { setMemoryCommitmentPreview, useMemoryCommitmentPreview } from '@/state/metrics-preview'
+
+const env = process.env.NEXT_PUBLIC_ENVIRONMENT
+const IS_ENABLED = env === 'local' || env === 'staging'
+const OPTIONS = [
+ { value: 'default', label: 'Default (real data)' },
+ { value: 'warn', label: 'Warn' },
+ { value: 'problematic', label: 'Problematic' },
+ { value: 'severe', label: 'Severe' },
+] as const
+
+export const MetricsTab = () => {
+ const { ref } = useParams()
+ const preview = useMemoryCommitmentPreview(ref)
+ if (!IS_ENABLED) return null
+
+ const handlePreviewChange = (value: string) => {
+ const option = OPTIONS.find((option) => option.value === value)
+ if (ref && option) setMemoryCommitmentPreview(ref, option.value)
+ }
+
+ return (
+ <div className="space-y-4 p-6">
+ <p className="text-sm text-foreground-light">
+ Preview metrics with simulated data. Default restores real data.
+ </p>
+ {!ref && <p className="text-xs text-foreground-muted">Open a project to preview metrics.</p>}
+ <div className="flex items-center justify-between gap-4">
+ <label htmlFor="memory-commitment-preview" className="text-sm text-foreground-light">
+ Memory commitment
+ </label>
+ <Select value={preview} onValueChange={handlePreviewChange} disabled={!ref}>
+ <SelectTrigger id="memory-commitment-preview" className="w-44 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {preview !== 'default' && (
+ <p className="text-xs text-warning-600">Simulated data is active for this project.</p>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/DevToolbar/MetricsTab.utils.test.ts b/apps/studio/components/ui/DevToolbar/MetricsTab.utils.test.ts
new file mode 100644
index 00000000000..1aeb533a66c
--- /dev/null
+++ b/apps/studio/components/ui/DevToolbar/MetricsTab.utils.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { memoryCommitmentThresholds } from '@/components/ui/Charts/Charts.test-fixtures'
+import {
+ getHighestCrossedThresholdZone,
+ getThresholdZoneRuns,
+} from '@/components/ui/Charts/ComposedChartThresholdZones.utils'
+
+beforeEach(() => vi.resetModules())
+afterEach(() => vi.unstubAllEnvs())
+
+const START = '2026-10-16T10:00:00Z'
+const END = '2026-10-16T11:00:00Z'
+const GIB = 1024 ** 3
+
+describe('memory commitment preview fixtures', () => {
+ it.each([
+ { preview: 'warn', expectedBadge: 'Warning' },
+ { preview: 'problematic', expectedBadge: 'Problematic' },
+ { preview: 'severe', expectedBadge: 'Severe' },
+ ] as const)(
+ 'makes $preview trigger the expected warning even when infrastructure capacity changes',
+ async ({ preview, expectedBadge }) => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'staging')
+ const { getMemoryCommitmentPreviewData } = await import('./MetricsTab.utils')
+ const data = getMemoryCommitmentPreviewData(preview, START, END)
+ expect(data).toBeDefined()
+ if (!data) throw new Error('Expected fixture data')
+
+ const zones = memoryCommitmentThresholds.map((zone) => ({
+ ...zone,
+ runs: getThresholdZoneRuns(zone.getRanges(data)),
+ }))
+ const selectedIndex = getHighestCrossedThresholdZone(data, zones, 'ram_commit_used')
+ const selectedZone = selectedIndex === undefined ? undefined : zones[selectedIndex]
+ expect(selectedZone?.badgeLabel).toBe(expectedBadge)
+ expect(data[0].period_start).toBe(new Date(START).toISOString())
+ expect(data.at(-1)?.period_start).toBe(new Date(END).toISOString())
+ const capacityZone = memoryCommitmentThresholds.find((zone) => zone.isAlwaysVisible)
+ if (!capacityZone) throw new Error('Expected the full capacity threshold')
+ const capacity = capacityZone.getRanges(data)
+ expect(capacity[0]).toEqual([9 * GIB, 9 * GIB])
+ expect(capacity.at(-1)).toEqual([3 * GIB, 3 * GIB])
+ }
+ )
+
+ it('stops supplying simulated data when Default is selected', async () => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'local')
+ const { getMemoryCommitmentPreviewData } = await import('./MetricsTab.utils')
+
+ expect(getMemoryCommitmentPreviewData('default', START, END)).toBeUndefined()
+ })
+
+ it.each(['prod', 'preview'])(
+ 'prevents simulated metrics from replacing real data in %s',
+ async (environment) => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', environment)
+ const { getMemoryCommitmentPreviewData } = await import('./MetricsTab.utils')
+ expect(getMemoryCommitmentPreviewData('severe', START, END)).toBeUndefined()
+ }
+ )
+})
diff --git a/apps/studio/components/ui/DevToolbar/MetricsTab.utils.ts b/apps/studio/components/ui/DevToolbar/MetricsTab.utils.ts
new file mode 100644
index 00000000000..1f051ad2aa9
--- /dev/null
+++ b/apps/studio/components/ui/DevToolbar/MetricsTab.utils.ts
@@ -0,0 +1,28 @@
+import type { DataPoint } from '@/data/analytics/constants'
+import type { MemoryCommitmentPreview } from '@/state/metrics-preview'
+
+const env = process.env.NEXT_PUBLIC_ENVIRONMENT
+const IS_ENABLED = env === 'local' || env === 'staging'
+const GIB = 1024 ** 3
+const FRACTIONS = { warn: 0.65, problematic: 0.85, severe: 0.95 }
+
+export function getMemoryCommitmentPreviewData(
+ preview: MemoryCommitmentPreview,
+ startDate: string | undefined,
+ endDate: string | undefined
+): DataPoint[] | undefined {
+ if (!IS_ENABLED || preview === 'default' || !startDate || !endDate) return undefined
+ const start = Date.parse(startDate)
+ const end = Date.parse(endDate)
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return undefined
+
+ return Array.from({ length: 40 }, (_, index) => {
+ const physicalMemory = (index < 20 ? 8 : 2) * GIB
+ const fraction = FRACTIONS[preview] + Math.sin(index / 3) * 0.015
+ return {
+ period_start: new Date(start + ((end - start) * index) / 39).toISOString(),
+ ram_commit_limit: GIB + physicalMemory / 2,
+ ram_commit_used: GIB + physicalMemory * fraction,
+ }
+ })
+}
diff --git a/apps/studio/data/analytics/infra-monitoring-queries.test.ts b/apps/studio/data/analytics/infra-monitoring-queries.test.ts
index 504bab80a7d..472378f3947 100644
--- a/apps/studio/data/analytics/infra-monitoring-queries.test.ts
+++ b/apps/studio/data/analytics/infra-monitoring-queries.test.ts
@@ -289,6 +289,24 @@ describe('2m interval aggregation', () => {
})
describe('aggregate1MinTo2Min', () => {
+ it('keeps commitment available when its capacity is missing from part of the bucket', () => {
+ const GIB = 1024 ** 3
+ const result = aggregate1MinTo2Min(
+ [
+ {
+ period_start: '2024-01-02T03:00:00Z',
+ ram_commit_used: 4 * GIB,
+ ram_commit_limit: 5 * GIB,
+ },
+ { period_start: '2024-01-02T03:01:00Z', ram_commit_used: 4 * GIB },
+ ],
+ 'ram_commit_used'
+ )
+
+ expect(result[0].ram_commit_used).toBe(4 * GIB)
+ expect(result[0].ram_commit_limit).toBeUndefined()
+ })
+
it('aggregates 1-minute data points into 2-minute buckets with correct averages', () => {
const dataPoints = [
{
diff --git a/apps/studio/data/analytics/infra-monitoring-queries.ts b/apps/studio/data/analytics/infra-monitoring-queries.ts
index 2d1ad996a18..85925568716 100644
--- a/apps/studio/data/analytics/infra-monitoring-queries.ts
+++ b/apps/studio/data/analytics/infra-monitoring-queries.ts
@@ -40,7 +40,8 @@ export function useInfraMonitoringQueries(
interval: AnalyticsInterval,
databaseIdentifier: string | undefined,
data: unknown,
- isVisible: boolean
+ isVisible: boolean,
+ preserveMissingAttribute?: string
) {
const shouldFetch = data === undefined && isVisible
const hasAttributes = attributes.length > 0
@@ -59,8 +60,8 @@ export function useInfraMonitoringQueries(
const seriesByAttribute = useMemo(() => {
if (!query.data) return undefined
- return mapResponseToAnalyticsData(query.data, attributes)
- }, [query.data, attributes])
+ return mapResponseToAnalyticsData(query.data, attributes, undefined, preserveMissingAttribute)
+ }, [query.data, attributes, preserveMissingAttribute])
if (!hasAttributes) {
return []
@@ -84,14 +85,22 @@ type AggregatedBucket = {
period_start: string
periodStartFormatted: string
_counts: Record<string, number>
- [key: string]: string | number | Record<string, number>
+ _missingAttributes: Set<string>
+ [key: string]: string | number | Set<string> | Record<string, number>
}
type DataPointWithFormatted = DataPoint & {
periodStartFormatted: string
}
-export const aggregate1MinTo2Min = (dataPoints: DataPoint[]): DataPointWithFormatted[] => {
+function shouldPreserveMissingAttribute(attribute: string, preserveMissingAttribute?: string) {
+ return attribute === 'ram_commit_limit' || attribute === preserveMissingAttribute
+}
+
+export const aggregate1MinTo2Min = (
+ dataPoints: DataPoint[],
+ preserveMissingAttribute?: string
+): DataPointWithFormatted[] => {
const aggregated = new Map<string, AggregatedBucket>()
const valueKeys = new Set<string>()
@@ -119,6 +128,7 @@ export const aggregate1MinTo2Min = (dataPoints: DataPoint[]): DataPointWithForma
period_start: bucketKey,
periodStartFormatted: twoMinBucket.format('HH:mm DD MMM'),
_counts: Object.fromEntries(Array.from(valueKeys).map((key) => [key, 0])),
+ _missingAttributes: new Set(),
}
// Initialize all value keys to 0
valueKeys.forEach((key) => {
@@ -130,6 +140,12 @@ export const aggregate1MinTo2Min = (dataPoints: DataPoint[]): DataPointWithForma
const bucket = aggregated.get(bucketKey)!
valueKeys.forEach((key) => {
const value = point[key]
+ if (
+ shouldPreserveMissingAttribute(key, preserveMissingAttribute) &&
+ typeof value !== 'number'
+ ) {
+ bucket._missingAttributes.add(key)
+ }
if (typeof value === 'number') {
const currentValue = typeof bucket[key] === 'number' ? bucket[key] : 0
bucket[key] = currentValue + value
@@ -140,12 +156,17 @@ export const aggregate1MinTo2Min = (dataPoints: DataPoint[]): DataPointWithForma
// Calculate averages
const result: DataPointWithFormatted[] = Array.from(aggregated.values()).map((bucket) => {
- const { _counts, period_start, periodStartFormatted, ...rest } = bucket
+ const { _counts, _missingAttributes, period_start, periodStartFormatted, ...rest } = bucket
const averaged: DataPointWithFormatted = {
period_start,
periodStartFormatted,
}
valueKeys.forEach((key) => {
+ if (
+ shouldPreserveMissingAttribute(key, preserveMissingAttribute) &&
+ (_missingAttributes.has(key) || _counts[key] === 0)
+ )
+ return
if (_counts[key] > 0) {
const restValue = rest[key]
averaged[key] = typeof restValue === 'number' ? restValue / _counts[key] : 0
@@ -162,7 +183,8 @@ export const aggregate1MinTo2Min = (dataPoints: DataPoint[]): DataPointWithForma
export function mapResponseToAnalyticsData(
response: InfraMonitoringMultiData,
attributes: InfraMonitoringAttribute[],
- dateFormat: string = DEFAULT_DATE_FORMAT
+ dateFormat: string = DEFAULT_DATE_FORMAT,
+ preserveMissingAttribute?: string
): Record<string, AnalyticsData> {
const needs2MinAggregation = (response as { _originalInterval?: '2m' })._originalInterval === '2m'
@@ -174,15 +196,20 @@ export function mapResponseToAnalyticsData(
let dataPoints = response.data.map((point) => {
const value = point.values?.[attribute]
- return {
+ const dataPoint: DataPointWithFormatted = {
period_start: point.period_start,
periodStartFormatted: dayjs(point.period_start).format(dateFormat),
- [attribute]: value === undefined ? 0 : Number(value),
}
+ const numericValue = Number(value ?? 0)
+ const isMissingPreservedValue =
+ shouldPreserveMissingAttribute(attribute, preserveMissingAttribute) &&
+ (value == null || !Number.isFinite(numericValue))
+ if (!isMissingPreservedValue) dataPoint[attribute] = numericValue
+ return dataPoint
})
if (needs2MinAggregation) {
- dataPoints = aggregate1MinTo2Min(dataPoints)
+ dataPoints = aggregate1MinTo2Min(dataPoints, preserveMissingAttribute)
}
acc[attribute] = {
@@ -205,15 +232,20 @@ export function mapResponseToAnalyticsData(
let dataPoints = singleResponse.data.map((point) => {
const value = point[attribute]
- return {
+ const dataPoint: DataPointWithFormatted = {
period_start: point.period_start,
periodStartFormatted: dayjs(point.period_start).format(dateFormat),
- [attribute]: value === undefined ? 0 : Number(value),
}
+ const numericValue = Number(value ?? 0)
+ const isMissingPreservedValue =
+ shouldPreserveMissingAttribute(attribute, preserveMissingAttribute) &&
+ (value == null || !Number.isFinite(numericValue))
+ if (!isMissingPreservedValue) dataPoint[attribute] = numericValue
+ return dataPoint
})
if (needs2MinAggregation) {
- dataPoints = aggregate1MinTo2Min(dataPoints)
+ dataPoints = aggregate1MinTo2Min(dataPoints, preserveMissingAttribute)
}
return {
diff --git a/apps/studio/data/reports/database-charts.test.ts b/apps/studio/data/reports/database-charts.test.ts
index e71d56beb17..7360fb0fe6d 100644
--- a/apps/studio/data/reports/database-charts.test.ts
+++ b/apps/studio/data/reports/database-charts.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from 'vitest'
import { getReportAttributesV2, shouldShowDiskIOBurstBalanceChart } from './database-charts'
+import { getThresholdZoneChart } from '@/components/ui/Charts/ComposedChartThresholdZones.utils'
import { RESOURCE_WARNING_MESSAGES } from '@/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.constants'
+import { mapResponseToAnalyticsData } from '@/data/analytics/infra-monitoring-queries'
+import type { InfraMonitoringMultiData } from '@/data/analytics/infra-monitoring-query'
import { Project } from '@/data/projects/project-detail-query'
const PROJECT: Project = {
@@ -162,3 +165,103 @@ describe('resource warning metrics chart IDs', () => {
expect(missingChartIds).toEqual([])
})
})
+
+describe('getReportAttributesV2 memory commitment chart', () => {
+ it.each(['multi', 'single'] as const)(
+ 'prevents missing capacity from turning normal commitment into a Severe warning in 2m %s responses',
+ (format) => {
+ const chart = getReportAttributesV2(ENTITLED_FEATURES, buildProject()).find(
+ (chart) => chart.id === 'memory-commitment'
+ )
+ if (!chart) throw new Error('Expected the memory commitment chart')
+
+ const GIB = 1024 ** 3
+ const samples = [
+ { period_start: '2024-01-02T03:00:00Z', ram_commit_limit: String(5 * GIB) },
+ { period_start: '2024-01-02T03:01:00Z', ram_commit_limit: undefined },
+ { period_start: '2024-01-02T03:02:00Z', ram_commit_limit: String(5 * GIB) },
+ { period_start: '2024-01-02T03:03:00Z', ram_commit_limit: String(5 * GIB) },
+ ].map((sample) => ({ ...sample, ram_commit_used: String(4 * GIB) }))
+ const metadata = { format: 'bytes', total: 0, totalAverage: 0, yAxisLimit: 9 * GIB }
+ const attributes = ['ram_commit_used', 'ram_commit_limit'] as const
+ const mapped = attributes.map((attribute) => {
+ const response: InfraMonitoringMultiData =
+ format === 'multi'
+ ? {
+ _originalInterval: '2m',
+ data: samples.map(({ period_start, ...values }) => ({ period_start, values })),
+ series: { [attribute]: metadata },
+ }
+ : { ...metadata, _originalInterval: '2m', data: samples }
+ return mapResponseToAnalyticsData(
+ response,
+ [attribute],
+ undefined,
+ chart.thresholdZoneAttribute
+ )[attribute].data
+ })
+ const data = mapped[0].map((point, index) => ({ ...point, ...mapped[1][index] }))
+ const guidance = getThresholdZoneChart(
+ data,
+ chart.thresholdZones,
+ chart.thresholdZoneAttribute
+ )
+
+ expect(guidance.selectedZone).toBeUndefined()
+ expect(data[0].ram_commit_limit).toBeUndefined()
+ expect(data.map((point) => point.ram_commit_used)).toEqual([4 * GIB, 4 * GIB])
+ expect(data[1].ram_commit_limit).toBe(5 * GIB)
+ }
+ )
+
+ it.each([true, false])(
+ 'controls risk guidance without hiding the commitment chart when risk zones are %s',
+ (showMemoryCommitmentRiskZones) => {
+ const chart = getReportAttributesV2(
+ ENTITLED_FEATURES,
+ buildProject(),
+ undefined,
+ undefined,
+ undefined,
+ false,
+ false,
+ true,
+ showMemoryCommitmentRiskZones
+ ).find((chart) => chart.id === 'memory-commitment')
+ if (!chart) throw new Error('Expected the memory commitment chart')
+
+ const GIB = 1024 ** 3
+ const guidance = getThresholdZoneChart(
+ [{ ram_commit_limit: 5 * GIB, ram_commit_used: 8.5 * GIB }],
+ chart.thresholdZones,
+ chart.thresholdZoneAttribute
+ )
+
+ expect(chart.hide).toBe(false)
+ expect(guidance.selectedZone?.badgeLabel).toBe(
+ showMemoryCommitmentRiskZones ? 'Severe' : undefined
+ )
+ expect(guidance.zones.map((zone) => zone.label)).toEqual(
+ showMemoryCommitmentRiskZones ? ['Severe', 'Full commitment capacity'] : []
+ )
+ }
+ )
+
+ it('keeps capacity tied to compute size so overcommitment cannot raise the reference', () => {
+ const chart = getReportAttributesV2(ENTITLED_FEATURES, buildProject()).find(
+ (chart) => chart.id === 'memory-commitment'
+ )
+ const capacity = chart?.thresholdZones?.find((zone) => zone.isAlwaysVisible)
+ const GIB = 1024 ** 3
+
+ expect(
+ capacity?.getRanges([
+ { ram_commit_limit: 5 * GIB, ram_commit_used: 12 * GIB },
+ { ram_commit_limit: 2 * GIB, ram_commit_used: 6 * GIB },
+ ])
+ ).toEqual([
+ [9 * GIB, 9 * GIB],
+ [3 * GIB, 3 * GIB],
+ ])
+ })
+})
diff --git a/apps/studio/data/reports/database-charts.ts b/apps/studio/data/reports/database-charts.ts
index 3aabacceff8..ef0f8720a02 100644
--- a/apps/studio/data/reports/database-charts.ts
+++ b/apps/studio/data/reports/database-charts.ts
@@ -1,5 +1,6 @@
import { COMPUTE_DISK, COMPUTE_MAX_IOPS } from 'shared-data'
+import { getMemoryCommitmentRanges } from './database-charts.utils'
import {
hasBurstableIO,
mapComputeSizeNameToAddonVariantId,
@@ -29,7 +30,8 @@ export const getReportAttributesV2: (
pgBouncerMaxConnections?: number,
isSpendCapEnabled?: boolean,
showDiskIOBurstBalanceChart?: boolean,
- showMemoryCommitmentChart?: boolean
+ showMemoryCommitmentChart?: boolean,
+ showMemoryCommitmentRiskZones?: boolean
) => ReportAttributes[] = (
entitledFeatures,
project,
@@ -38,7 +40,8 @@ export const getReportAttributesV2: (
pgBouncerMaxConnections,
isSpendCapEnabled,
showDiskIOBurstBalanceChart,
- showMemoryCommitmentChart
+ showMemoryCommitmentChart,
+ showMemoryCommitmentRiskZones = true
) => {
const computeVariantId = mapComputeSizeNameToAddonVariantId(project?.infra_compute_size)
// High Availability projects run Multigres, whose dedicated pooler is multipooler rather
@@ -123,7 +126,6 @@ export const getReportAttributesV2: (
showLegend: true,
hideChartType: false,
defaultChartStyle: 'bar',
- showMaxValue: true,
showGrid: true,
syncId: 'database-reports',
valuePrecision: 2,
@@ -131,6 +133,51 @@ export const getReportAttributesV2: (
width: 75,
tickFormatter: (value: number) => formatBytesMinMB(value, 2),
},
+ titleTooltip: showMemoryCommitmentRiskZones
+ ? 'Risk thresholds estimate memory commitment risk from physical RAM plus 1 GiB of swap and do not predict when the database will run out of memory.'
+ : undefined,
+ thresholdZoneAttribute: showMemoryCommitmentRiskZones ? 'ram_commit_used' : undefined,
+ thresholdZones: showMemoryCommitmentRiskZones
+ ? [
+ {
+ label: 'Acknowledgment',
+ badgeLabel: 'Warning',
+ tooltipLabel: '50% threshold',
+ color: 'var(--color-yellow-900)',
+ textColor: 'var(--color-yellow-1100)',
+ tooltip:
+ 'Above 50% of physical RAM plus 1 GiB: monitor memory usage and enable memory investigation tools to understand what your database has promised to operations.',
+ getRanges: (data) => getMemoryCommitmentRanges(data, 0.5, 0.8),
+ },
+ {
+ label: 'Problematic',
+ badgeLabel: 'Problematic',
+ tooltipLabel: '80% threshold',
+ color: 'var(--color-orange-900)',
+ textColor: 'var(--color-orange-1100)',
+ tooltip:
+ 'Above 80% of physical RAM plus 1 GiB: optimize memory usage or upgrade compute, since using idle memory commitments at once can exhaust resources and trigger recovery.',
+ getRanges: (data) => getMemoryCommitmentRanges(data, 0.8, 0.9),
+ },
+ {
+ label: 'Severe',
+ badgeLabel: 'Severe',
+ tooltipLabel: '90% threshold',
+ color: 'hsl(var(--destructive-600))',
+ tooltip:
+ 'Above 90% of physical RAM plus 1 GiB: simultaneous use of promised memory creates a high risk of an unexpected crash and recovery, so optimize memory usage or upgrade compute.',
+ getRanges: (data) => getMemoryCommitmentRanges(data, 0.9),
+ },
+ {
+ label: 'Full commitment capacity',
+ color: 'var(--chart-reference)',
+ isAlwaysVisible: true,
+ tooltip:
+ 'Estimated physical RAM plus 1 GiB of swap, based on the infrastructure capacity at each timestamp.',
+ getRanges: (data) => getMemoryCommitmentRanges(data, 1, 1),
+ },
+ ]
+ : undefined,
attributes: [
{
attribute: 'ram_commit_used',
@@ -139,17 +186,13 @@ export const getReportAttributesV2: (
color: 'var(--chart-1)',
fill: 'var(--chart-1-fill)',
tooltip:
- 'Total memory the kernel has promised to processes (RAM plus swap). Sustained values near or above the commit limit indicate overcommitment and a high risk of out-of-memory failures',
+ 'Memory the kernel has promised to processes, which may remain unused until needed and does not by itself indicate an out-of-memory failure',
},
{
attribute: 'ram_commit_limit',
provider: 'infra-monitoring',
- label: 'Commit limit',
- color: 'var(--chart-reference)',
- isMaxValue: true,
+ enabled: false,
omitFromTotal: true,
- tooltip:
- 'Maximum memory the kernel will commit (RAM plus swap, adjusted by the overcommit ratio). Committed memory approaching this limit puts the database at risk of being killed when the system runs out of memory',
},
],
},
diff --git a/apps/studio/data/reports/database-charts.utils.test.ts b/apps/studio/data/reports/database-charts.utils.test.ts
new file mode 100644
index 00000000000..a0e62729884
--- /dev/null
+++ b/apps/studio/data/reports/database-charts.utils.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+
+import { getMemoryCommitmentRanges } from './database-charts.utils'
+
+const GIB = 1024 ** 3
+
+const pointForMemory = (physicalMemoryGiB: number, committedGiB = 0) => ({
+ ram_commit_limit: (1 + physicalMemoryGiB / 2) * GIB,
+ ram_commit_used: committedGiB * GIB,
+})
+
+describe('getMemoryCommitmentRanges', () => {
+ it.each([
+ [0.5, 0.8, 5, 7.4],
+ [0.8, 0.9, 7.4, 8.2],
+ [0.9, undefined, 8.2, 9],
+ ])(
+ 'derives the %s threshold from physical RAM rather than the commit limit',
+ (lower, upper, expectedLower, expectedUpper) => {
+ const ranges = getMemoryCommitmentRanges([pointForMemory(8)], lower, upper)
+
+ expect(ranges).toEqual([[expectedLower * GIB, expectedUpper * GIB]])
+ }
+ )
+
+ it('uses historical compute size so resizing does not rewrite earlier thresholds', () => {
+ expect(getMemoryCommitmentRanges([pointForMemory(2), pointForMemory(8)], 0.5, 0.8)).toEqual([
+ [2 * GIB, 2.6 * GIB],
+ [5 * GIB, 7.4 * GIB],
+ ])
+ })
+
+ it('keeps commitments above capacity visible instead of clipping the chart', () => {
+ expect(getMemoryCommitmentRanges([pointForMemory(8, 12), pointForMemory(8, 6)], 0.9)).toEqual([
+ [8.2 * GIB, 12 * GIB],
+ [8.2 * GIB, 12 * GIB],
+ ])
+ })
+})
diff --git a/apps/studio/data/reports/database-charts.utils.ts b/apps/studio/data/reports/database-charts.utils.ts
new file mode 100644
index 00000000000..31223d5aec6
--- /dev/null
+++ b/apps/studio/data/reports/database-charts.utils.ts
@@ -0,0 +1,36 @@
+import type { Datum } from '@/components/ui/Charts/Charts.types'
+
+const SWAP_BYTES = 1024 ** 3
+
+export function getMemoryCommitmentRanges(
+ data: Datum[],
+ lowerFraction: number,
+ upperFraction?: number
+): ([number, number] | null)[] {
+ const maxCommitted = data.reduce((maximum, point) => {
+ const committed = point.ram_commit_used
+ return typeof committed === 'number' && Number.isFinite(committed)
+ ? Math.max(maximum, committed)
+ : maximum
+ }, 0)
+
+ return data.map((point) => {
+ const commitLimit = point.ram_commit_limit
+ if (
+ typeof commitLimit !== 'number' ||
+ !Number.isFinite(commitLimit) ||
+ commitLimit <= SWAP_BYTES
+ ) {
+ return null
+ }
+
+ const physicalMemory = (commitLimit - SWAP_BYTES) * 2
+ const lower = SWAP_BYTES + physicalMemory * lowerFraction
+ const upper =
+ upperFraction === undefined
+ ? Math.max(SWAP_BYTES + physicalMemory, maxCommitted)
+ : SWAP_BYTES + physicalMemory * upperFraction
+
+ return [lower, upper]
+ })
+}
diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsx
index 8a88cd05d20..9d51e5ea18e 100644
--- a/apps/studio/pages/_app.tsx
+++ b/apps/studio/pages/_app.tsx
@@ -91,8 +91,13 @@ const ProjectStatusTab = IS_DEV_TOOLBAR_ENABLED
)
: () => null
+const MetricsTab = IS_DEV_TOOLBAR_ENABLED
+ ? dynamic(() => import('@/components/ui/DevToolbar/MetricsTab').then((m) => m.MetricsTab))
+ : () => null
+
const devToolbarExtraTabs: ExtraTab[] = IS_DEV_TOOLBAR_ENABLED
? [
+ { id: 'metrics', label: 'Metrics', content: <MetricsTab /> },
{ id: 'warnings', label: 'Warnings', content: <ResourceWarningsTab /> },
{ id: 'project-status', label: 'Project Status', content: <ProjectStatusTab /> },
]
diff --git a/apps/studio/pages/project/[ref]/observability/database.tsx b/apps/studio/pages/project/[ref]/observability/database.tsx
index b0756b0cbad..9d9a6f2c314 100644
--- a/apps/studio/pages/project/[ref]/observability/database.tsx
+++ b/apps/studio/pages/project/[ref]/observability/database.tsx
@@ -26,6 +26,7 @@ import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import type { MultiAttribute } from '@/components/ui/Charts/ComposedChart.utils'
import { LazyComposedChartHandler } from '@/components/ui/Charts/ComposedChartHandler'
import { ReportSettings } from '@/components/ui/Charts/ReportSettings'
+import { getMemoryCommitmentPreviewData } from '@/components/ui/DevToolbar/MetricsTab.utils'
import { DocsButton } from '@/components/ui/DocsButton'
import { ObservabilityLink } from '@/components/ui/ObservabilityLink'
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
@@ -46,6 +47,7 @@ import { useIsHighAvailability, useSelectedProjectQuery } from '@/hooks/misc/use
import { DOCS_URL } from '@/lib/constants'
import { formatBytes } from '@/lib/helpers'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
+import { useMemoryCommitmentPreview } from '@/state/metrics-preview'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
import type { NextPageWithLayout } from '@/types'
@@ -212,6 +214,13 @@ const DatabaseUsage = () => {
const showDiskIOBurstBalanceChart = useFlag('showDiskIOBurstBalanceChart')
const showMemoryCommitmentChart = useFlag('showMemoryCommitmentChart')
+ const showMemoryCommitmentRiskZones = useFlag('showMemoryCommitmentRiskZones')
+ const memoryCommitmentPreview = useMemoryCommitmentPreview(ref)
+ const memoryCommitmentPreviewData = getMemoryCommitmentPreviewData(
+ memoryCommitmentPreview,
+ selectedDateRange?.period_start?.date,
+ selectedDateRange?.period_end?.date
+ )
const REPORT_ATTRIBUTES = getReportAttributesV2(
entitledFeatures,
@@ -221,7 +230,8 @@ const DatabaseUsage = () => {
defaultMaxClientConn,
isSpendCapEnabled,
showDiskIOBurstBalanceChart,
- showMemoryCommitmentChart
+ showMemoryCommitmentChart,
+ showMemoryCommitmentRiskZones
)
const { isPending: isUpdatingDiskSize } = useProjectDiskResizeMutation({
@@ -339,6 +349,8 @@ const DatabaseUsage = () => {
>
{selectedDateRange &&
REPORT_ATTRIBUTES.filter((chart) => !chart.hide).map((chart) => {
+ const chartPreviewData =
+ chart.id === 'memory-commitment' ? memoryCommitmentPreviewData : undefined
const chartAvailable =
!chart.entitlement ||
isEntitlementLoading ||
@@ -347,6 +359,8 @@ const DatabaseUsage = () => {
<LazyComposedChartHandler
key={chart.id}
{...chart}
+ data={chartPreviewData}
+ highlightedValue={chartPreviewData?.at(-1)?.ram_commit_used}
attributes={chart.attributes as MultiAttribute[]}
interval={selectedDateRange.interval}
startDate={selectedDateRange?.period_start?.date}
diff --git a/apps/studio/routes/__root.tsx b/apps/studio/routes/__root.tsx
index f0fcb8b67b4..5faea5d2c9c 100644
--- a/apps/studio/routes/__root.tsx
+++ b/apps/studio/routes/__root.tsx
@@ -180,8 +180,23 @@ const ProjectStatusTab = IS_DEV_TOOLBAR_ENABLED
)
: () => null
+const MetricsTab = IS_DEV_TOOLBAR_ENABLED
+ ? lazy(() =>
+ import('@/components/ui/DevToolbar/MetricsTab').then((m) => ({ default: m.MetricsTab }))
+ )
+ : () => null
+
const devToolbarExtraTabs: ExtraTab[] = IS_DEV_TOOLBAR_ENABLED
? [
+ {
+ id: 'metrics',
+ label: 'Metrics',
+ content: (
+ <Suspense fallback={null}>
+ <MetricsTab />
+ </Suspense>
+ ),
+ },
{
id: 'warnings',
label: 'Warnings',
diff --git a/apps/studio/state/metrics-preview.test.ts b/apps/studio/state/metrics-preview.test.ts
new file mode 100644
index 00000000000..959e24f8fff
--- /dev/null
+++ b/apps/studio/state/metrics-preview.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+beforeEach(() => vi.resetModules())
+afterEach(() => vi.unstubAllEnvs())
+
+describe('metrics preview environment and project scope', () => {
+ it.each(['local', 'staging'])(
+ 'keeps one project’s simulated metrics from affecting another project in %s',
+ async (environment) => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', environment)
+ const { getMemoryCommitmentPreview, setMemoryCommitmentPreview } =
+ await import('./metrics-preview')
+
+ setMemoryCommitmentPreview('project-a', 'severe')
+ expect(getMemoryCommitmentPreview('project-a')).toBe('severe')
+ expect(getMemoryCommitmentPreview('project-b')).toBe('default')
+ setMemoryCommitmentPreview('project-b', 'warn')
+ setMemoryCommitmentPreview('project-a', 'default')
+ expect(getMemoryCommitmentPreview('project-a')).toBe('default')
+ expect(getMemoryCommitmentPreview('project-b')).toBe('warn')
+ expect(getMemoryCommitmentPreview(undefined)).toBe('default')
+ }
+ )
+
+ it.each(['prod', 'production', 'preview', 'test'])(
+ 'prevents simulated metrics from replacing real data in %s',
+ async (environment) => {
+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', environment)
+ const { getMemoryCommitmentPreview, setMemoryCommitmentPreview } =
+ await import('./metrics-preview')
+
+ setMemoryCommitmentPreview('project-a', 'severe')
+ expect(getMemoryCommitmentPreview('project-a')).toBe('default')
+ }
+ )
+})
diff --git a/apps/studio/state/metrics-preview.ts b/apps/studio/state/metrics-preview.ts
new file mode 100644
index 00000000000..44d053744a2
--- /dev/null
+++ b/apps/studio/state/metrics-preview.ts
@@ -0,0 +1,38 @@
+import { useSyncExternalStore } from 'react'
+
+export type MemoryCommitmentPreview = 'default' | 'warn' | 'problematic' | 'severe'
+
+const env = process.env.NEXT_PUBLIC_ENVIRONMENT
+const IS_ENABLED = env === 'local' || env === 'staging'
+const overrides = new Map<string, MemoryCommitmentPreview>()
+const listeners = new Set<() => void>()
+
+export function getMemoryCommitmentPreview(
+ projectRef: string | undefined
+): MemoryCommitmentPreview {
+ if (!IS_ENABLED || !projectRef) return 'default'
+ return overrides.get(projectRef) ?? 'default'
+}
+
+export function setMemoryCommitmentPreview(projectRef: string, preview: MemoryCommitmentPreview) {
+ if (!IS_ENABLED || !projectRef || getMemoryCommitmentPreview(projectRef) === preview) return
+ if (preview === 'default') overrides.delete(projectRef)
+ else overrides.set(projectRef, preview)
+ listeners.forEach((listener) => listener())
+}
+
+function subscribe(listener: () => void) {
+ if (!IS_ENABLED) return () => {}
+ listeners.add(listener)
+ return () => {
+ listeners.delete(listener)
+ }
+}
+
+export function useMemoryCommitmentPreview(projectRef: string | undefined) {
+ return useSyncExternalStore<MemoryCommitmentPreview>(
+ subscribe,
+ () => getMemoryCommitmentPreview(projectRef),
+ () => 'default'
+ )
+}