@skyhook-io/radar-app 1.21.2 → 1.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +50 -28
  4. package/src/api/actions.test.ts +11 -0
  5. package/src/api/actions.ts +5 -0
  6. package/src/api/apiResources.navigation.test.tsx +58 -0
  7. package/src/api/apiResources.ts +22 -16
  8. package/src/api/client.diagnostics.test.ts +52 -0
  9. package/src/api/client.triggerCronJob.test.tsx +49 -0
  10. package/src/api/client.ts +140 -120
  11. package/src/api/connectionBinding.test.tsx +82 -0
  12. package/src/api/connectionBinding.ts +52 -0
  13. package/src/api/contextSwitch.test.ts +11 -0
  14. package/src/api/contextSwitch.ts +58 -0
  15. package/src/api/radarFeatures.ts +5 -0
  16. package/src/components/ConnectionErrorView.tsx +13 -0
  17. package/src/components/ContextSwitchActions.tsx +43 -0
  18. package/src/components/ContextSwitcher.tsx +13 -6
  19. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  20. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  21. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  22. package/src/components/cost/CostTrendChart.tsx +25 -2
  23. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  24. package/src/components/cost/CostView.tsx +10 -2
  25. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  26. package/src/components/cost/CostViewTabs.tsx +14 -22
  27. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  28. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  29. package/src/components/cost/source.test.ts +16 -1
  30. package/src/components/cost/source.ts +34 -0
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  33. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  34. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  35. package/src/components/dock/TerminalTab.test.tsx +12 -1
  36. package/src/components/dock/TerminalTab.tsx +6 -3
  37. package/src/components/home/CostCard.test.tsx +49 -0
  38. package/src/components/home/CostCard.tsx +98 -63
  39. package/src/components/home/mcpToolCatalog.ts +1 -0
  40. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  41. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  42. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  43. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  44. package/src/components/resource/HPACharts.tsx +34 -1
  45. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  46. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  47. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  48. package/src/components/resource/RestartChart.tsx +31 -3
  49. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  50. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  51. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  52. package/src/components/resource/RightsizingStrip.tsx +27 -300
  53. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  54. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  55. package/src/components/resource/nameMatchedScope.ts +39 -0
  56. package/src/components/resources/pod-file-upload.ts +3 -0
  57. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  58. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  59. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  60. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  61. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  62. package/src/components/rightsizing/model.test.ts +20 -9
  63. package/src/components/rightsizing/model.ts +17 -176
  64. package/src/components/rightsizing/notices.test.tsx +30 -29
  65. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  66. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  67. package/src/components/ui/command-items.ts +3 -4
  68. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  69. package/src/components/useContextSwitchFlow.tsx +43 -5
  70. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  71. package/src/components/workload/WorkloadView.test.ts +22 -1
  72. package/src/components/workload/WorkloadView.tsx +57 -16
  73. package/src/context/ConnectionContext.test.ts +1 -0
  74. package/src/context/ConnectionContext.tsx +58 -15
  75. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  76. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  77. package/src/context/ContextSwitchContext.tsx +15 -1
  78. package/src/context/NavCustomization.tsx +6 -3
  79. package/src/hooks/useEventSource.test.tsx +85 -0
  80. package/src/hooks/useEventSource.ts +43 -16
  81. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  82. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  83. package/src/index.ts +3 -0
  84. package/src/integrations/resourceHosts.test.tsx +1 -1
  85. package/src/integrations/resourceHosts.tsx +2 -0
  86. package/src/utils/navigation.ts +1 -15
  87. package/src/utils/page-links.ts +6 -0
  88. package/src/components/rightsizing/presentation.test.ts +0 -150
  89. package/src/components/rightsizing/presentation.ts +0 -109
@@ -1,104 +1,11 @@
1
1
  import { describe, expect, it } from 'vitest'
2
- import type { RightsizingRow } from '../../api/client'
3
2
  import {
4
- getRightsizingExplanation,
5
- getRightsizingPresentation,
6
- podLevelOverUseNote,
7
3
  RIGHTSIZING_METHODOLOGY,
8
4
  RIGHTSIZING_DOCS_URL,
9
5
  RIGHTSIZING_SUMMARY,
10
6
  } from './RightsizingStrip'
11
7
 
