regressedProfileFunctions.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import {useCallback, useMemo, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import type {SelectOption} from 'sentry/components/compactSelect';
  5. import {CompactSelect} from 'sentry/components/compactSelect';
  6. import Link from 'sentry/components/links/link';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import Pagination from 'sentry/components/pagination';
  9. import PerformanceDuration from 'sentry/components/performanceDuration';
  10. import {TextTruncateOverflow} from 'sentry/components/profiling/textTruncateOverflow';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import type {Organization} from 'sentry/types/organization';
  14. import type {Project} from 'sentry/types/project';
  15. import {defined} from 'sentry/utils';
  16. import {trackAnalytics} from 'sentry/utils/analytics';
  17. import {formatPercentage} from 'sentry/utils/number/formatPercentage';
  18. import type {FunctionTrend, TrendType} from 'sentry/utils/profiling/hooks/types';
  19. import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
  20. import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
  21. import {
  22. generateProfileDifferentialFlamegraphRouteWithQuery,
  23. generateProfileRouteFromProfileReference,
  24. } from 'sentry/utils/profiling/routes';
  25. import {relativeChange} from 'sentry/utils/profiling/units/units';
  26. import {decodeScalar} from 'sentry/utils/queryString';
  27. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  28. import {useLocation} from 'sentry/utils/useLocation';
  29. import {useNavigate} from 'sentry/utils/useNavigate';
  30. import useOrganization from 'sentry/utils/useOrganization';
  31. import {ProfilingSparklineChart} from './profilingSparklineChart';
  32. const REGRESSED_FUNCTIONS_LIMIT = 5;
  33. const REGRESSED_FUNCTIONS_CURSOR = 'functionRegressionCursor';
  34. function trendToPoints(trend: FunctionTrend): Array<{timestamp: number; value: number}> {
  35. if (!trend.stats.data.length) {
  36. return [];
  37. }
  38. return trend.stats.data.map(p => {
  39. return {
  40. timestamp: p[0],
  41. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  42. value: p[1][0].count,
  43. };
  44. });
  45. }
  46. function findBreakPointIndex(
  47. breakpoint: number,
  48. examples: FunctionTrend['examples']
  49. ): number {
  50. let low = 0;
  51. let high = examples.length - 1;
  52. let mid = 0;
  53. let bestMatch: number = examples.length;
  54. while (low <= high) {
  55. mid = Math.floor((low + high) / 2);
  56. const value = examples[mid]![0];
  57. if (breakpoint === value) {
  58. return mid;
  59. }
  60. if (breakpoint > value) {
  61. low = mid + 1;
  62. bestMatch = mid + 1;
  63. } else if (breakpoint < value) {
  64. high = mid - 1;
  65. bestMatch = mid;
  66. }
  67. }
  68. // We dont need an exact match as the breakpoint is not guaranteed to be
  69. // in the worst array, so we return the closest index
  70. return bestMatch;
  71. }
  72. function findWorstProfileIDBeforeAndAfter(trend: FunctionTrend): {
  73. after: Profiling.BaseProfileReference | null;
  74. before: Profiling.BaseProfileReference | null;
  75. } {
  76. const breakPointIndex = findBreakPointIndex(trend.breakpoint, trend.examples);
  77. let beforeProfile: Profiling.BaseProfileReference | null = null;
  78. let afterProfile: Profiling.BaseProfileReference | null = null;
  79. const STABILITY_WINDOW = 2 * 60 * 1000;
  80. for (let i = breakPointIndex; i >= 0; i--) {
  81. if (!defined(trend.examples[i])) {
  82. continue;
  83. }
  84. if (trend.examples[i]![0] < trend.breakpoint - STABILITY_WINDOW) {
  85. break;
  86. }
  87. beforeProfile = trend.examples[i]![1];
  88. }
  89. for (let i = breakPointIndex; i < trend.examples.length; i++) {
  90. if (!defined(trend.examples[i])) {
  91. continue;
  92. }
  93. if (trend.examples[i]![0] > trend.breakpoint + STABILITY_WINDOW) {
  94. break;
  95. }
  96. afterProfile = trend.examples[i]![1];
  97. }
  98. return {
  99. before: beforeProfile,
  100. after: afterProfile,
  101. };
  102. }
  103. interface MostRegressedProfileFunctionsProps {
  104. transaction: string;
  105. }
  106. export function MostRegressedProfileFunctions(props: MostRegressedProfileFunctionsProps) {
  107. const organization = useOrganization();
  108. const project = useCurrentProjectFromRouteParam();
  109. const navigate = useNavigate();
  110. const location = useLocation();
  111. const theme = useTheme();
  112. const fnTrendCursor = useMemo(
  113. () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
  114. [location.query]
  115. );
  116. const handleRegressedFunctionsCursor = useCallback(
  117. (cursor: any, pathname: any, query: any) => {
  118. navigate({
  119. pathname,
  120. query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
  121. });
  122. },
  123. [navigate]
  124. );
  125. const functionQuery = useMemo(() => {
  126. const conditions = new MutableSearch('');
  127. conditions.setFilterValues('is_application', ['1']);
  128. conditions.setFilterValues('transaction', [props.transaction]);
  129. return conditions.formatString();
  130. }, [props.transaction]);
  131. const [trendType, setTrendType] = useState<TrendType>('regression');
  132. const trendsQuery = useProfileFunctionTrends({
  133. trendFunction: 'p95()',
  134. trendType,
  135. query: functionQuery,
  136. limit: REGRESSED_FUNCTIONS_LIMIT,
  137. cursor: fnTrendCursor,
  138. });
  139. const trends = trendsQuery?.data ?? [];
  140. const onChangeTrendType = useCallback((v: any) => setTrendType(v.value), []);
  141. const hasDifferentialFlamegraphPageFeature = organization.features.includes(
  142. 'profiling-differential-flamegraph-page'
  143. );
  144. return (
  145. <RegressedFunctionsContainer>
  146. <RegressedFunctionsTitleContainer>
  147. <RegressedFunctionsTypeSelect
  148. value={trendType}
  149. options={TREND_FUNCTION_OPTIONS}
  150. onChange={onChangeTrendType}
  151. triggerProps={TRIGGER_PROPS}
  152. offset={4}
  153. />
  154. <RegressedFunctionsPagination
  155. pageLinks={trendsQuery.getResponseHeader?.('Link')}
  156. onCursor={handleRegressedFunctionsCursor}
  157. size="xs"
  158. />
  159. </RegressedFunctionsTitleContainer>
  160. {trendsQuery.isPending ? (
  161. <RegressedFunctionsQueryState>
  162. <LoadingIndicator size={36} />
  163. </RegressedFunctionsQueryState>
  164. ) : trendsQuery.isError ? (
  165. <RegressedFunctionsQueryState>
  166. {t('Failed to fetch regressed functions')}
  167. </RegressedFunctionsQueryState>
  168. ) : !trends.length ? (
  169. <RegressedFunctionsQueryState>
  170. {trendType === 'regression' ? (
  171. <p>{t('No regressed functions detected')}</p>
  172. ) : (
  173. <p>{t('No improved functions detected')}</p>
  174. )}
  175. </RegressedFunctionsQueryState>
  176. ) : (
  177. trends.map((fn, i) => {
  178. const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
  179. return (
  180. <RegressedFunctionRow key={i}>
  181. {hasDifferentialFlamegraphPageFeature ? (
  182. <RegressedFunctionDifferentialFlamegraph
  183. transaction={props.transaction}
  184. organization={organization}
  185. project={project}
  186. fn={fn}
  187. />
  188. ) : (
  189. <RegressedFunctionBeforeAfterFlamechart
  190. organization={organization}
  191. project={project}
  192. before={before}
  193. after={after}
  194. fn={fn}
  195. />
  196. )}
  197. <RegressedFunctionMetricsRow>
  198. <div>
  199. <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
  200. </div>
  201. <div>
  202. {/* We dont handle improvements as formatPercentage and relativeChange
  203. on lines below dont return absolute values, else we end up with a double sign */}
  204. {trendType === 'regression'
  205. ? fn.aggregate_range_1 < fn.aggregate_range_2
  206. ? '+'
  207. : '-'
  208. : null}
  209. {formatPercentage(
  210. relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
  211. )}
  212. </div>
  213. </RegressedFunctionMetricsRow>
  214. <RegressedFunctionSparklineContainer>
  215. <ProfilingSparklineChart
  216. name="p95(function.duration)"
  217. points={trendToPoints(fn)}
  218. color={trendType === 'improvement' ? theme.green300 : theme.red300}
  219. aggregate_range_1={fn.aggregate_range_1}
  220. aggregate_range_2={fn.aggregate_range_2}
  221. breakpoint={fn.breakpoint}
  222. start={fn.stats.data[0]![0]}
  223. end={fn.stats.data[fn.stats.data.length - 1]![0]}
  224. />
  225. </RegressedFunctionSparklineContainer>
  226. </RegressedFunctionRow>
  227. );
  228. })
  229. )}
  230. </RegressedFunctionsContainer>
  231. );
  232. }
  233. interface RegressedFunctionDifferentialFlamegraphProps {
  234. fn: FunctionTrend;
  235. organization: Organization;
  236. project: Project | null;
  237. transaction: string;
  238. }
  239. function RegressedFunctionDifferentialFlamegraph(
  240. props: RegressedFunctionDifferentialFlamegraphProps
  241. ) {
  242. const onRegressedFunctionClick = useCallback(() => {
  243. trackAnalytics('profiling_views.go_to_differential_flamegraph', {
  244. organization: props.organization,
  245. source: `profiling_transaction.regressed_functions_table`,
  246. });
  247. }, [props.organization]);
  248. const differentialFlamegraphLink = generateProfileDifferentialFlamegraphRouteWithQuery({
  249. orgSlug: props.organization.slug,
  250. projectSlug: props.project?.slug ?? '',
  251. transaction: props.transaction,
  252. fingerprint: props.fn.fingerprint,
  253. breakpoint: props.fn.breakpoint,
  254. query: {
  255. // specify the frame to focus, the flamegraph will switch
  256. // to the appropriate thread when these are specified
  257. frameName: props.fn.function,
  258. framePackage: props.fn.package,
  259. },
  260. });
  261. return (
  262. <RegressedFunctionMainRow>
  263. <div>
  264. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  265. <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>
  266. </Link>
  267. </div>
  268. <div>
  269. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  270. <PerformanceDuration abbreviation nanoseconds={props.fn.aggregate_range_1} />
  271. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  272. <PerformanceDuration abbreviation nanoseconds={props.fn.aggregate_range_2} />
  273. </Link>
  274. </div>
  275. </RegressedFunctionMainRow>
  276. );
  277. }
  278. interface RegressedFunctionBeforeAfterProps {
  279. after: Profiling.BaseProfileReference | null;
  280. before: Profiling.BaseProfileReference | null;
  281. fn: FunctionTrend;
  282. organization: Organization;
  283. project: Project | null;
  284. }
  285. function RegressedFunctionBeforeAfterFlamechart(
  286. props: RegressedFunctionBeforeAfterProps
  287. ) {
  288. const onRegressedFunctionClick = useCallback(() => {
  289. trackAnalytics('profiling_views.go_to_flamegraph', {
  290. organization: props.organization,
  291. source: `profiling_transaction.regressed_functions_table`,
  292. });
  293. }, [props.organization]);
  294. let rendered = <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>;
  295. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  296. const example = props.fn['all_examples()']?.[0];
  297. if (defined(example)) {
  298. rendered = (
  299. <Link
  300. onClick={onRegressedFunctionClick}
  301. to={generateProfileRouteFromProfileReference({
  302. orgSlug: props.organization.slug,
  303. projectSlug: props.project?.slug ?? '',
  304. reference: example,
  305. // specify the frame to focus, the flamegraph will switch
  306. // to the appropriate thread when these are specified
  307. frameName: props.fn.function,
  308. framePackage: props.fn.package,
  309. })}
  310. >
  311. {rendered}
  312. </Link>
  313. );
  314. }
  315. let before = (
  316. <PerformanceDuration abbreviation nanoseconds={props.fn.aggregate_range_1} />
  317. );
  318. if (props.before) {
  319. before = (
  320. <Link
  321. onClick={onRegressedFunctionClick}
  322. to={generateProfileRouteFromProfileReference({
  323. orgSlug: props.organization.slug,
  324. projectSlug: props.project?.slug ?? '',
  325. reference: props.before,
  326. // specify the frame to focus, the flamegraph will switch
  327. // to the appropriate thread when these are specified
  328. frameName: props.fn.function,
  329. framePackage: props.fn.package,
  330. })}
  331. >
  332. {before}
  333. </Link>
  334. );
  335. }
  336. let after = (
  337. <PerformanceDuration abbreviation nanoseconds={props.fn.aggregate_range_2} />
  338. );
  339. if (props.after) {
  340. after = (
  341. <Link
  342. onClick={onRegressedFunctionClick}
  343. to={generateProfileRouteFromProfileReference({
  344. orgSlug: props.organization.slug,
  345. projectSlug: props.project?.slug ?? '',
  346. reference: props.after,
  347. // specify the frame to focus, the flamegraph will switch
  348. // to the appropriate thread when these are specified
  349. frameName: props.fn.function,
  350. framePackage: props.fn.package,
  351. })}
  352. >
  353. {after}
  354. </Link>
  355. );
  356. }
  357. return (
  358. <RegressedFunctionMainRow>
  359. <div>{rendered}</div>
  360. <div>
  361. {before}
  362. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  363. {after}
  364. </div>
  365. </RegressedFunctionMainRow>
  366. );
  367. }
  368. const ChangeArrow = styled('span')`
  369. color: ${p => p.theme.subText};
  370. `;
  371. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  372. button {
  373. margin: 0;
  374. padding: 0;
  375. }
  376. `;
  377. const RegressedFunctionSparklineContainer = styled('div')``;
  378. const RegressedFunctionRow = styled('div')`
  379. position: relative;
  380. margin-bottom: ${space(1)};
  381. `;
  382. const RegressedFunctionMainRow = styled('div')`
  383. display: flex;
  384. align-items: center;
  385. justify-content: space-between;
  386. > div:first-child {
  387. min-width: 0;
  388. }
  389. > div:last-child {
  390. white-space: nowrap;
  391. }
  392. `;
  393. const RegressedFunctionMetricsRow = styled('div')`
  394. display: flex;
  395. align-items: center;
  396. justify-content: space-between;
  397. font-size: ${p => p.theme.fontSizeSmall};
  398. color: ${p => p.theme.subText};
  399. margin-top: ${space(0.25)};
  400. `;
  401. const RegressedFunctionsContainer = styled('div')`
  402. flex-basis: 80px;
  403. padding: 0 ${space(1)};
  404. border-bottom: 1px solid ${p => p.theme.border};
  405. `;
  406. const RegressedFunctionsPagination = styled(Pagination)`
  407. margin: 0;
  408. button {
  409. height: 16px;
  410. width: 16px;
  411. min-width: 16px;
  412. min-height: 16px;
  413. svg {
  414. width: 10px;
  415. height: 10px;
  416. }
  417. }
  418. `;
  419. const RegressedFunctionsTitleContainer = styled('div')`
  420. display: flex;
  421. align-items: center;
  422. justify-content: space-between;
  423. margin-bottom: ${space(0.5)};
  424. margin-top: ${space(0.5)};
  425. `;
  426. const RegressedFunctionsQueryState = styled('div')`
  427. text-align: center;
  428. padding: ${space(2)} ${space(0.5)};
  429. color: ${p => p.theme.subText};
  430. `;
  431. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  432. const TREND_FUNCTION_OPTIONS: Array<SelectOption<TrendType>> = [
  433. {
  434. label: t('Most Regressed Functions'),
  435. value: 'regression' as const,
  436. },
  437. {
  438. label: t('Most Improved Functions'),
  439. value: 'improvement' as const,
  440. },
  441. ];