regressedProfileFunctions.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 as string,
  258. framePackage: props.fn.package as string,
  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
  271. abbreviation
  272. nanoseconds={props.fn.aggregate_range_1 as number}
  273. />
  274. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  275. <PerformanceDuration
  276. abbreviation
  277. nanoseconds={props.fn.aggregate_range_2 as number}
  278. />
  279. </Link>
  280. </div>
  281. </RegressedFunctionMainRow>
  282. );
  283. }
  284. interface RegressedFunctionBeforeAfterProps {
  285. after: Profiling.BaseProfileReference | null;
  286. before: Profiling.BaseProfileReference | null;
  287. fn: FunctionTrend;
  288. organization: Organization;
  289. project: Project | null;
  290. }
  291. function RegressedFunctionBeforeAfterFlamechart(
  292. props: RegressedFunctionBeforeAfterProps
  293. ) {
  294. const onRegressedFunctionClick = useCallback(() => {
  295. trackAnalytics('profiling_views.go_to_flamegraph', {
  296. organization: props.organization,
  297. source: `profiling_transaction.regressed_functions_table`,
  298. });
  299. }, [props.organization]);
  300. let rendered = <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>;
  301. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  302. const example = props.fn['all_examples()']?.[0];
  303. if (defined(example)) {
  304. rendered = (
  305. <Link
  306. onClick={onRegressedFunctionClick}
  307. to={generateProfileRouteFromProfileReference({
  308. orgSlug: props.organization.slug,
  309. projectSlug: props.project?.slug ?? '',
  310. reference: example,
  311. // specify the frame to focus, the flamegraph will switch
  312. // to the appropriate thread when these are specified
  313. frameName: props.fn.function as string,
  314. framePackage: props.fn.package as string,
  315. })}
  316. >
  317. {rendered}
  318. </Link>
  319. );
  320. }
  321. let before = (
  322. <PerformanceDuration
  323. abbreviation
  324. nanoseconds={props.fn.aggregate_range_1 as number}
  325. />
  326. );
  327. if (props.before) {
  328. before = (
  329. <Link
  330. onClick={onRegressedFunctionClick}
  331. to={generateProfileRouteFromProfileReference({
  332. orgSlug: props.organization.slug,
  333. projectSlug: props.project?.slug ?? '',
  334. reference: props.before,
  335. // specify the frame to focus, the flamegraph will switch
  336. // to the appropriate thread when these are specified
  337. frameName: props.fn.function as string,
  338. framePackage: props.fn.package as string,
  339. })}
  340. >
  341. {before}
  342. </Link>
  343. );
  344. }
  345. let after = (
  346. <PerformanceDuration
  347. abbreviation
  348. nanoseconds={props.fn.aggregate_range_2 as number}
  349. />
  350. );
  351. if (props.after) {
  352. after = (
  353. <Link
  354. onClick={onRegressedFunctionClick}
  355. to={generateProfileRouteFromProfileReference({
  356. orgSlug: props.organization.slug,
  357. projectSlug: props.project?.slug ?? '',
  358. reference: props.after,
  359. // specify the frame to focus, the flamegraph will switch
  360. // to the appropriate thread when these are specified
  361. frameName: props.fn.function as string,
  362. framePackage: props.fn.package as string,
  363. })}
  364. >
  365. {after}
  366. </Link>
  367. );
  368. }
  369. return (
  370. <RegressedFunctionMainRow>
  371. <div>{rendered}</div>
  372. <div>
  373. {before}
  374. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  375. {after}
  376. </div>
  377. </RegressedFunctionMainRow>
  378. );
  379. }
  380. const ChangeArrow = styled('span')`
  381. color: ${p => p.theme.subText};
  382. `;
  383. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  384. button {
  385. margin: 0;
  386. padding: 0;
  387. }
  388. `;
  389. const RegressedFunctionSparklineContainer = styled('div')``;
  390. const RegressedFunctionRow = styled('div')`
  391. position: relative;
  392. margin-bottom: ${space(1)};
  393. `;
  394. const RegressedFunctionMainRow = styled('div')`
  395. display: flex;
  396. align-items: center;
  397. justify-content: space-between;
  398. > div:first-child {
  399. min-width: 0;
  400. }
  401. > div:last-child {
  402. white-space: nowrap;
  403. }
  404. `;
  405. const RegressedFunctionMetricsRow = styled('div')`
  406. display: flex;
  407. align-items: center;
  408. justify-content: space-between;
  409. font-size: ${p => p.theme.fontSizeSmall};
  410. color: ${p => p.theme.subText};
  411. margin-top: ${space(0.25)};
  412. `;
  413. const RegressedFunctionsContainer = styled('div')`
  414. flex-basis: 80px;
  415. padding: 0 ${space(1)};
  416. border-bottom: 1px solid ${p => p.theme.border};
  417. `;
  418. const RegressedFunctionsPagination = styled(Pagination)`
  419. margin: 0;
  420. button {
  421. height: 16px;
  422. width: 16px;
  423. min-width: 16px;
  424. min-height: 16px;
  425. svg {
  426. width: 10px;
  427. height: 10px;
  428. }
  429. }
  430. `;
  431. const RegressedFunctionsTitleContainer = styled('div')`
  432. display: flex;
  433. align-items: center;
  434. justify-content: space-between;
  435. margin-bottom: ${space(0.5)};
  436. margin-top: ${space(0.5)};
  437. `;
  438. const RegressedFunctionsQueryState = styled('div')`
  439. text-align: center;
  440. padding: ${space(2)} ${space(0.5)};
  441. color: ${p => p.theme.subText};
  442. `;
  443. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  444. const TREND_FUNCTION_OPTIONS: Array<SelectOption<TrendType>> = [
  445. {
  446. label: t('Most Regressed Functions'),
  447. value: 'regression' as const,
  448. },
  449. {
  450. label: t('Most Improved Functions'),
  451. value: 'improvement' as const,
  452. },
  453. ];