12
- const row = (overrides: Partial<RightsizingRow> = {}): RightsizingRow => ({
13
- container: 'server',
14
- resource: 'cpu',
15
- fit: 'balanced',
16
- confidence: 'high',
17
- sampleCount: 2016,
18
- expectedSamples: 2016,
19
- coverage: 1,
20
- hpaManaged: false,
21
- hpaEvidenceAvailable: true,
22
- oomEvidenceAvailable: true,
23
- throttleAvailable: true,
24
- ...overrides,
25
- })
26
-
27
- describe('rightsizing presentation', () => {
28
- it('keeps fit, confidence, and runtime risk as separate concepts', () => {
29
- expect(getRightsizingPresentation('oversized')).toEqual({
30
- label: 'Oversized',
31
- severity: 'info',
32
- })
33
- expect(getRightsizingPresentation('under_requested')).toEqual({
34
- label: 'Under-requested',
35
- severity: 'warning',
36
- })
37
- expect(getRightsizingPresentation('insufficient_history')).toEqual({
38
- label: 'Insufficient history',
39
- severity: 'neutral',
40
- })
41
- })
42
-
43
- it('labels query failures independently from insufficient history', () => {
44
- expect(getRightsizingPresentation('insufficient_history', 'usage query failed')).toEqual({
45
- label: 'Query failed',
46
- severity: 'error',
47
- })
48
- })
49
-
50
- it('explains why recommendations are withheld without inventing a zero-risk result', () => {
51
- expect(getRightsizingExplanation(row({ recommendationReason: 'hpa_managed' }))).toContain(
52
- 'HPA manages cpu',
53
- )
54
- expect(
55
- getRightsizingExplanation(row({ resource: 'memory', recommendationReason: 'oom_evidence' })),
56
- ).toContain('OOM evidence')
57
- expect(
58
- getRightsizingExplanation(row({ recommendationReason: 'hpa_evidence_unavailable' })),
59
- ).toContain('could not verify HPA')
60
- expect(
61
- getRightsizingExplanation(
62
- row({
63
- resource: 'memory',
64
- recommendationReason: 'oom_evidence_unavailable',
65
- }),
66
- ),
67
- ).toContain('could not verify recent OOM')
68
- expect(getRightsizingExplanation(row({ throttleAvailable: false }))).toContain(
69
- 'throttling metrics are unavailable',
70
- )
71
- })
72
-
73
- it('separates the demand target from a conservative reduction step', () => {
74
- const explanation = getRightsizingExplanation(
75
- row({
76
- fit: 'oversized',
77
- currentRequest: '1',
78
- recommendedRequest: '500m',
79
- calculatedRequest: '10m',
80
- reductionLimited: true,
81
- bursty: true,
82
- peak: { name: 'P99', value: 0.2, formatted: '200m' },
83
- }),
84
- )
85
- expect(explanation).toContain('Demand-based target: 10m')
86
- expect(explanation).toContain('conservative next step')
87
- expect(explanation).toContain('CPU P99 reached 200m')
88
- })
89
-
90
- it('does not revive the misleading efficiency vocabulary', () => {
91
- const copy = [
92
- getRightsizingPresentation('balanced').label,
93
- getRightsizingPresentation('oversized').label,
94
- getRightsizingExplanation(row({ recommendationReason: 'request_within_fit_range' })),
95
- ]
96
- .join(' ')
97
- .toLowerCase()
98
- expect(copy).not.toContain('efficien')
99
- expect(copy).not.toContain('waste')
100
- })
101
-
8
+ describe('Prometheus rightsizing', () => {
102
9
  it('sets the workload-level scope and methodology without promising savings or changes', () => {
103
10
  expect(RIGHTSIZING_SUMMARY).toContain('this workload')
104
11
  expect(RIGHTSIZING_SUMMARY).toContain('not a savings estimate or automatic change')
@@ -108,97 +15,3 @@ describe('rightsizing presentation', () => {
108
15
  expect(RIGHTSIZING_DOCS_URL).toContain('/features/rightsizing')
109
16
  })
110
17
  })
111
-
112
- describe('live pod inventory', () => {
113
- it('qualifies a memory row when the pod list could not be read', () => {
114
- const explanation = getRightsizingExplanation(
115
- row({ resource: 'memory', liveInventoryUnavailable: true }),
116
- )
117
- expect(explanation).toContain('could not read')
118
- expect(explanation).toContain('out-of-memory restarts')
119
- })
120
-
121
- it('adds the caveat to a suppression reason instead of replacing it', () => {
122
- const explanation = getRightsizingExplanation(
123
- row({ resource: 'memory', recommendationReason: 'oom_evidence', liveInventoryUnavailable: true }),
124
- )
125
- expect(explanation).toContain('OOM evidence exists')
126
- expect(explanation).toContain('could not read')
127
- })
128
-
129
- it('keeps the caveat on a staged reduction, where an unchecked pod matters most', () => {
130
- const explanation = getRightsizingExplanation(
131
- row({
132
- resource: 'memory',
133
- liveInventoryUnavailable: true,
134
- reductionLimited: true,
135
- calculatedRequest: '256Mi',
136
- recommendedRequest: '384Mi',
137
- }),
138
- )
139
- expect(explanation).toContain('conservative next step')
140
- expect(explanation).toContain('could not read')
141
- })
142
-
143
- it('says nothing when the pods were read', () => {
144
- expect(getRightsizingExplanation(row({ resource: 'memory' })) ?? '').not.toContain(
145
- 'could not read',
146
- )
147
- })
148
- })
149
-
150
- describe('pod-level request rows', () => {
151
- it('explains the pod-level value instead of promising a per-container verdict', () => {
152
- const message = getRightsizingExplanation(
153
- row({
154
- fit: 'pod_level_request',
155
- recommendationReason: 'pod_level_request',
156
- podLevelRequest: '128Mi',
157
- resource: 'memory',
158
- }),
159
- )
160
- expect(message).toContain('128Mi')
161
- })
162
-
163
- it('labels a fit this frontend does not know instead of rendering nothing', () => {
164
- const unknownFit = 'future_fit' as unknown as Parameters<typeof getRightsizingPresentation>[0]
165
- expect(getRightsizingPresentation(unknownFit).label).toBe('future_fit')
166
- })
167
- })
168
-
169
- describe('pod-level request below one container\'s usage', () => {
170
- const podLevel = (observed: number, formatted: string) =>
171
- row({
172
- fit: 'pod_level_request',
173
- recommendationReason: 'pod_level_request',
174
- podLevelRequest: '200m',
175
- podLevelRequestValue: 0.2,
176
- observed: { name: 'P95', value: observed, formatted },
177
- })
178
-
179
- it('names the overuse when one container alone used more than the pod request', () => {
180
- const message = getRightsizingExplanation(podLevel(0.44, '440m'))
181
- expect(message).toContain('440m')
182
- expect(podLevelOverUseNote(podLevel(0.44, '440m'))).toBe(message)
183
- })
184
-
185
- it('says nothing about overuse when the container stayed under the pod request', () => {
186
- expect(podLevelOverUseNote(podLevel(0.15, '150m'))).toBeUndefined()
187
- })
188
-
189
- it('does not ask to raise the request when an HPA scales on it', () => {
190
- const note = podLevelOverUseNote({ ...podLevel(0.44, '440m'), hpaManaged: true })
191
- expect(note).toContain('440m')
192
- expect(note).toContain('HPA')
193
- })
194
-
195
- it('asks for an autoscaling check when Radar could not read HPAs', () => {
196
- const note = podLevelOverUseNote({ ...podLevel(0.44, '440m'), hpaEvidenceAvailable: false })
197
- expect(note).toContain('440m')
198
- expect(note).toContain('HPA')
199
- })
200
-
201
- it('stays quiet before six hours of samples', () => {
202
- expect(podLevelOverUseNote({ ...podLevel(0.44, '440m'), sampleCount: 1, coverage: 0 })).toBeUndefined()
203
- })
204
- })
@@ -1,13 +1,16 @@
1
- import { ArrowRight, ExternalLink, Gauge, HelpCircle, Loader2 } from 'lucide-react'
2
- import { Link, useLocation } from 'react-router-dom'
3
- import { Badge } from '@skyhook-io/k8s-ui/components/ui/Badge'
1
+ import { ExternalLink, Gauge, HelpCircle } from 'lucide-react'
2
+ import { RightsizingScanLink } from '../rightsizing/RightsizingScanLink'
3
+ import {
4
+ RightsizingEvidence,
5
+ RightsizingEmptyState as EmptyState,
6
+ } from '@skyhook-io/k8s-ui/components/rightsizing/RightsizingEvidence'
7
+ import { ClusterScopeNote } from '@skyhook-io/k8s-ui/components/ui/ClusterScopeNote'
8
+ import { isClusterScopeWithheld } from '@skyhook-io/k8s-ui/types/cluster-scope'
4
9
  import {
5
10
  usePrometheusRightsizing,
6
11
  usePrometheusStatus,
7
12
  useAutoPromConnect,
8
13
  type PrometheusRightsizing,
9
- type RightsizingFit,
10
- type RightsizingRow,
11
14
  } from '../../api/client'
12
15
  import { Tooltip } from '../ui/Tooltip'
13
16
 
@@ -35,7 +38,6 @@ function useRightsizingEvidence({ kind, namespace, name }: RightsizingProps) {
35
38
 
36
39
  export function RightsizingPanel(props: RightsizingProps) {
37
40
  const state = useRightsizingEvidence(props)
38
- const { search } = useLocation()
39
41
  if (!state.supported) return null
40
42
 
41
43
  return (
@@ -45,7 +47,9 @@ export function RightsizingPanel(props: RightsizingProps) {
45
47
  <Gauge className="mt-0.5 h-4 w-4 text-theme-text-tertiary" />
46
48
  <div>
47
49
  <div className="flex items-center gap-1.5">
48
- <h3 className="text-sm font-semibold text-theme-text-primary">Rightsizing</h3>
50
+ <h3 className="text-sm font-semibold text-theme-text-primary">
51
+ Rightsizing · Prometheus
52
+ </h3>
49
53
  <Tooltip content={RIGHTSIZING_METHODOLOGY}>
50
54
  <HelpCircle className="h-3.5 w-3.5 text-theme-text-tertiary" />
51
55
  </Tooltip>
@@ -65,13 +69,12 @@ export function RightsizingPanel(props: RightsizingProps) {
65
69
  </div>
66
70
  </div>
67
71
  <div className="flex items-center gap-3">
68
- {state.data && <RightsizingContext data={state.data} />}
69
- <Link
70
- to={{ pathname: '/cost/rightsizing', search }}
72
+ {!state.error && state.data && <RightsizingContext data={state.data} />}
73
+ <RightsizingScanLink
71
74
  className="text-xs font-medium text-accent-text hover:underline"
72
75
  >
73
76
  Scan visible workloads
74
- </Link>
77
+ </RightsizingScanLink>
75
78
  </div>
76
79
  </header>
77
80
  <div className="p-4">
@@ -88,23 +91,28 @@ export function RightsizingStrip(props: RightsizingProps) {
88
91
  <section className="mb-3 rounded-lg border border-theme-border bg-theme-surface/40 p-3">
89
92
  <header className="mb-2 flex items-center justify-between gap-3">
90
93
  <div className="flex items-center gap-1.5">
91
- <h3 className="text-sm font-medium text-theme-text-primary">Rightsizing</h3>
94
+ <h3 className="text-sm font-medium text-theme-text-primary">Rightsizing · Prometheus</h3>
92
95
  <Tooltip content={RIGHTSIZING_METHODOLOGY}>
93
96
  <HelpCircle className="h-3.5 w-3.5 text-theme-text-tertiary" />
94
97
  </Tooltip>
95
98
  </div>
96
- {state.data && <RightsizingContext data={state.data} compact />}
99
+ {!state.error && state.data && <RightsizingContext data={state.data} compact />}
97
100
  </header>
98
101
  <RightsizingBody state={state} compact />
99
102
  </section>
100
103
  )
101
104
  }
102
105
 
103
- function RightsizingBody({
106
+ type RightsizingBodyState = Pick<
107
+ ReturnType<typeof useRightsizingEvidence>,
108
+ 'statusLoading' | 'connected' | 'isLoading' | 'error' | 'data'
109
+ >
110
+
111
+ export function RightsizingBody({
104
112
  state,
105
113
  compact,
106
114
  }: {
107
- state: ReturnType<typeof useRightsizingEvidence>
115
+ state: RightsizingBodyState
108
116
  compact: boolean
109
117
  }) {
110
118
  if (state.statusLoading) {
@@ -116,156 +124,15 @@ function RightsizingBody({
116
124
  if (state.isLoading && !state.data) {
117
125
  return <EmptyState text="Analyzing seven days of workload demand…" loading />
118
126
  }
119
- if (state.error && !state.data) {
127
+ if (state.error) {
120
128
  const message = state.error instanceof Error ? state.error.message : String(state.error)
121
129
  return <EmptyState text={`Rightsizing unavailable — ${message}`} />
122
130
  }
123
131
  if (!state.data) return null
124
- if (!state.data.sampleAvailable || state.data.rows.length === 0) {
125
- return <EmptyState text={state.data.reason ?? 'No rightsizing evidence is available.'} />
126
- }
127
-
128
- const byContainer = new Map<string, RightsizingRow[]>()
129
- for (const row of state.data.rows) {
130
- const rows = byContainer.get(row.container) ?? []
131
- rows.push(row)
132
- byContainer.set(row.container, rows)
133
- }
134
-
135
- if (compact) {
136
- return (
137
- <div className="space-y-2">
138
- {Array.from(byContainer.entries()).map(([container, rows]) => (
139
- <div key={container}>
140
- <div className="mb-1 text-xs font-medium text-theme-text-secondary">{container}</div>
141
- <div className="space-y-1 pl-2">
142
- {rows.map((row) => (
143
- <CompactFitRow key={row.resource} row={row} />
144
- ))}
145
- </div>
146
- </div>
147
- ))}
148
- </div>
149
- )
132
+ if (isClusterScopeWithheld(state.data.clusterScope)) {
133
+ return <ClusterScopeNote scope={state.data.clusterScope} title="Recommendations withheld" />
150
134
  }
151
-
152
- return (
153
- <div className="space-y-4">
154
- {(state.data.scaledToZero || state.data.ownerCoverage === 'current_pods') && (
155
- <div className="flex flex-wrap gap-2">
156
- {state.data.scaledToZero && (
157
- <Badge severity="neutral" size="sm">
158
- No current replicas · showing retained evidence
159
- </Badge>
160
- )}
161
- {state.data.ownerCoverage === 'current_pods' && (
162
- <Badge severity="info" size="sm">
163
- Current pods only · confidence capped
164
- </Badge>
165
- )}
166
- </div>
167
- )}
168
- {Array.from(byContainer.entries()).map(([container, rows]) => (
169
- <div key={container}>
170
- <h4 className="mb-2 text-xs font-semibold text-theme-text-secondary">{container}</h4>
171
- <div className="grid gap-3 md:grid-cols-2">
172
- {rows.map((row) => (
173
- <FitCard key={row.resource} row={row} window={state.data!.window} />
174
- ))}
175
- </div>
176
- </div>
177
- ))}
178
- </div>
179
- )
180
- }
181
-
182
- function FitCard({ row, window }: { row: RightsizingRow; window: string }) {
183
- return (
184
- <div className="rounded-md border border-theme-border bg-theme-base/60 p-3">
185
- <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
186
- <span className="text-xs font-semibold uppercase tracking-wide text-theme-text-tertiary">
187
- {row.resource}
188
- </span>
189
- <div className="flex flex-wrap items-center justify-end gap-1.5">
190
- <FitBadge fit={row.fit} queryError={row.queryError} />
191
- {row.hpaManaged && (
192
- <Badge severity="info" size="sm">
193
- HPA-managed
194
- </Badge>
195
- )}
196
- {row.bursty && (
197
- <Badge severity="warning" size="sm">
198
- Bursty CPU
199
- </Badge>
200
- )}
201
- {row.throttleRatio != null && row.throttleRatio >= 0.1 && (
202
- <Badge severity="alert" size="sm">
203
- Throttling observed
204
- </Badge>
205
- )}
206
- {(row.currentPodOOM || row.windowOomEvidence) && (
207
- <Badge severity="error" size="sm">
208
- OOM evidence
209
- </Badge>
210
- )}
211
- </div>
212
- </div>
213
- <div className="flex items-baseline gap-2 tabular-nums">
214
- <div>
215
- <div className="text-[10px] uppercase tracking-wide text-theme-text-quaternary">
216
- {row.podLevelRequest ? 'Pod-level request' : 'Current request'}
217
- </div>
218
- <div className="text-lg font-semibold text-theme-text-primary">
219
- {row.podLevelRequest ?? row.currentRequest ?? 'Unset'}
220
- </div>
221
- </div>
222
- <ArrowRight className="h-4 w-4 text-theme-text-quaternary" />
223
- <div>
224
- <div className="text-[10px] uppercase tracking-wide text-theme-text-quaternary">
225
- Suggested next step
226
- </div>
227
- <div className="text-lg font-semibold text-theme-text-primary">
228
- {row.recommendedRequest ?? '—'}
229
- </div>
230
- </div>
231
- </div>
232
- <div className="mt-3 grid grid-cols-2 gap-3 border-t border-theme-border pt-3 text-xs">
233
- <Metric
234
- label={`${row.observed?.name ?? (row.resource === 'cpu' ? 'P95' : 'Max')} observed`}
235
- value={row.observed?.formatted ?? 'No samples'}
236
- />
237
- <Metric label={`Evidence · ${window}`} value={`${confidenceLabel(row)} · 5m samples`} />
238
- </div>
239
- <FitExplanation row={row} />
240
- </div>
241
- )
242
- }
243
-
244
- function CompactFitRow({ row }: { row: RightsizingRow }) {
245
- return (
246
- <div className="flex flex-wrap items-center gap-2 text-xs tabular-nums text-theme-text-tertiary">
247
- <span className="w-12 text-[10px] uppercase tracking-wide text-theme-text-quaternary">
248
- {row.resource}
249
- </span>
250
- <span className="min-w-14 text-theme-text-secondary">
251
- {row.podLevelRequest ? `pod ${row.podLevelRequest}` : (row.currentRequest ?? 'unset')}
252
- </span>
253
- {row.recommendedRequest && (
254
- <>
255
- <ArrowRight className="h-3 w-3 text-theme-text-quaternary" />
256
- <span className="min-w-14 text-theme-text-primary">{row.recommendedRequest}</span>
257
- </>
258
- )}
259
- {row.observed && (
260
- <span className="text-[10px] text-theme-text-quaternary">
261
- ({row.observed.name} {row.observed.formatted})
262
- </span>
263
- )}
264
- <span className="ml-auto">
265
- <FitBadge fit={row.fit} queryError={row.queryError} />
266
- </span>
267
- </div>
268
- )
135
+ return <RightsizingEvidence data={state.data} compact={compact} />
269
136
  }
270
137
 
271
138
  function RightsizingContext({
@@ -282,143 +149,3 @@ function RightsizingContext({
282
149
  </span>
283
150
  )
284
151
  }
285
-
286
- function FitBadge({ fit, queryError }: { fit: RightsizingFit; queryError?: string }) {
287
- const presentation = getRightsizingPresentation(fit, queryError)
288
- return (
289
- <Badge severity={presentation.severity} size="sm">
290
- {presentation.label}
291
- </Badge>
292
- )
293
- }
294
-
295
- export function getRightsizingPresentation(fit: RightsizingFit, queryError?: string) {
296
- if (queryError) return { label: 'Query failed', severity: 'error' as const }
297
- const labels: Record<RightsizingFit, string> = {
298
- balanced: 'Balanced',
299
- oversized: 'Oversized',
300
- under_requested: 'Under-requested',
301
- missing_request: 'Missing request',
302
- insufficient_history: 'Insufficient history',
303
- pod_level_request: 'Pod-level request',
304
- }
305
- const severities: Record<RightsizingFit, 'success' | 'info' | 'warning' | 'neutral'> = {
306
- balanced: 'success',
307
- oversized: 'info',
308
- under_requested: 'warning',
309
- missing_request: 'warning',
310
- insufficient_history: 'neutral',
311
- pod_level_request: 'neutral',
312
- }
313
- // An older frontend can meet a fit added by a newer agent.
314
- return { label: labels[fit] ?? fit, severity: severities[fit] ?? ('neutral' as const) }
315
- }
316
-
317
- function FitExplanation({ row }: { row: RightsizingRow }) {
318
- const message = getRightsizingExplanation(row)
319
- if (!message) return null
320
- return <p className="mt-3 text-xs text-theme-text-tertiary">{message}</p>
321
- }
322
-
323
- export function getRightsizingExplanation(row: RightsizingRow): string | undefined {
324
- const messages: Record<string, string> = {
325
- request_within_fit_range: 'The configured request is within 30% of the evidence-based target.',
326
- insufficient_history: 'At least six hours of samples are required before suggesting a request.',
327
- hpa_managed: `The HPA manages ${row.resource}; review its target before changing this request.`,
328
- hpa_evidence_unavailable:
329
- 'Radar could not verify HPA ownership, so it withheld a suggested request.',
330
- oom_evidence: 'A lower memory request is withheld because OOM evidence exists.',
331
- oom_evidence_unavailable:
332
- 'Radar could not verify recent OOM history, so it withheld a lower memory request.',
333
- recommended_request_exceeds_limit:
334
- 'The evidence-based request would exceed the current limit; review the limit first.',
335
- requests_exceed_pod_limit:
336
- "Together with the other containers' requests and suggested increases, this request would take the pod above its pod-level limit (spec.resources), which Kubernetes rejects. Decide how to split the limit between containers, or raise the pod limit.",
337
- }
338
- // A denied pod read leaves currentPodOOM unknown rather than false, so it
339
- // qualifies whatever else is said instead of replacing it — including a
340
- // staged reduction, which is exactly where an unchecked pod matters most.
341
- const inventoryNote =
342
- row.liveInventoryUnavailable && row.resource === 'memory'
343
- ? "Radar could not read this workload's pods, so it could not check them for out-of-memory restarts."
344
- : undefined
345
- const qualified = (base: string) => (inventoryNote ? `${base} ${inventoryNote}` : base)
346
- if (row.fit === 'pod_level_request' && row.podLevelRequest && !row.queryError)
347
- return qualified(podLevelRequestExplanation(row, row.podLevelRequest))
348
- if (row.reductionLimited && row.calculatedRequest && row.recommendedRequest) {
349
- const burstNote = row.bursty && row.peak ? ` CPU P99 reached ${row.peak.formatted}.` : ''
350
- return qualified(
351
- `Demand-based target: ${row.calculatedRequest}. Radar suggests ${row.recommendedRequest} as a conservative next step; observe another full window before reducing further.${burstNote}`,
352
- )
353
- }
354
- const message = row.queryError
355
- ? `Partial result: ${row.queryError}.`
356
- : messages[row.recommendationReason ?? '']
357
- const throttleUnavailable = row.resource === 'cpu' && !row.throttleAvailable
358
- if (!message && !throttleUnavailable) return inventoryNote
359
- return qualified(
360
- message ?? 'CPU throttling metrics are unavailable; no throttling conclusion was drawn.',
361
- )
362
- }
363
-
364
- function podLevelRequestExplanation(row: RightsizingRow, podLevelRequest: string): string {
365
- const overUse = podLevelOverUseNote(row)
366
- if (overUse) return overUse
367
- const resource = row.resource === 'cpu' ? 'CPU' : 'memory'
368
- const own = row.currentRequest
369
- ? ` This container's own request (${row.currentRequest}) no longer decides what is reserved.`
370
- : ''
371
- return `This pod sets one ${resource} request for all its containers: ${podLevelRequest} in spec.resources. The scheduler reserves that instead of container requests, so Radar doesn't suggest a request per container; check the pod-level request against the usage of its containers.${own}`
372
- }
373
-
374
- /**
375
- * One container's usage above the pod's whole request is a sound lower bound on
376
- * the pod's own use. Adding containers up would overstate it, so only this case
377
- * is called out.
378
- */
379
- export function podLevelOverUseNote(row: RightsizingRow): string | undefined {
380
- if (
381
- row.fit !== 'pod_level_request' ||
382
- row.sampleCount < RIGHTSIZING_MIN_SAMPLES ||
383
- !row.observed ||
384
- !row.podLevelRequest ||
385
- row.podLevelRequestValue == null ||
386
- row.observed.value <= row.podLevelRequestValue
387
- )
388
- return undefined
389
- const resource = row.resource === 'cpu' ? 'CPU' : 'memory'
390
- const finding = `This container alone used ${row.observed.formatted} (${row.observed.name}), more than the pod's whole ${row.podLevelRequest} ${resource} request. Radar can't size pod-level requests yet.`
391
- // An HPA scaling on this resource divides usage by the pod request, so
392
- // raising it changes scaling; Radar never suggests that unreviewed.
393
- if (row.hpaManaged)
394
- return `${finding} The HPA scales on this request, so review its target before raising spec.resources.requests.${row.resource}.`
395
- if (!row.hpaEvidenceAvailable)
396
- return `${finding} Radar couldn't check for an HPA on this resource, so check autoscaling before raising spec.resources.requests.${row.resource}.`
397
- return `${finding} Consider raising spec.resources.requests.${row.resource}.`
398
- }
399
-
400
- // Mirrors rightsizingMinSamples (six hours of 5-minute samples) in
401
- // internal/prometheus/rightsizing.go: below it Radar draws no conclusion.
402
- const RIGHTSIZING_MIN_SAMPLES = 72
403
-
404
- function confidenceLabel(row: RightsizingRow) {
405
- return `${row.confidence[0].toUpperCase()}${row.confidence.slice(1)} confidence`
406
- }
407
-
408
- function Metric({ label, value }: { label: string; value: string }) {
409
- return (
410
- <div>
411
- <div className="text-theme-text-quaternary">{label}</div>
412
- <div className="mt-0.5 text-theme-text-secondary">{value}</div>
413
- </div>
414
- )
415
- }
416
-
417
- function EmptyState({ text, loading = false }: { text: string; loading?: boolean }) {
418
- return (
419
- <div className="flex min-h-16 items-center justify-center text-sm text-theme-text-tertiary">
420
- {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
421
- {text}
422
- </div>
423
- )
424
- }
@@ -5,6 +5,11 @@ import type { WorkloadMetrics, WorkloadMetricPanel } from '../../api/workloadMet
5
5
 
6
6
  let result: { data?: WorkloadMetrics; isLoading?: boolean; isPlaceholderData?: boolean; error?: Error } = {}
7
7
  vi.mock('../../api/workloadMetrics', () => ({ useWorkloadMetrics: () => result }))
8
+ let chartScopes: Record<string, { state: string; note: string } | undefined> = {}
9
+ vi.mock('../../api/client', async (importActual) => ({
10
+ ...(await importActual<typeof import('../../api/client')>()),
11
+ usePrometheusResourceMetrics: (_kind: string, _ns: string, _name: string, category: string) => ({ data: { unit: 'cores', clusterScope: chartScopes[category] } }),
12
+ }))
8
13
  const { WorkloadMetricsSection } = await import('./WorkloadMetricsSection')
9
14
  const panel = (value: number, unit = 'requests/s'): WorkloadMetricPanel => ({
10
15
  state: 'available', unit,
@@ -13,6 +18,7 @@ const panel = (value: number, unit = 'requests/s'): WorkloadMetricPanel => ({
13
18
  const render = () => renderToString(<MemoryRouter><WorkloadMetricsSection kind="Deployment" namespace="shop" name="checkout" range="1h" /></MemoryRouter>)
14
19
 
15
20
  beforeEach(() => {
21
+ chartScopes = {}
16
22
  result = { data: {
17
23
  state: 'available', source: 'beyla',
18
24
  sources: [{ id: 'beyla', label: 'Beyla', state: 'available' }],
@@ -75,6 +81,22 @@ describe('Workload metrics interpretation', () => {
75
81
  expect(html).toContain('History lookup failed')
76
82
  expect(html).not.toContain('Existing memory chart')
77
83
  })
84
+ it('says name-matched charts were kept to this cluster when their scope was verified', () => {
85
+ result.data!.panels.cpu = { state: 'error', unit: 'cores', reason: 'History lookup failed', series: [] }
86
+ chartScopes = { cpu: { state: 'scoped_verified', note: 'Matched by cluster labels confirmed against this cluster\'s Pods.' } }
87
+ const html = renderToString(<MemoryRouter><WorkloadMetricsSection kind="Deployment" namespace="shop" name="checkout" range="1h" nameMatchedCharts={{ cpu: <span>Existing CPU chart</span> }} /></MemoryRouter>).replaceAll('<!-- -->', '')
88
+ expect(html).toContain('Basic CPU · matched by cluster label')
89
+ expect(html).toContain('kept to this cluster by its cluster labels')
90
+ expect(html).not.toContain('may include another cluster')
91
+ expect(html).not.toContain('identity unverified')
92
+ })
93
+ it('keeps the name-matched caveat for an unlabeled store', () => {
94
+ result.data!.panels.cpu = { state: 'error', unit: 'cores', reason: 'History lookup failed', series: [] }
95
+ chartScopes = { cpu: { state: 'unlabeled', note: 'No cluster label.' } }
96
+ const html = renderToString(<MemoryRouter><WorkloadMetricsSection kind="Deployment" namespace="shop" name="checkout" range="1h" nameMatchedCharts={{ cpu: <span>Existing CPU chart</span> }} /></MemoryRouter>).replaceAll('<!-- -->', '')
97
+ expect(html).toContain('Basic CPU · identity unverified')
98
+ expect(html).toContain('These charts match current Pod names, not Pod UIDs or historical workload ownership; matching names in a shared backend may include another cluster.')
99
+ })
78
100
  it('does not flash name-matched charts during the initial request', () => {
79
101
  result = { isLoading: true }
80
102
  const html = renderToString(<MemoryRouter><WorkloadMetricsSection kind="Deployment" namespace="shop" name="checkout" range="1h" nameMatchedCharts={{ cpu: <span>Existing CPU chart</span> }} /></MemoryRouter>)