Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: span percentile - UI (#9397)

Yunus Mf5bf4293a169
diff --git a/frontend/src/api/trace/getSpanPercentiles.ts b/frontend/src/api/trace/getSpanPercentiles.ts
new file mode 100644
index 0000000000..7d275401ba
--- /dev/null
+++ b/frontend/src/api/trace/getSpanPercentiles.ts
@@ -0,0 +1,28 @@
+import { ApiBaseInstance } from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import {
+ GetSpanPercentilesProps,
+ GetSpanPercentilesResponseDataProps,
+} from 'types/api/trace/getSpanPercentiles';
+
+const getSpanPercentiles = async (
+ props: GetSpanPercentilesProps,
+): Promise<SuccessResponseV2<GetSpanPercentilesResponseDataProps>> => {
+ try {
+ const response = await ApiBaseInstance.post('/span_percentile', {
+ ...props,
+ });
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ throw error;
+ }
+};
+
+export default getSpanPercentiles;
diff --git a/frontend/src/constants/dateTimeFormats.ts b/frontend/src/constants/dateTimeFormats.ts
index 701051700a..0afccc3ff9 100644
--- a/frontend/src/constants/dateTimeFormats.ts
+++ b/frontend/src/constants/dateTimeFormats.ts
@@ -24,6 +24,7 @@ export const DATE_TIME_FORMATS = {
TIME_SECONDS: 'HH:mm:ss',
TIME_UTC: 'HH:mm:ss (UTC Z)',
TIME_UTC_MS: 'HH:mm:ss.SSS (UTC Z)',
+ TIME_SPAN_PERCENTILE: 'HH:mm:ss MMM DD',
// Short date formats
DATE_SHORT: 'MM/DD',
diff --git a/frontend/src/constants/reactQueryKeys.ts b/frontend/src/constants/reactQueryKeys.ts
index 2809e0b7c7..88ab13ab26 100644
--- a/frontend/src/constants/reactQueryKeys.ts
+++ b/frontend/src/constants/reactQueryKeys.ts
@@ -90,4 +90,7 @@ export const REACT_QUERY_KEY = {
// Routing Policies Query Keys
GET_ROUTING_POLICIES: 'GET_ROUTING_POLICIES',
+
+ // Span Percentiles Query Keys
+ GET_SPAN_PERCENTILES: 'GET_SPAN_PERCENTILES',
} as const;
diff --git a/frontend/src/constants/userPreferences.ts b/frontend/src/constants/userPreferences.ts
index fdec6cc39e..8f9cba137e 100644
--- a/frontend/src/constants/userPreferences.ts
+++ b/frontend/src/constants/userPreferences.ts
@@ -3,4 +3,5 @@ export const USER_PREFERENCES = {
NAV_SHORTCUTS: 'nav_shortcuts',
LAST_SEEN_CHANGELOG_VERSION: 'last_seen_changelog_version',
SPAN_DETAILS_PINNED_ATTRIBUTES: 'span_details_pinned_attributes',
+ SPAN_PERCENTILE_RESOURCE_ATTRIBUTES: 'span_percentile_resource_attributes',
};
diff --git a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.styles.scss b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.styles.scss
index 54179aa26f..5a06b43a7d 100644
--- a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.styles.scss
+++ b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.styles.scss
@@ -55,6 +55,337 @@
flex-direction: column;
gap: 8px;
+ .span-name-wrapper {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+
+ .loading-spinner-container {
+ padding: 4px 8px;
+ line-height: 18px; /* 128.571% */
+ letter-spacing: -0.07px;
+
+ display: inline-flex;
+ }
+
+ .span-percentile-value {
+ color: var(--text-sakura-400, #f56c87);
+ font-variant-numeric: lining-nums tabular-nums stacked-fractions
+ slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on;
+ font-family: Inter;
+ font-size: 14px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 18px; /* 128.571% */
+ letter-spacing: -0.07px;
+ min-width: 48px;
+ padding: 4px 8px;
+
+ border-left: 1px solid var(--bg-slate-400);
+
+ cursor: pointer;
+ }
+ }
+
+ .span-percentiles-container {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+
+ fill: linear-gradient(
+ 139deg,
+ rgba(18, 19, 23, 0.32) 0%,
+ rgba(18, 19, 23, 0.36) 98.68%
+ );
+
+ stroke-width: 1px;
+ stroke: var(--bg-slate-500, #161922);
+ filter: drop-shadow(2px 4px 16px rgba(0, 0, 0, 0.2));
+ backdrop-filter: blur(20px);
+ border: 1px solid var(--bg-slate-500);
+ border-radius: 4px;
+
+ .span-percentiles-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 8px 12px 8px 12px;
+ border-bottom: 1px solid var(--bg-slate-500);
+
+ .span-percentiles-header-text {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ }
+ }
+
+ .span-percentile-content {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 8px;
+
+ .span-percentile-content-title {
+ .span-percentile-value {
+ color: var(--text-sakura-400, #f56c87);
+ font-variant-numeric: lining-nums tabular-nums stacked-fractions
+ slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on;
+ }
+
+ .span-percentile-value-loader {
+ display: inline-flex;
+ align-items: flex-end;
+ justify-content: flex-end;
+ margin-right: 4px;
+ margin-left: 4px;
+ line-height: 18px;
+ }
+ }
+
+ .span-percentile-timerange {
+ width: 100%;
+
+ .span-percentile-timerange-select {
+ width: 100%;
+ margin-top: 8px;
+ margin-bottom: 16px;
+
+ .ant-select-selector {
+ border-radius: 50px;
+ border: 1px solid var(--bg-slate-400, #1d212d);
+ background: var(--bg-slate-500, #161922);
+ color: var(--bg-vanilla-400);
+ font-family: Inter;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 20px; /* 142.857% */
+ letter-spacing: 0.28px;
+
+ height: 32px;
+ }
+ }
+ }
+
+ .span-percentile-values-table {
+ .span-percentile-values-table-header-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+
+ .span-percentile-values-table-header {
+ color: var(--text-vanilla-400);
+ text-align: right;
+ font-family: Inter;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 20px; /* 181.818% */
+ text-transform: uppercase;
+ }
+ }
+
+ .span-percentile-values-table-data-rows {
+ margin-top: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+
+ .span-percentile-values-table-data-rows-skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+
+ .ant-skeleton-title {
+ width: 100% !important;
+ margin-top: 0px !important;
+ }
+
+ .ant-skeleton-paragraph {
+ margin-top: 8px;
+
+ & > li + li {
+ margin-top: 10px;
+ width: 100% !important;
+ }
+ }
+ }
+ }
+
+ .span-percentile-values-table-data-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 0px 4px;
+
+ .span-percentile-values-table-data-row-key {
+ flex: 0 0 auto;
+ color: var(--text-vanilla-100);
+ text-align: right;
+ font-variant-numeric: lining-nums tabular-nums slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on;
+ font-family: Inter;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 20px; /* 166.667% */
+ }
+
+ .span-percentile-values-table-data-row-value {
+ color: var(--text-vanilla-400);
+ font-variant-numeric: lining-nums tabular-nums stacked-fractions
+ slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on, 'ss02' on;
+ font-family: Inter;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 20px; /* 166.667% */
+ }
+
+ .dashed-line {
+ flex: 1;
+ height: 0; /* line only */
+ margin: 0 8px;
+ border-top: 1px dashed var(--bg-slate-300);
+
+ /* Use border image to control dash length & spacing */
+ border-top-width: 1px;
+ border-top-style: solid; /* temporary solid for image */
+ border-image: repeating-linear-gradient(
+ to right,
+ #1d212d 0,
+ #1d212d 10px,
+ transparent 10px,
+ transparent 20px
+ )
+ 1 stretch;
+ }
+ }
+
+ .current-span-percentile-row {
+ border-radius: 2px;
+ background: rgba(78, 116, 248, 0.2);
+
+ .span-percentile-values-table-data-row-key {
+ color: var(--text-robin-300);
+ }
+
+ .dashed-line {
+ flex: 1;
+ height: 0; /* line only */
+ margin: 0 8px;
+ border-top: 1px dashed #abbdff;
+
+ /* Use border image to control dash length & spacing */
+ border-top-width: 1px;
+ border-top-style: solid; /* temporary solid for image */
+ border-image: repeating-linear-gradient(
+ to right,
+ #abbdff 0,
+ #abbdff 10px,
+ transparent 10px,
+ transparent 20px
+ )
+ 1 stretch;
+ }
+
+ .span-percentile-values-table-data-row-value {
+ color: var(--text-robin-400);
+ }
+ }
+ }
+ }
+
+ .resource-attributes-select-container {
+ overflow: hidden;
+ width: calc(100% + 16px);
+
+ position: absolute;
+ top: 32px;
+ left: -8px;
+ z-index: 1000;
+
+ .resource-attributes-select-container-header {
+ .resource-attributes-select-container-input {
+ border-radius: 0px;
+ border: none !important;
+ box-shadow: none !important;
+ height: 36px;
+
+ border-bottom: 1px solid var(--bg-slate-400) !important;
+ }
+ }
+
+ border-radius: 4px;
+ border: 1px solid var(--bg-slate-400, #1d212d);
+ background: linear-gradient(
+ 139deg,
+ rgba(18, 19, 23, 1) 0%,
+ rgba(18, 19, 23, 1) 98.68%
+ );
+ box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
+ backdrop-filter: blur(20px);
+
+ .ant-select {
+ width: 100%;
+ }
+
+ .resource-attributes-items {
+ height: 200px;
+ overflow-y: auto;
+
+ &::-webkit-scrollbar {
+ width: 0.3rem;
+ height: 0.3rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--bg-slate-300);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: var(--bg-slate-200);
+ }
+ }
+
+ .resource-attributes-select-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px 8px 12px;
+
+ .resource-attributes-select-item-checkbox {
+ .ant-checkbox-disabled {
+ background-color: var(--bg-robin-500);
+ color: var(--bg-vanilla-100);
+ }
+
+ .resource-attributes-select-item-value {
+ color: var(--bg-vanilla-100);
+
+ font-family: Inter;
+ font-size: 13px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 20px; /* 142.857% */
+ letter-spacing: -0.07px;
+ }
+ }
+ }
+ }
+ }
+
.attribute-key {
color: var(--bg-vanilla-400);
font-family: Inter;
@@ -68,7 +399,6 @@
.value-wrapper {
display: flex;
- padding: 2px 8px;
align-items: center;
width: fit-content;
max-width: 100%;
@@ -77,6 +407,7 @@
background: var(--bg-slate-500);
.attribute-value {
+ padding: 2px 8px;
color: var(--bg-vanilla-400);
font-family: 'Inter';
font-size: 14px;
@@ -200,6 +531,44 @@
}
}
+.span-percentile-tooltip {
+ .ant-tooltip-content {
+ width: 300px;
+ max-width: 300px;
+ }
+
+ .span-percentile-tooltip-text {
+ color: var(--text-vanilla-400);
+ font-variant-numeric: lining-nums tabular-nums stacked-fractions ordinal
+ slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on;
+ font-family: Inter;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 20px; /* 166.667% */
+ letter-spacing: -0.06px;
+
+ .span-percentile-tooltip-text-percentile {
+ color: var(--text-sakura-500);
+ font-variant-numeric: lining-nums tabular-nums stacked-fractions slashed-zero;
+ font-feature-settings: 'dlig' on, 'salt' on;
+ font-family: Inter;
+ font-size: 12px;
+ }
+
+ .span-percentile-tooltip-text-link {
+ color: var(--text-vanilla-400);
+ text-align: right;
+ font-family: Inter;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 20px; /* 166.667% */
+ }
+ }
+}
+
.span-details-drawer-docked {
width: 48px;
flex: 0 48px !important;
@@ -208,6 +577,7 @@
justify-content: center;
}
}
+
.resizable-handle {
box-sizing: border-box;
border: 2px solid transparent;
@@ -234,6 +604,164 @@
.description {
.item {
+ .span-name-wrapper {
+ .span-percentile-value {
+ color: var(--text-sakura-400, #f56c87);
+ border-left: 1px solid var(--bg-slate-300);
+ }
+ }
+
+ .span-percentiles-container {
+ fill: linear-gradient(
+ 139deg,
+ rgba(18, 19, 23, 0.32) 0%,
+ rgba(18, 19, 23, 0.36) 98.68%
+ );
+
+ stroke-width: 1px;
+ stroke: var(--bg-slate-500);
+ filter: drop-shadow(2px 4px 16px rgba(0, 0, 0, 0.2));
+ backdrop-filter: blur(20px);
+ border: 1px solid var(--bg-vanilla-300);
+ border-radius: 4px;
+
+ .span-percentiles-header {
+ border-bottom: 1px solid var(--bg-vanilla-300);
+ }
+
+ .span-percentile-content {
+ .span-percentile-content-title {
+ .span-percentile-value {
+ color: var(--text-sakura-400, #f56c87);
+ }
+ }
+
+ .span-percentile-timerange {
+ .span-percentile-timerange-select {
+ .ant-select-selector {
+ border: 1px solid var(--bg-vanilla-300);
+ background: var(--bg-vanilla-300);
+ color: var(--text-slate-300);
+ }
+ }
+ }
+
+ .span-percentile-values-table {
+ .span-percentile-values-table-header-row {
+ .span-percentile-values-table-header {
+ color: var(--text-vanilla-400);
+ }
+ }
+
+ .span-percentile-values-table-data-row {
+ .span-percentile-values-table-data-row-key {
+ color: var(--text-ink-100);
+ }
+
+ .span-percentile-values-table-data-row-value {
+ color: var(--text-ink-400);
+ }
+
+ .dashed-line {
+ flex: 1;
+ height: 0; /* line only */
+ margin: 0 8px;
+ border-top: 1px dashed var(--bg-slate-300);
+
+ /* Use border image to control dash length & spacing */
+ border-top-width: 1px;
+ border-top-style: solid; /* temporary solid for image */
+ border-image: repeating-linear-gradient(
+ to right,
+ var(--bg-slate-300) 0,
+ var(--bg-slate-300) 10px,
+ transparent 10px,
+ transparent 20px
+ )
+ 1 stretch;
+ }
+ }
+
+ .current-span-percentile-row {
+ border-radius: 2px;
+ background: rgba(78, 116, 248, 0.2);
+
+ .span-percentile-values-table-data-row-key {
+ color: var(--text-robin-300, #95acfb);
+ }
+
+ .dashed-line {
+ border-top: 1px dashed #abbdff;
+
+ /* Use border image to control dash length & spacing */
+ border-top-width: 1px;
+ border-top-style: solid; /* temporary solid for image */
+ border-image: repeating-linear-gradient(
+ to right,
+ #abbdff 0,
+ #abbdff 10px,
+ transparent 10px,
+ transparent 20px
+ )
+ 1 stretch;
+ }
+
+ .span-percentile-values-table-data-row-value {
+ color: var(--text-robin-400);
+ }
+ }
+ }
+ }
+
+ .resource-attributes-select-container {
+ .resource-attributes-select-container-header {
+ .resource-attributes-select-container-input {
+ border: none !important;
+ box-shadow: none !important;
+ height: 36px;
+
+ border-bottom: 1px solid var(--bg-vanilla-400) !important;
+ background: var(--bg-vanilla-300);
+ color: var(--text-ink-400);
+ }
+ }
+
+ border-radius: 4px;
+ border: 1px solid var(--bg-vanilla-300);
+ background: var(--bg-vanilla-300);
+ box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12),
+ 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);
+ backdrop-filter: blur(20px);
+
+ .resource-attributes-items {
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--bg-slate-300);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: var(--bg-slate-200);
+ }
+ }
+
+ .resource-attributes-select-item {
+ .resource-attributes-select-item-checkbox {
+ .ant-checkbox-disabled {
+ background-color: var(--bg-robin-500);
+ color: var(--text-ink-100);
+ }
+
+ .resource-attributes-select-item-value {
+ color: var(--text-ink-100);
+ }
+ }
+ }
+ }
+ }
+
.attribute-key {
color: var(--bg-ink-400);
}
diff --git a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
index eddbee1167..9dd55f2377 100644
--- a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
+++ b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
@@ -1,27 +1,53 @@
import './SpanDetailsDrawer.styles.scss';
-import { Button, Tabs, TabsProps, Tooltip, Typography } from 'antd';
+import {
+ Button,
+ Checkbox,
+ Input,
+ Select,
+ Skeleton,
+ Tabs,
+ TabsProps,
+ Tooltip,
+ Typography,
+} from 'antd';
import { RadioChangeEvent } from 'antd/lib';
+import getSpanPercentiles from 'api/trace/getSpanPercentiles';
+import getUserPreference from 'api/v1/user/preferences/name/get';
+import updateUserPreference from 'api/v1/user/preferences/name/update';
import LogsIcon from 'assets/AlertHistory/LogsIcon';
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import SignozRadioGroup from 'components/SignozRadioGroup/SignozRadioGroup';
+import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { themeColors } from 'constants/theme';
+import { USER_PREFERENCES } from 'constants/userPreferences';
+import dayjs from 'dayjs';
+import useClickOutside from 'hooks/useClickOutside';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
import {
Anvil,
BarChart2,
Bookmark,
+ Check,
+ ChevronDown,
Link2,
+ Loader2,
PanelRight,
+ PlusIcon,
Search,
} from 'lucide-react';
+import { AnimatePresence, motion } from 'motion/react';
import {
Dispatch,
SetStateAction,
useCallback,
+ useEffect,
useMemo,
+ useRef,
useState,
} from 'react';
+import { useMutation, useQuery } from 'react-query';
import { Span } from 'types/api/trace/getTraceV2';
import { formatEpochTimestamp } from 'utils/timeUtils';
@@ -40,6 +66,45 @@ interface ISpanDetailsDrawerProps {
traceEndTime: number;
}
+const timerangeOptions = [
+ {
+ label: '1 hour',
+ value: 1,
+ },
+ {
+ label: '2 hours',
+ value: 2,
+ },
+ {
+ label: '3 hours',
+ value: 3,
+ },
+ {
+ label: '6 hours',
+ value: 6,
+ },
+ {
+ label: '12 hours',
+ value: 12,
+ },
+ {
+ label: '24 hours',
+ value: 24,
+ },
+];
+
+interface IResourceAttribute {
+ key: string;
+ value: string;
+ isSelected: boolean;
+}
+
+const DEFAULT_RESOURCE_ATTRIBUTES = {
+ serviceName: 'service.name',
+ name: 'name',
+};
+
+// eslint-disable-next-line sonarjs/cognitive-complexity
function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
const {
isSpanDetailsDocked,
@@ -53,12 +118,60 @@ function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
const [shouldAutoFocusSearch, setShouldAutoFocusSearch] = useState<boolean>(
false,
);
+ const [isSpanPercentilesOpen, setIsSpanPercentilesOpen] = useState<boolean>(
+ false,
+ );
const [isRelatedSignalsOpen, setIsRelatedSignalsOpen] = useState<boolean>(
false,
);
const [activeDrawerView, setActiveDrawerView] = useState<RelatedSignalsViews>(
RelatedSignalsViews.LOGS,
);
+
+ const [selectedTimeRange, setSelectedTimeRange] = useState<number>(1);
+ const [
+ resourceAttributesSearchQuery,
+ setResourceAttributesSearchQuery,
+ ] = useState<string>('');
+
+ const [spanPercentileData, setSpanPercentileData] = useState<{
+ percentile: number;
+ description: string;
+ percentiles: Record<string, number>;
+ } | null>(null);
+
+ const [
+ showResourceAttributesSelector,
+ setShowResourceAttributesSelector,
+ ] = useState<boolean>(false);
+
+ const [selectedResourceAttributes, setSelectedResourceAttributes] = useState<
+ Record<string, string>
+ >({});
+
+ const [spanResourceAttributes, updateSpanResourceAttributes] = useState<
+ IResourceAttribute[]
+ >([] as IResourceAttribute[]);
+
+ const [initialWaitCompleted, setInitialWaitCompleted] = useState<boolean>(
+ false,
+ );
+
+ const [
+ shouldFetchSpanPercentilesData,
+ setShouldFetchSpanPercentilesData,
+ ] = useState<boolean>(false);
+
+ const [
+ shouldUpdateUserPreference,
+ setShouldUpdateUserPreference,
+ ] = useState<boolean>(false);
+
+ const handleTimeRangeChange = useCallback((value: number): void => {
+ setShouldFetchSpanPercentilesData(true);
+ setSelectedTimeRange(value);
+ }, []);
+
const color = generateColor(
selectedSpan?.serviceName || '',
themeColors.traceDetailColors,
@@ -166,6 +279,265 @@ function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
];
}
+ const resourceAttributesSelectorRef = useRef<HTMLDivElement | null>(null);
+
+ useClickOutside({
+ ref: resourceAttributesSelectorRef,
+ onClickOutside: () => {
+ if (resourceAttributesSelectorRef.current) {
+ setShowResourceAttributesSelector(false);
+ }
+ },
+ eventType: 'mousedown',
+ });
+
+ const spanPercentileTooltipText = useMemo(
+ () => (
+ <div className="span-percentile-tooltip-text">
+ <Typography.Text>
+ This span duration is{' '}
+ <span className="span-percentile-tooltip-text-percentile">
+ p{Math.floor(spanPercentileData?.percentile || 0)}
+ </span>{' '}
+ out of the distribution for this resource evaluated for {selectedTimeRange}{' '}
+ hour(s) since the span start time.
+ </Typography.Text>
+ <br />
+ <br />
+ <Typography.Text className="span-percentile-tooltip-text-link">
+ Click to learn more
+ </Typography.Text>
+ </div>
+ ),
+ [spanPercentileData?.percentile, selectedTimeRange],
+ );
+
+ const endTime = useMemo(
+ () => Math.floor(Number(selectedSpan?.timestamp) / 1000) * 1000,
+ [selectedSpan?.timestamp],
+ );
+
+ const startTime = useMemo(
+ () =>
+ dayjs(selectedSpan?.timestamp)
+ .subtract(Number(selectedTimeRange), 'hour')
+ .unix() * 1000,
+ [selectedSpan?.timestamp, selectedTimeRange],
+ );
+
+ const { mutate: updateUserPreferenceMutation } = useMutation(
+ updateUserPreference,
+ );
+
+ // TODO: Span percentile should be eventually moved to context and not fetched on every span change
+ const {
+ data: userSelectedResourceAttributes,
+ isError: isErrorUserSelectedResourceAttributes,
+ } = useQuery({
+ queryFn: () =>
+ getUserPreference({
+ name: USER_PREFERENCES.SPAN_PERCENTILE_RESOURCE_ATTRIBUTES,
+ }),
+ queryKey: [
+ 'getUserPreferenceByPreferenceName',
+ USER_PREFERENCES.SPAN_PERCENTILE_RESOURCE_ATTRIBUTES,
+ selectedSpan?.spanId,
+ ],
+ enabled: selectedSpan !== null && selectedSpan?.tagMap !== undefined,
+ });
+
+ const {
+ isLoading: isLoadingSpanPercentilesData,
+ isFetching: isFetchingSpanPercentilesData,
+ data,
+ refetch: refetchSpanPercentilesData,
+ isError: isErrorSpanPercentilesData,
+ } = useQuery({
+ queryFn: () =>
+ getSpanPercentiles({
+ start: startTime || 0,
+ end: endTime || 0,
+ spanDuration: selectedSpan?.durationNano || 0,
+ serviceName: selectedSpan?.serviceName || '',
+ name: selectedSpan?.name || '',
+ resourceAttributes: selectedResourceAttributes,
+ }),
+ queryKey: [
+ REACT_QUERY_KEY.GET_SPAN_PERCENTILES,
+ selectedSpan?.spanId,
+ startTime,
+ endTime,
+ ],
+ enabled:
+ selectedSpan !== null &&
+ shouldFetchSpanPercentilesData &&
+ !showResourceAttributesSelector &&
+ initialWaitCompleted,
+ onSuccess: (response) => {
+ if (response.httpStatusCode !== 200) {
+ return;
+ }
+
+ if (shouldUpdateUserPreference) {
+ updateUserPreferenceMutation({
+ name: USER_PREFERENCES.SPAN_PERCENTILE_RESOURCE_ATTRIBUTES,
+ value: [...Object.keys(selectedResourceAttributes)],
+ });
+
+ setShouldUpdateUserPreference(false);
+ }
+ },
+ });
+
+ // Prod Req - Wait for 2 seconds before fetching span percentile data on initial load
+ useEffect(() => {
+ setInitialWaitCompleted(false);
+
+ const timer = setTimeout(() => {
+ setInitialWaitCompleted(true);
+ }, 2000); // 2-second delay
+
+ return (): void => clearTimeout(timer); // Cleanup on re-run or unmount
+ }, [selectedSpan?.spanId]);
+
+ useEffect(() => {
+ if (data?.httpStatusCode !== 200) {
+ setSpanPercentileData(null);
+
+ return;
+ }
+
+ if (data) {
+ const percentileData = {
+ percentile: data?.data?.position?.percentile || 0,
+ description: data?.data?.position?.description || '',
+ percentiles: data?.data?.percentiles || {},
+ };
+
+ setSpanPercentileData(percentileData);
+ }
+ }, [data]);
+
+ useEffect(() => {
+ if (userSelectedResourceAttributes) {
+ const userSelectedResourceAttributesList = (userSelectedResourceAttributes
+ ?.data?.value as string[]).map((attribute: string) => attribute);
+
+ let selectedResourceAttributesMap: Record<string, string> = {};
+
+ userSelectedResourceAttributesList.forEach((attribute: string) => {
+ selectedResourceAttributesMap[attribute] =
+ selectedSpan?.tagMap?.[attribute] || '';
+ });
+
+ // filter out the attributes that are not in the selectedSpan?.tagMap
+ selectedResourceAttributesMap = Object.fromEntries(
+ Object.entries(selectedResourceAttributesMap).filter(
+ ([key]) => selectedSpan?.tagMap?.[key] !== undefined,
+ ),
+ );
+
+ const resourceAttributes = Object.entries(selectedSpan?.tagMap || {}).map(
+ ([key, value]) => ({
+ key,
+ value,
+ isSelected:
+ key === DEFAULT_RESOURCE_ATTRIBUTES.serviceName ||
+ key === DEFAULT_RESOURCE_ATTRIBUTES.name ||
+ (key in selectedResourceAttributesMap &&
+ selectedResourceAttributesMap[key] !== '' &&
+ selectedResourceAttributesMap[key] !== undefined),
+ }),
+ );
+
+ // selected resources should be at the top of the list
+ const selectedResourceAttributes = resourceAttributes.filter(
+ (resourceAttribute) => resourceAttribute.isSelected,
+ );
+
+ const unselectedResourceAttributes = resourceAttributes.filter(
+ (resourceAttribute) => !resourceAttribute.isSelected,
+ );
+
+ const sortedResourceAttributes = [
+ ...selectedResourceAttributes,
+ ...unselectedResourceAttributes,
+ ];
+
+ updateSpanResourceAttributes(sortedResourceAttributes);
+
+ setSelectedResourceAttributes(
+ selectedResourceAttributesMap as Record<string, string>,
+ );
+
+ setShouldFetchSpanPercentilesData(true);
+ }
+
+ if (isErrorUserSelectedResourceAttributes) {
+ const resourceAttributes = Object.entries(selectedSpan?.tagMap || {}).map(
+ ([key, value]) => ({
+ key,
+ value,
+ isSelected:
+ key === DEFAULT_RESOURCE_ATTRIBUTES.serviceName ||
+ key === DEFAULT_RESOURCE_ATTRIBUTES.name,
+ }),
+ );
+
+ updateSpanResourceAttributes(resourceAttributes);
+
+ setShouldFetchSpanPercentilesData(true);
+ }
+ }, [
+ userSelectedResourceAttributes,
+ isErrorUserSelectedResourceAttributes,
+ selectedSpan?.tagMap,
+ ]);
+
+ const handleResourceAttributeChange = useCallback(
+ (key: string, value: string, isSelected: boolean): void => {
+ updateSpanResourceAttributes((prev) =>
+ prev.map((resourceAttribute) =>
+ resourceAttribute.key === key
+ ? { ...resourceAttribute, isSelected }
+ : resourceAttribute,
+ ),
+ );
+
+ const newSelectedResourceAttributes = { ...selectedResourceAttributes };
+
+ if (isSelected) {
+ newSelectedResourceAttributes[key] = value;
+ } else {
+ delete newSelectedResourceAttributes[key];
+ }
+
+ setSelectedResourceAttributes(newSelectedResourceAttributes);
+
+ setShouldFetchSpanPercentilesData(true);
+
+ setShouldUpdateUserPreference(true);
+ },
+ [selectedResourceAttributes],
+ );
+
+ useEffect(() => {
+ if (
+ shouldFetchSpanPercentilesData &&
+ !showResourceAttributesSelector &&
+ initialWaitCompleted
+ ) {
+ refetchSpanPercentilesData();
+
+ setShouldFetchSpanPercentilesData(false);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ shouldFetchSpanPercentilesData,
+ showResourceAttributesSelector,
+ initialWaitCompleted,
+ ]);
+
return (
<>
<section className="header">
@@ -186,13 +558,226 @@ function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
<section className="description">
<div className="item">
<Typography.Text className="attribute-key">span name</Typography.Text>
- <Tooltip title={selectedSpan.name}>
- <div className="value-wrapper">
+
+ <div className="value-wrapper span-name-wrapper">
+ <Tooltip title={selectedSpan.name}>
<Typography.Text className="attribute-value" ellipsis>
{selectedSpan.name}
</Typography.Text>
- </div>
- </Tooltip>
+ </Tooltip>
+
+ {isLoadingSpanPercentilesData && (
+ <div className="loading-spinner-container">
+ <Loader2 size={16} className="animate-spin" />
+ </div>
+ )}
+
+ {!isLoadingSpanPercentilesData && spanPercentileData && (
+ <Tooltip
+ title={isSpanPercentilesOpen ? '' : spanPercentileTooltipText}
+ placement="bottomRight"
+ overlayClassName="span-percentile-tooltip"
+ arrow={false}
+ >
+ <Typography.Text
+ className="span-percentile-value"
+ onClick={(): void => setIsSpanPercentilesOpen((prev) => !prev)}
+ >
+ p{Math.floor(spanPercentileData?.percentile || 0)}
+ </Typography.Text>
+ </Tooltip>
+ )}
+ </div>
+
+ <AnimatePresence initial={false}>
+ {isSpanPercentilesOpen && !isErrorSpanPercentilesData && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ key="box"
+ >
+ <div className="span-percentiles-container">
+ <div className="span-percentiles-header">
+ <Typography.Text
+ className="span-percentiles-header-text"
+ onClick={(): void => setIsSpanPercentilesOpen((prev) => !prev)}
+ >
+ <ChevronDown size={16} /> Span Percentile
+ </Typography.Text>
+
+ {showResourceAttributesSelector ? (
+ <Check
+ data-testid="check-icon"
+ size={16}
+ className="cursor-pointer span-percentiles-header-icon"
+ onClick={(): void => setShowResourceAttributesSelector(false)}
+ />
+ ) : (
+ <PlusIcon
+ data-testid="plus-icon"
+ size={16}
+ className="cursor-pointer span-percentiles-header-icon"
+ onClick={(): void => setShowResourceAttributesSelector(true)}
+ />
+ )}
+ </div>
+
+ {showResourceAttributesSelector && (
+ <div
+ className="resource-attributes-select-container"
+ ref={resourceAttributesSelectorRef}
+ >
+ <div className="resource-attributes-select-container-header">
+ <Input
+ placeholder="Search resource attributes"
+ className="resource-attributes-select-container-input"
+ value={resourceAttributesSearchQuery}
+ onChange={(e): void =>
+ setResourceAttributesSearchQuery(e.target.value as string)
+ }
+ />
+ </div>
+
+ <div className="resource-attributes-items">
+ {spanResourceAttributes
+ .filter((resourceAttribute) =>
+ resourceAttribute.key
+ .toLowerCase()
+ .includes(resourceAttributesSearchQuery.toLowerCase()),
+ )
+ .map((resourceAttribute) => (
+ <div
+ className="resource-attributes-select-item"
+ key={resourceAttribute.key}
+ >
+ <div className="resource-attributes-select-item-checkbox">
+ <Checkbox
+ checked={resourceAttribute.isSelected}
+ onChange={(e): void => {
+ handleResourceAttributeChange(
+ resourceAttribute.key,
+ resourceAttribute.value,
+ e.target.checked,
+ );
+ }}
+ disabled={
+ resourceAttribute.key === 'service.name' ||
+ resourceAttribute.key === 'name'
+ }
+ >
+ <div className="resource-attributes-select-item-value">
+ {resourceAttribute.key}
+ </div>
+ </Checkbox>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="span-percentile-content">
+ <Typography.Text className="span-percentile-content-title">
+ This span duration is{' '}
+ {!isLoadingSpanPercentilesData &&
+ !isFetchingSpanPercentilesData &&
+ spanPercentileData ? (
+ <span className="span-percentile-value">
+ p{Math.floor(spanPercentileData?.percentile || 0)}
+ </span>
+ ) : (
+ <span className="span-percentile-value-loader">
+ <Loader2 size={12} className="animate-spin" />
+ </span>
+ )}{' '}
+ out of the distribution for this resource evaluated for{' '}
+ {selectedTimeRange} hour(s) since the span start time.
+ </Typography.Text>
+
+ <div className="span-percentile-timerange">
+ <Select
+ labelInValue
+ placeholder="Select timerange"
+ className="span-percentile-timerange-select"
+ value={{
+ label: `${selectedTimeRange}h : ${dayjs(selectedSpan?.timestamp)
+ .subtract(selectedTimeRange, 'hour')
+ .format(DATE_TIME_FORMATS.TIME_SPAN_PERCENTILE)} - ${dayjs(
+ selectedSpan?.timestamp,
+ ).format(DATE_TIME_FORMATS.TIME_SPAN_PERCENTILE)}`,
+ value: selectedTimeRange,
+ }}
+ onChange={(value): void => {
+ handleTimeRangeChange(Number(value.value));
+ }}
+ options={timerangeOptions}
+ />
+ </div>
+
+ <div className="span-percentile-values-table">
+ <div className="span-percentile-values-table-header-row">
+ <Typography.Text className="span-percentile-values-table-header">
+ Percentile
+ </Typography.Text>
+
+ <Typography.Text className="span-percentile-values-table-header">
+ Duration
+ </Typography.Text>
+ </div>
+
+ <div className="span-percentile-values-table-data-rows">
+ {isLoadingSpanPercentilesData || isFetchingSpanPercentilesData ? (
+ <Skeleton
+ active
+ paragraph={{ rows: 3 }}
+ className="span-percentile-values-table-data-rows-skeleton"
+ />
+ ) : (
+ <>
+ {Object.entries(spanPercentileData?.percentiles || {}).map(
+ ([percentile, duration]) => (
+ <div
+ className="span-percentile-values-table-data-row"
+ key={percentile}
+ >
+ <Typography.Text className="span-percentile-values-table-data-row-key">
+ {percentile}
+ </Typography.Text>
+
+ <div className="dashed-line" />
+
+ <Typography.Text className="span-percentile-values-table-data-row-value">
+ {getYAxisFormattedValue(`${duration / 1000000}`, 'ms')}
+ </Typography.Text>
+ </div>
+ ),
+ )}
+
+ <div className="span-percentile-values-table-data-row current-span-percentile-row">
+ <Typography.Text className="span-percentile-values-table-data-row-key">
+ p{Math.floor(spanPercentileData?.percentile || 0)}
+ </Typography.Text>
+
+ <div className="dashed-line" />
+
+ <Typography.Text className="span-percentile-values-table-data-row-value">
+ (this span){' '}
+ {getYAxisFormattedValue(
+ `${selectedSpan.durationNano / 1000000}`,
+ 'ms',
+ )}
+ </Typography.Text>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
</div>
<div className="item">
<Typography.Text className="attribute-key">span id</Typography.Text>
diff --git a/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
index b857260f0b..4b0ad009e9 100644
--- a/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
+++ b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
@@ -1,3 +1,8 @@
+/* eslint-disable sonarjs/no-duplicate-string */
+/* eslint-disable sonarjs/no-identical-functions */
+
+import getSpanPercentiles from 'api/trace/getSpanPercentiles';
+import getUserPreference from 'api/v1/user/preferences/name/get';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
@@ -10,6 +15,8 @@ import {
userEvent,
waitFor,
} from 'tests/test-utils';
+import { SuccessResponseV2 } from 'types/api';
+import { GetSpanPercentilesResponseDataProps } from 'types/api/trace/getSpanPercentiles';
import SpanDetailsDrawer from '../SpanDetailsDrawer';
import {
@@ -24,6 +31,11 @@ import {
mockSpanLogsResponse,
} from './mockData';
+// Get typed mocks
+const mockGetSpanPercentiles = jest.mocked(getSpanPercentiles);
+const mockGetUserPreference = jest.mocked(getUserPreference);
+const mockSafeNavigate = jest.fn();
+
// Mock external dependencies
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
@@ -39,9 +51,8 @@ jest.mock('@signozhq/button', () => ({
),
}));
-const mockSafeNavigate = jest.fn();
jest.mock('hooks/useSafeNavigate', () => ({
- useSafeNavigate: (): any => ({
+ useSafeNavigate: (): { safeNavigate: jest.MockedFunction<() => void> } => ({
safeNavigate: mockSafeNavigate,
}),
}));
@@ -69,7 +80,10 @@ const mockUpdateAllQueriesOperators = jest.fn().mockReturnValue({
});
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
- useQueryBuilder: (): any => ({
+ useQueryBuilder: (): {
+ updateAllQueriesOperators: jest.MockedFunction<() => any>;
+ currentQuery: any;
+ } => ({
updateAllQueriesOperators: mockUpdateAllQueriesOperators,
currentQuery: {
builder: {
@@ -114,26 +128,46 @@ jest.mock('lib/uPlotLib/utils/generateColor', () => ({
generateColor: jest.fn().mockReturnValue('#1f77b4'),
}));
+// Mock getSpanPercentiles API
+jest.mock('api/trace/getSpanPercentiles', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+// Mock getUserPreference API
+jest.mock('api/v1/user/preferences/name/get', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
jest.mock(
'components/OverlayScrollbar/OverlayScrollbar',
() =>
// eslint-disable-next-line func-names, @typescript-eslint/explicit-function-return-type, react/display-name
- function ({ children }: any) {
+ function ({ children }: { children: React.ReactNode }) {
return <div data-testid="overlay-scrollbar">{children}</div>;
},
);
// Mock Virtuoso to avoid complex virtualization
jest.mock('react-virtuoso', () => ({
- Virtuoso: jest.fn(({ data, itemContent }) => (
- <div data-testid="virtuoso">
- {data?.map((item: any, index: number) => (
- <div key={item.id || index} data-testid={`log-item-${item.id}`}>
- {itemContent(index, item)}
- </div>
- ))}
- </div>
- )),
+ Virtuoso: jest.fn(
+ ({
+ data,
+ itemContent,
+ }: {
+ data: any[];
+ itemContent: (index: number, item: any) => React.ReactNode;
+ }) => (
+ <div data-testid="virtuoso">
+ {data?.map((item: any, index: number) => (
+ <div key={item.id || index} data-testid={`log-item-${item.id}`}>
+ {itemContent(index, item)}
+ </div>
+ ))}
+ </div>
+ ),
+ ),
}));
// Mock RawLogView component
@@ -146,7 +180,12 @@ jest.mock(
onLogClick,
isHighlighted,
helpTooltip,
- }: any) {
+ }: {
+ data: any;
+ onLogClick: (data: any, event: React.MouseEvent) => void;
+ isHighlighted: boolean;
+ helpTooltip: string;
+ }) {
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<div
@@ -165,9 +204,11 @@ jest.mock(
// Mock PreferenceContextProvider
jest.mock('providers/preferences/context/PreferenceContextProvider', () => ({
- PreferenceContextProvider: ({ children }: any): JSX.Element => (
- <div>{children}</div>
- ),
+ PreferenceContextProvider: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }): JSX.Element => <div>{children}</div>,
}));
// Mock QueryBuilder context value
@@ -218,6 +259,51 @@ const renderSpanDetailsDrawer = (props = {}): void => {
);
};
+// Constants for repeated strings
+const SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER = 'Search resource attributes';
+const P75_TEXT = 'p75';
+const SPAN_PERCENTILE_TEXT = 'Span Percentile';
+
+// Mock data for span percentiles
+const mockSpanPercentileResponse = {
+ httpStatusCode: 200 as const,
+ data: {
+ percentiles: {
+ p50: 500000000, // 500ms in nanoseconds
+ p90: 1000000000, // 1s in nanoseconds
+ p95: 1500000000, // 1.5s in nanoseconds
+ p99: 2000000000, // 2s in nanoseconds
+ },
+ position: {
+ percentile: 75.5,
+ description: 'This span is in the 75th percentile',
+ },
+ },
+};
+
+const mockUserPreferenceResponse = {
+ statusCode: 200,
+ httpStatusCode: 200,
+ error: null,
+ message: 'Success',
+ data: {
+ name: 'span_percentile_resource_attributes',
+ description: 'Resource attributes for span percentile calculation',
+ valueType: 'array',
+ defaultValue: [],
+ value: ['service.name', 'name', 'http.method'],
+ allowedValues: [],
+ allowedScopes: [],
+ createdAt: '2023-01-01T00:00:00Z',
+ updatedAt: '2023-01-01T00:00:00Z',
+ },
+};
+
+const mockSpanPercentileErrorResponse = ({
+ httpStatusCode: 500,
+ data: null,
+} as unknown) as SuccessResponseV2<GetSpanPercentilesResponseDataProps>;
+
describe('SpanDetailsDrawer', () => {
let apiCallHistory: any = {};
@@ -232,12 +318,14 @@ describe('SpanDetailsDrawer', () => {
mockSafeNavigate.mockClear();
mockWindowOpen.mockClear();
mockUpdateAllQueriesOperators.mockClear();
+ mockGetSpanPercentiles.mockClear();
+ mockGetUserPreference.mockClear();
// Setup API call tracking
(GetMetricQueryRange as jest.Mock).mockImplementation((query) => {
// Determine response based on v5 filter expressions
- const filterExpression =
- query.query?.builder?.queryData?.[0]?.filter?.expression;
+ const filterExpression = (query as any)?.query?.builder?.queryData?.[0]
+ ?.filter?.expression;
if (!filterExpression) return Promise.resolve(mockEmptyLogsResponse);
@@ -322,17 +410,17 @@ describe('SpanDetailsDrawer', () => {
} = apiCallHistory;
// 1. Span logs query (trace_id + span_id)
- expect(spanQuery.query.builder.queryData[0].filter.expression).toBe(
+ expect((spanQuery as any).query.builder.queryData[0].filter.expression).toBe(
expectedSpanFilterExpression,
);
// 2. Before logs query (trace_id + id < first_span_log_id)
- expect(beforeQuery.query.builder.queryData[0].filter.expression).toBe(
- expectedBeforeFilterExpression,
- );
+ expect(
+ (beforeQuery as any).query.builder.queryData[0].filter.expression,
+ ).toBe(expectedBeforeFilterExpression);
// 3. After logs query (trace_id + id > last_span_log_id)
- expect(afterQuery.query.builder.queryData[0].filter.expression).toBe(
+ expect((afterQuery as any).query.builder.queryData[0].filter.expression).toBe(
expectedAfterFilterExpression,
);
@@ -361,13 +449,19 @@ describe('SpanDetailsDrawer', () => {
} = apiCallHistory;
// Verify ordering: span query should use 'desc' (default)
- expect(spanQuery.query.builder.queryData[0].orderBy[0].order).toBe('desc');
+ expect((spanQuery as any).query.builder.queryData[0].orderBy[0].order).toBe(
+ 'desc',
+ );
// Before query should use 'desc' (default)
- expect(beforeQuery.query.builder.queryData[0].orderBy[0].order).toBe('desc');
+ expect((beforeQuery as any).query.builder.queryData[0].orderBy[0].order).toBe(
+ 'desc',
+ );
// After query should use 'asc' for chronological order
- expect(afterQuery.query.builder.queryData[0].orderBy[0].order).toBe('asc');
+ expect((afterQuery as any).query.builder.queryData[0].orderBy[0].order).toBe(
+ 'asc',
+ );
});
it('should navigate to logs explorer with span filters when span log is clicked', async () => {
@@ -528,6 +622,435 @@ describe('SpanDetailsDrawer', () => {
expect(contextLogAfter).toHaveClass('log-context');
expect(contextLogBefore).not.toHaveAttribute('title');
});
+
+ // Span Percentile Tests
+ describe('Span Percentile Functionality', () => {
+ beforeEach(() => {
+ // Setup default mocks for percentile tests
+ mockGetUserPreference.mockResolvedValue(mockUserPreferenceResponse);
+ mockGetSpanPercentiles.mockResolvedValue(mockSpanPercentileResponse);
+ });
+
+ it('should display span percentile value after successful API call', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for the 2-second delay and API call to complete
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+ });
+
+ it('should show loading spinner while fetching percentile data', async () => {
+ // Mock a delayed response
+ mockGetSpanPercentiles.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(() => resolve(mockSpanPercentileResponse), 1000);
+ }),
+ );
+
+ renderSpanDetailsDrawer();
+
+ // Wait for loading spinner to appear (it's visible as a div with class loading-spinner-container)
+ await waitFor(
+ () => {
+ const spinnerContainer = document.querySelector(
+ '.loading-spinner-container',
+ );
+ expect(spinnerContainer).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+ });
+
+ it('should expand percentile details when percentile value is clicked', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ // Click on the percentile value to expand details
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Verify percentile details are expanded
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ // Look for the text that's actually rendered
+ expect(screen.getByText(/This span duration is/)).toBeInTheDocument();
+ expect(
+ screen.getByText(/out of the distribution for this resource/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('should display percentile table with correct values', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Wait for the percentile details to expand
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ // Wait for the table to be visible (it might take a moment to render)
+ await waitFor(
+ () => {
+ expect(screen.getByText('Percentile')).toBeInTheDocument();
+ expect(screen.getByText('Duration')).toBeInTheDocument();
+ },
+ { timeout: 5000 },
+ );
+
+ // Verify percentile values are displayed
+ expect(screen.getByText('p50')).toBeInTheDocument();
+ expect(screen.getByText('p90')).toBeInTheDocument();
+ expect(screen.getByText('p95')).toBeInTheDocument();
+ expect(screen.getByText('p99')).toBeInTheDocument();
+
+ // Verify current span row - use getAllByText since there are multiple p75 elements
+ expect(screen.getAllByText(P75_TEXT)).toHaveLength(3); // Should appear in value, expanded details, and table
+
+ // Verify the table has the current span indicator (there are multiple occurrences)
+ expect(screen.getAllByText(/this span/i).length).toBeGreaterThan(0);
+ });
+
+ it('should allow time range selection and trigger API call', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load and expand
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Wait for percentile details to expand
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ // Find the time range selector and verify it exists
+ const timeRangeSelector = screen.getByRole('combobox');
+ expect(timeRangeSelector).toBeInTheDocument();
+
+ // Verify the default time range is displayed
+ expect(screen.getByText(/1.*hour/i)).toBeInTheDocument();
+
+ // Verify API was called with default parameters
+ await waitFor(() => {
+ expect(mockGetSpanPercentiles).toHaveBeenCalledWith(
+ expect.objectContaining({
+ start: expect.any(Number),
+ end: expect.any(Number),
+ spanDuration: mockSpan.durationNano,
+ serviceName: mockSpan.serviceName,
+ name: mockSpan.name,
+ resourceAttributes: expect.any(Object),
+ }),
+ );
+ });
+ });
+
+ it('should show resource attributes selector when plus icon is clicked', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load and expand
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Wait for percentile details to expand
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ // Click the plus icon using test ID
+ const plusIcon = screen.getByTestId('plus-icon');
+ fireEvent.click(plusIcon);
+
+ // Verify resource attributes selector is shown
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText(SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('should filter resource attributes based on search query', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load and expand
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Wait for percentile details to expand and show resource attributes
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ const plusIcon = screen.getByTestId('plus-icon');
+ fireEvent.click(plusIcon);
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText(SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER),
+ ).toBeInTheDocument();
+ });
+
+ // Type in search query
+ const searchInput = screen.getByPlaceholderText(
+ SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER,
+ );
+ fireEvent.change(searchInput, { target: { value: 'http' } });
+
+ // Verify only matching attributes are shown (use getAllByText for all since they appear in multiple places)
+ expect(screen.getAllByText('http.method').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('http.url').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('http.status_code').length).toBeGreaterThan(0);
+ });
+
+ it('should handle resource attribute selection and trigger API call', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load and expand
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.click(percentileValue);
+
+ // Wait for percentile details to expand and show resource attributes
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ const plusIcon = screen.getByTestId('plus-icon');
+ fireEvent.click(plusIcon);
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText(SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER),
+ ).toBeInTheDocument();
+ });
+
+ // Find and click a checkbox for a resource attribute
+ const httpMethodCheckbox = screen.getByRole('checkbox', {
+ name: /http\.method/i,
+ });
+ fireEvent.click(httpMethodCheckbox);
+
+ // Verify API was called with updated resource attributes
+ await waitFor(() => {
+ expect(mockGetSpanPercentiles).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resourceAttributes: expect.objectContaining({
+ 'http.method': 'GET',
+ }),
+ }),
+ );
+ });
+ });
+
+ it('should handle API error gracefully', async () => {
+ // Mock API error
+ mockGetSpanPercentiles.mockResolvedValue(mockSpanPercentileErrorResponse);
+
+ renderSpanDetailsDrawer();
+
+ // Wait for the 2-second delay
+ await waitFor(
+ () => {
+ // Verify no percentile value is displayed on error
+ expect(screen.queryByText(/p\d+/)).not.toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+ });
+
+ it('should not display percentile value when API returns non-200 status', async () => {
+ // Mock API response with non-200 status
+ mockGetSpanPercentiles.mockResolvedValue(({
+ httpStatusCode: 500 as const,
+ data: null,
+ } as unknown) as Awaited<ReturnType<typeof getSpanPercentiles>>);
+
+ renderSpanDetailsDrawer();
+
+ // Wait for the 2-second delay
+ await waitFor(
+ () => {
+ // Verify no percentile value is displayed
+ expect(screen.queryByText(/p\d+/)).not.toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+ });
+
+ it('should display tooltip with correct content', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ // Hover over the percentile value to show tooltip
+ const percentileValue = screen.getByText(P75_TEXT);
+ fireEvent.mouseEnter(percentileValue);
+
+ // Verify tooltip content - use more flexible text matching
+ await waitFor(() => {
+ expect(screen.getByText(/This span duration is/)).toBeInTheDocument();
+ expect(screen.getByText(/out of the distribution/)).toBeInTheDocument();
+ expect(
+ screen.getByText(/evaluated for 1 hour\(s\) since the span start time/),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Click to learn more')).toBeInTheDocument();
+ });
+ });
+
+ it('should handle empty percentile data gracefully', async () => {
+ // Mock empty percentile response
+ mockGetSpanPercentiles.mockResolvedValue({
+ httpStatusCode: 200,
+ data: {
+ percentiles: {},
+ position: {
+ percentile: 0,
+ description: '',
+ },
+ },
+ });
+
+ renderSpanDetailsDrawer();
+
+ // Wait for the 2-second delay
+ await waitFor(
+ () => {
+ // Verify p0 is displayed for empty data
+ expect(screen.getByText('p0')).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+ });
+
+ it('should call API with correct parameters', async () => {
+ renderSpanDetailsDrawer();
+
+ // Wait for API call to be made
+ await waitFor(
+ () => {
+ expect(mockGetSpanPercentiles).toHaveBeenCalled();
+ },
+ { timeout: 3000 },
+ );
+
+ // Verify API was called with correct parameters
+ expect(mockGetSpanPercentiles).toHaveBeenCalledWith({
+ start: expect.any(Number),
+ end: expect.any(Number),
+ spanDuration: mockSpan.durationNano,
+ serviceName: mockSpan.serviceName,
+ name: mockSpan.name,
+ resourceAttributes: expect.any(Object),
+ });
+ });
+
+ it('should handle user preference loading', async () => {
+ renderSpanDetailsDrawer();
+
+ // Verify getUserPreference was called
+ await waitFor(() => {
+ expect(mockGetUserPreference).toHaveBeenCalledWith({
+ name: 'span_percentile_resource_attributes',
+ });
+ });
+ });
+
+ it('should close resource attributes selector when check icon is clicked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ renderSpanDetailsDrawer();
+
+ // Wait for percentile data to load and expand
+ await waitFor(
+ () => {
+ expect(screen.getByText(P75_TEXT)).toBeInTheDocument();
+ },
+ { timeout: 3000 },
+ );
+
+ const percentileValue = screen.getByText(P75_TEXT);
+ await user.click(percentileValue);
+
+ // Wait for percentile details to expand and show resource attributes
+ await waitFor(() => {
+ expect(screen.getByText(SPAN_PERCENTILE_TEXT)).toBeInTheDocument();
+ });
+
+ const plusIcon = screen.getByTestId('plus-icon');
+ await user.click(plusIcon);
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText(SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER),
+ ).toBeInTheDocument();
+ });
+
+ // Click the check icon to close the selector
+ const checkIcon = screen.getByTestId('check-icon');
+ await user.click(checkIcon);
+
+ // Verify resource attributes selector is hidden
+ await waitFor(() => {
+ expect(
+ screen.queryByPlaceholderText(SEARCH_RESOURCE_ATTRIBUTES_PLACEHOLDER),
+ ).not.toBeInTheDocument();
+ });
+ });
+ });
});
describe('SpanDetailsDrawer - Search Visibility User Flows', () => {
diff --git a/frontend/src/container/TraceMetadata/TraceMetadata.tsx b/frontend/src/container/TraceMetadata/TraceMetadata.tsx
index 929cbd0de6..bd3a0f42b8 100644
--- a/frontend/src/container/TraceMetadata/TraceMetadata.tsx
+++ b/frontend/src/container/TraceMetadata/TraceMetadata.tsx
@@ -35,21 +35,21 @@ function TraceMetadata(props: ITraceMetadataProps): JSX.Element {
totalSpans,
notFound,
} = props;
+
+ const handlePreviousBtnClick = (): void => {
+ if (window.history.length > 1) {
+ history.goBack();
+ } else {
+ history.push(ROUTES.TRACES_EXPLORER);
+ }
+ };
+
return (
<div className="trace-metadata">
<section className="metadata-info">
<div className="first-row">
- <Button className="previous-btn">
- <ArrowLeft
- size={14}
- onClick={(): void => {
- if (window.history.length > 1) {
- history.goBack();
- } else {
- history.push(ROUTES.TRACES_EXPLORER);
- }
- }}
- />
+ <Button className="previous-btn" onClick={handlePreviousBtnClick}>
+ <ArrowLeft size={14} />
</Button>
<div className="trace-name">
<DraftingCompass size={14} className="drafting" />
diff --git a/frontend/src/types/api/trace/getSpanPercentiles.ts b/frontend/src/types/api/trace/getSpanPercentiles.ts
new file mode 100644
index 0000000000..73b3152914
--- /dev/null
+++ b/frontend/src/types/api/trace/getSpanPercentiles.ts
@@ -0,0 +1,21 @@
+export interface GetSpanPercentilesProps {
+ start: number;
+ end: number;
+ spanDuration: number;
+ serviceName: string;
+ name: string;
+ resourceAttributes: Record<string, string>;
+}
+
+export interface GetSpanPercentilesResponseDataProps {
+ percentiles: Record<string, number>;
+ position: {
+ percentile: number;
+ description: string;
+ };
+}
+
+export interface GetSpanPercentilesResponsePayloadProps {
+ status: string;
+ data: GetSpanPercentilesResponseDataProps;
+}