regressedProfileFunctions.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 {browserHistory} from 'sentry/utils/browserHistory';
  18. import {formatPercentage} from 'sentry/utils/number/formatPercentage';
  19. import type {FunctionTrend, TrendType} from 'sentry/utils/profiling/hooks/types';
  20. import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
  21. import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
  22. import {
  23. generateProfileDifferentialFlamegraphRouteWithQuery,
  24. generateProfileRouteFromProfileReference,
  25. } from 'sentry/utils/profiling/routes';
  26. import {relativeChange} from 'sentry/utils/profiling/units/units';
  27. import {decodeScalar} from 'sentry/utils/queryString';
  28. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  29. import {useLocation} from 'sentry/utils/useLocation';
  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): {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. value: p[1][0].count,
  42. };
  43. });
  44. }
  45. function findBreakPointIndex(
  46. breakpoint: number,
  47. examples: FunctionTrend['examples']
  48. ): number {
  49. let low = 0;
  50. let high = examples.length - 1;
  51. let mid = 0;
  52. let bestMatch: number = examples.length;
  53. // eslint-disable-next-line
  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 location = useLocation();
  110. const theme = useTheme();
  111. const fnTrendCursor = useMemo(
  112. () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
  113. [location.query]
  114. );
  115. const handleRegressedFunctionsCursor = useCallback((cursor, pathname, query) => {
  116. browserHistory.push({
  117. pathname,
  118. query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
  119. });
  120. }, []);
  121. const functionQuery = useMemo(() => {
  122. const conditions = new MutableSearch('');
  123. conditions.setFilterValues('is_application', ['1']);
  124. conditions.setFilterValues('transaction', [props.transaction]);
  125. return conditions.formatString();
  126. }, [props.transaction]);
  127. const [trendType, setTrendType] = useState<TrendType>('regression');
  128. const trendsQuery = useProfileFunctionTrends({
  129. trendFunction: 'p95()',
  130. trendType,
  131. query: functionQuery,
  132. limit: REGRESSED_FUNCTIONS_LIMIT,
  133. cursor: fnTrendCursor,
  134. });
  135. const trends = trendsQuery?.data ?? [];
  136. const onChangeTrendType = useCallback(v => setTrendType(v.value), []);
  137. const hasDifferentialFlamegraphPageFeature =
  138. false && organization.features.includes('profiling-differential-flamegraph-page');
  139. return (
  140. <RegressedFunctionsContainer>
  141. <RegressedFunctionsTitleContainer>
  142. <RegressedFunctionsTypeSelect
  143. value={trendType}
  144. options={TREND_FUNCTION_OPTIONS}
  145. onChange={onChangeTrendType}
  146. triggerProps={TRIGGER_PROPS}
  147. offset={4}
  148. />
  149. <RegressedFunctionsPagination
  150. pageLinks={trendsQuery.getResponseHeader?.('Link')}
  151. onCursor={handleRegressedFunctionsCursor}
  152. size="xs"
  153. />
  154. </RegressedFunctionsTitleContainer>
  155. {trendsQuery.isPending ? (
  156. <RegressedFunctionsQueryState>
  157. <LoadingIndicator size={36} />
  158. </RegressedFunctionsQueryState>
  159. ) : trendsQuery.isError ? (
  160. <RegressedFunctionsQueryState>
  161. {t('Failed to fetch regressed functions')}
  162. </RegressedFunctionsQueryState>
  163. ) : !trends.length ? (
  164. <RegressedFunctionsQueryState>
  165. {trendType === 'regression' ? (
  166. <p>{t('No regressed functions detected')}</p>
  167. ) : (
  168. <p>{t('No improved functions detected')}</p>
  169. )}
  170. </RegressedFunctionsQueryState>
  171. ) : (
  172. trends.map((fn, i) => {
  173. const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
  174. return (
  175. <RegressedFunctionRow key={i}>
  176. {hasDifferentialFlamegraphPageFeature ? (
  177. <RegressedFunctionDifferentialFlamegraph
  178. transaction={props.transaction}
  179. organization={organization}
  180. project={project}
  181. fn={fn}
  182. />
  183. ) : (
  184. <RegressedFunctionBeforeAfterFlamechart
  185. organization={organization}
  186. project={project}
  187. before={before}
  188. after={after}
  189. fn={fn}
  190. />
  191. )}
  192. <RegressedFunctionMetricsRow>
  193. <div>
  194. <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
  195. </div>
  196. <div>
  197. {/* We dont handle improvements as formatPercentage and relativeChange
  198. on lines below dont return absolute values, else we end up with a double sign */}
  199. {trendType === 'regression'
  200. ? fn.aggregate_range_1 < fn.aggregate_range_2
  201. ? '+'
  202. : '-'
  203. : null}
  204. {formatPercentage(
  205. relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
  206. )}
  207. </div>
  208. </RegressedFunctionMetricsRow>
  209. <RegressedFunctionSparklineContainer>
  210. <ProfilingSparklineChart
  211. name="p95(function.duration)"
  212. points={trendToPoints(fn)}
  213. color={trendType === 'improvement' ? theme.green300 : theme.red300}
  214. aggregate_range_1={fn.aggregate_range_1}
  215. aggregate_range_2={fn.aggregate_range_2}
  216. breakpoint={fn.breakpoint}
  217. start={fn.stats.data[0][0]}
  218. end={fn.stats.data[fn.stats.data.length - 1][0]}
  219. />
  220. </RegressedFunctionSparklineContainer>
  221. </RegressedFunctionRow>
  222. );
  223. })
  224. )}
  225. </RegressedFunctionsContainer>
  226. );
  227. }
  228. interface RegressedFunctionDifferentialFlamegraphProps {
  229. fn: FunctionTrend;
  230. organization: Organization;
  231. project: Project | null;
  232. transaction: string;
  233. }
  234. function RegressedFunctionDifferentialFlamegraph(
  235. props: RegressedFunctionDifferentialFlamegraphProps
  236. ) {
  237. const onRegressedFunctionClick = useCallback(() => {
  238. trackAnalytics('profiling_views.go_to_differential_flamegraph', {
  239. organization: props.organization,
  240. source: `profiling_transaction.regressed_functions_table`,
  241. });
  242. }, [props.organization]);
  243. const differentialFlamegraphLink = generateProfileDifferentialFlamegraphRouteWithQuery({
  244. orgSlug: props.organization.slug,
  245. projectSlug: props.project?.slug ?? '',
  246. transaction: props.transaction,
  247. fingerprint: props.fn.fingerprint,
  248. breakpoint: props.fn.breakpoint,
  249. query: {
  250. // specify the frame to focus, the flamegraph will switch
  251. // to the appropriate thread when these are specified
  252. frameName: props.fn.function as string,
  253. framePackage: props.fn.package as string,
  254. },
  255. });
  256. return (
  257. <RegressedFunctionMainRow>
  258. <div>
  259. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  260. <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>
  261. </Link>
  262. </div>
  263. <div>
  264. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  265. <PerformanceDuration
  266. abbreviation
  267. nanoseconds={props.fn.aggregate_range_1 as number}
  268. />
  269. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  270. <PerformanceDuration
  271. abbreviation
  272. nanoseconds={props.fn.aggregate_range_2 as number}
  273. />
  274. </Link>
  275. </div>
  276. </RegressedFunctionMainRow>
  277. );
  278. }
  279. interface RegressedFunctionBeforeAfterProps {
  280. after: Profiling.BaseProfileReference | null;
  281. before: Profiling.BaseProfileReference | null;
  282. fn: FunctionTrend;
  283. organization: Organization;
  284. project: Project | null;
  285. }
  286. function RegressedFunctionBeforeAfterFlamechart(
  287. props: RegressedFunctionBeforeAfterProps
  288. ) {
  289. const onRegressedFunctionClick = useCallback(() => {
  290. trackAnalytics('profiling_views.go_to_flamegraph', {
  291. organization: props.organization,
  292. source: `profiling_transaction.regressed_functions_table`,
  293. });
  294. }, [props.organization]);
  295. let rendered = <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>;
  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 as string,
  308. framePackage: props.fn.package as string,
  309. })}
  310. >
  311. {rendered}
  312. </Link>
  313. );
  314. }
  315. let before = (
  316. <PerformanceDuration
  317. abbreviation
  318. nanoseconds={props.fn.aggregate_range_1 as number}
  319. />
  320. );
  321. if (props.before) {
  322. before = (
  323. <Link
  324. onClick={onRegressedFunctionClick}
  325. to={generateProfileRouteFromProfileReference({
  326. orgSlug: props.organization.slug,
  327. projectSlug: props.project?.slug ?? '',
  328. reference: props.before,
  329. // specify the frame to focus, the flamegraph will switch
  330. // to the appropriate thread when these are specified
  331. frameName: props.fn.function as string,
  332. framePackage: props.fn.package as string,
  333. })}
  334. >
  335. {before}
  336. </Link>
  337. );
  338. }
  339. let after = (
  340. <PerformanceDuration
  341. abbreviation
  342. nanoseconds={props.fn.aggregate_range_2 as number}
  343. />
  344. );
  345. if (props.after) {
  346. after = (
  347. <Link
  348. onClick={onRegressedFunctionClick}
  349. to={generateProfileRouteFromProfileReference({
  350. orgSlug: props.organization.slug,
  351. projectSlug: props.project?.slug ?? '',
  352. reference: props.after,
  353. // specify the frame to focus, the flamegraph will switch
  354. // to the appropriate thread when these are specified
  355. frameName: props.fn.function as string,
  356. framePackage: props.fn.package as string,
  357. })}
  358. >
  359. {after}
  360. </Link>
  361. );
  362. }
  363. return (
  364. <RegressedFunctionMainRow>
  365. <div>{rendered}</div>
  366. <div>
  367. {before}
  368. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  369. {after}
  370. </div>
  371. </RegressedFunctionMainRow>
  372. );
  373. }
  374. const ChangeArrow = styled('span')`
  375. color: ${p => p.theme.subText};
  376. `;
  377. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  378. button {
  379. margin: 0;
  380. padding: 0;
  381. }
  382. `;
  383. const RegressedFunctionSparklineContainer = styled('div')``;
  384. const RegressedFunctionRow = styled('div')`
  385. position: relative;
  386. margin-bottom: ${space(1)};
  387. `;
  388. const RegressedFunctionMainRow = styled('div')`
  389. display: flex;
  390. align-items: center;
  391. justify-content: space-between;
  392. > div:first-child {
  393. min-width: 0;
  394. }
  395. > div:last-child {
  396. white-space: nowrap;
  397. }
  398. `;
  399. const RegressedFunctionMetricsRow = styled('div')`
  400. display: flex;
  401. align-items: center;
  402. justify-content: space-between;
  403. font-size: ${p => p.theme.fontSizeSmall};
  404. color: ${p => p.theme.subText};
  405. margin-top: ${space(0.25)};
  406. `;
  407. const RegressedFunctionsContainer = styled('div')`
  408. flex-basis: 80px;
  409. padding: 0 ${space(1)};
  410. border-bottom: 1px solid ${p => p.theme.border};
  411. `;
  412. const RegressedFunctionsPagination = styled(Pagination)`
  413. margin: 0;
  414. button {
  415. height: 16px;
  416. width: 16px;
  417. min-width: 16px;
  418. min-height: 16px;
  419. svg {
  420. width: 10px;
  421. height: 10px;
  422. }
  423. }
  424. `;
  425. const RegressedFunctionsTitleContainer = styled('div')`
  426. display: flex;
  427. align-items: center;
  428. justify-content: space-between;
  429. margin-bottom: ${space(0.5)};
  430. margin-top: ${space(0.5)};
  431. `;
  432. const RegressedFunctionsQueryState = styled('div')`
  433. text-align: center;
  434. padding: ${space(2)} ${space(0.5)};
  435. color: ${p => p.theme.subText};
  436. `;
  437. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  438. const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
  439. {
  440. label: t('Most Regressed Functions'),
  441. value: 'regression' as const,
  442. },
  443. {
  444. label: t('Most Improved Functions'),
  445. value: 'improvement' as const,
  446. },
  447. ];