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: add support for infra metrics in trace details (#8911)

Shaheer Kochai155a44a25ddf
diff --git a/frontend/src/components/LogDetail/index.tsx b/frontend/src/components/LogDetail/index.tsx
index 23a50ca3d7..8498c81852 100644
--- a/frontend/src/components/LogDetail/index.tsx
+++ b/frontend/src/components/LogDetail/index.tsx
@@ -383,7 +383,8 @@ function LogDetailInner({
podName={log.resources_string?.[RESOURCE_KEYS.POD_NAME] || ''}
nodeName={log.resources_string?.[RESOURCE_KEYS.NODE_NAME] || ''}
hostName={log.resources_string?.[RESOURCE_KEYS.HOST_NAME] || ''}
- logLineTimestamp={log.timestamp.toString()}
+ timestamp={log.timestamp.toString()}
+ dataSource={DataSource.LOGS}
/>
)}
</Drawer>
diff --git a/frontend/src/container/LogDetailedView/InfraMetrics/InfraMetrics.tsx b/frontend/src/container/LogDetailedView/InfraMetrics/InfraMetrics.tsx
index 78a1d21b16..e895f6252b 100644
--- a/frontend/src/container/LogDetailedView/InfraMetrics/InfraMetrics.tsx
+++ b/frontend/src/container/LogDetailedView/InfraMetrics/InfraMetrics.tsx
@@ -1,9 +1,11 @@
import './InfraMetrics.styles.scss';
-import { Empty, Radio } from 'antd';
+import { Empty } from 'antd';
import { RadioChangeEvent } from 'antd/lib';
+import SignozRadioGroup from 'components/SignozRadioGroup/SignozRadioGroup';
import { History, Table } from 'lucide-react';
-import { useState } from 'react';
+import { useMemo, useState } from 'react';
+import { DataSource } from 'types/common/queryBuilder';
import { VIEW_TYPES } from './constants';
import NodeMetrics from './NodeMetrics';
@@ -14,7 +16,8 @@ interface MetricsDataProps {
nodeName: string;
hostName: string;
clusterName: string;
- logLineTimestamp: string;
+ timestamp: string;
+ dataSource: DataSource.LOGS | DataSource.TRACES;
}
function InfraMetrics({
@@ -22,22 +25,56 @@ function InfraMetrics({
nodeName,
hostName,
clusterName,
- logLineTimestamp,
+ timestamp,
+ dataSource = DataSource.LOGS,
}: MetricsDataProps): JSX.Element {
const [selectedView, setSelectedView] = useState<string>(() =>
podName ? VIEW_TYPES.POD : VIEW_TYPES.NODE,
);
+ const viewOptions = useMemo(() => {
+ const options = [
+ {
+ label: (
+ <div className="view-title">
+ <Table size={14} />
+ Node
+ </div>
+ ),
+ value: VIEW_TYPES.NODE,
+ },
+ ];
+
+ if (podName) {
+ options.push({
+ label: (
+ <div className="view-title">
+ <History size={14} />
+ Pod
+ </div>
+ ),
+ value: VIEW_TYPES.POD,
+ });
+ }
+
+ return options;
+ }, [podName]);
+
const handleModeChange = (e: RadioChangeEvent): void => {
setSelectedView(e.target.value);
};
if (!podName && !nodeName && !hostName) {
+ const emptyStateDescription =
+ dataSource === DataSource.TRACES
+ ? 'No data available. Please select a span containing a pod, node, or host attributes to view metrics.'
+ : 'No data available. Please select a valid log line containing a pod, node, or host attributes to view metrics.';
+
return (
<div className="empty-container">
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
- description="No data available. Please select a valid log line containing a pod, node, or host attributes to view metrics."
+ description={emptyStateDescription}
/>
</div>
);
@@ -45,46 +82,26 @@ function InfraMetrics({
return (
<div className="infra-metrics-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleModeChange}
+ <SignozRadioGroup
value={selectedView}
- >
- <Radio.Button
- className={selectedView === VIEW_TYPES.NODE ? 'selected_view tab' : 'tab'}
- value={VIEW_TYPES.NODE}
- >
- <div className="view-title">
- <Table size={14} />
- Node
- </div>
- </Radio.Button>
- {podName && (
- <Radio.Button
- className={selectedView === VIEW_TYPES.POD ? 'selected_view tab' : 'tab'}
- value={VIEW_TYPES.POD}
- >
- <div className="view-title">
- <History size={14} />
- Pod
- </div>
- </Radio.Button>
- )}
- </Radio.Group>
+ onChange={handleModeChange}
+ className="views-tabs"
+ options={viewOptions}
+ />
{/* TODO(Rahul): Make a common config driven component for this and other infra metrics components */}
{selectedView === VIEW_TYPES.NODE && (
<NodeMetrics
nodeName={nodeName}
clusterName={clusterName}
hostName={hostName}
- logLineTimestamp={logLineTimestamp}
+ timestamp={timestamp}
/>
)}
{selectedView === VIEW_TYPES.POD && podName && (
<PodMetrics
podName={podName}
clusterName={clusterName}
- logLineTimestamp={logLineTimestamp}
+ timestamp={timestamp}
/>
)}
</div>
diff --git a/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx b/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx
index 9f20ca996d..02ea57e99e 100644
--- a/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx
+++ b/frontend/src/container/LogDetailedView/InfraMetrics/NodeMetrics.tsx
@@ -29,15 +29,15 @@ function NodeMetrics({
nodeName,
clusterName,
hostName,
- logLineTimestamp,
+ timestamp,
}: {
nodeName: string;
clusterName: string;
hostName: string;
- logLineTimestamp: string;
+ timestamp: string;
}): JSX.Element {
const { start, end, verticalLineTimestamp } = useMemo(() => {
- const logTimestamp = dayjs(logLineTimestamp);
+ const logTimestamp = dayjs(timestamp);
const now = dayjs();
const startTime = logTimestamp.subtract(3, 'hour');
@@ -50,7 +50,7 @@ function NodeMetrics({
end: endTime.unix(),
verticalLineTimestamp: logTimestamp.unix(),
};
- }, [logLineTimestamp]);
+ }, [timestamp]);
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
diff --git a/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx b/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx
index 426be24057..a2e11a8c31 100644
--- a/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx
+++ b/frontend/src/container/LogDetailedView/InfraMetrics/PodMetrics.tsx
@@ -23,14 +23,14 @@ import { getPodQueryPayload, podWidgetInfo } from './constants';
function PodMetrics({
podName,
clusterName,
- logLineTimestamp,
+ timestamp,
}: {
podName: string;
clusterName: string;
- logLineTimestamp: string;
+ timestamp: string;
}): JSX.Element {
const { start, end, verticalLineTimestamp } = useMemo(() => {
- const logTimestamp = dayjs(logLineTimestamp);
+ const logTimestamp = dayjs(timestamp);
const now = dayjs();
const startTime = logTimestamp.subtract(3, 'hour');
@@ -43,7 +43,7 @@ function PodMetrics({
end: endTime.unix(),
verticalLineTimestamp: logTimestamp.unix(),
};
- }, [logLineTimestamp]);
+ }, [timestamp]);
const legendScrollPositionRef = useRef<{
scrollTop: number;
diff --git a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
index 182a98326c..eddbee1167 100644
--- a/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
+++ b/frontend/src/container/SpanDetailsDrawer/SpanDetailsDrawer.tsx
@@ -7,8 +7,21 @@ import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import SignozRadioGroup from 'components/SignozRadioGroup/SignozRadioGroup';
import { themeColors } from 'constants/theme';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
-import { Anvil, Bookmark, Link2, PanelRight, Search } from 'lucide-react';
-import { Dispatch, SetStateAction, useCallback, useState } from 'react';
+import {
+ Anvil,
+ BarChart2,
+ Bookmark,
+ Link2,
+ PanelRight,
+ Search,
+} from 'lucide-react';
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from 'react';
import { Span } from 'types/api/trace/getTraceV2';
import { formatEpochTimestamp } from 'utils/timeUtils';
@@ -17,6 +30,7 @@ import { RelatedSignalsViews } from './constants';
import Events from './Events/Events';
import LinkedSpans from './LinkedSpans/LinkedSpans';
import SpanRelatedSignals from './SpanRelatedSignals/SpanRelatedSignals';
+import { hasInfraMetadata } from './utils';
interface ISpanDetailsDrawerProps {
isSpanDetailsDocked: boolean;
@@ -60,6 +74,35 @@ function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
setIsRelatedSignalsOpen(false);
}, []);
+ const relatedSignalsOptions = useMemo(() => {
+ const baseOptions = [
+ {
+ label: (
+ <div className="view-title">
+ <LogsIcon width={14} height={14} />
+ Logs
+ </div>
+ ),
+ value: RelatedSignalsViews.LOGS,
+ },
+ ];
+
+ // Only show Infra option if span has infrastructure metadata
+ if (hasInfraMetadata(selectedSpan)) {
+ baseOptions.push({
+ label: (
+ <div className="view-title">
+ <BarChart2 size={14} />
+ Metrics
+ </div>
+ ),
+ value: RelatedSignalsViews.INFRA,
+ });
+ }
+
+ return baseOptions;
+ }, [selectedSpan]);
+
function getItems(span: Span, startTime: number): TabsProps['items'] {
return [
{
@@ -226,17 +269,7 @@ function SpanDetailsDrawer(props: ISpanDetailsDrawerProps): JSX.Element {
<div className="related-signals-section">
<SignozRadioGroup
value=""
- options={[
- {
- label: (
- <div className="view-title">
- <LogsIcon width={14} height={14} />
- Logs
- </div>
- ),
- value: RelatedSignalsViews.LOGS,
- },
- ]}
+ options={relatedSignalsOptions}
onChange={handleRelatedSignalsChange}
className="related-signals-radio"
/>
diff --git a/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.styles.scss b/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.styles.scss
index 20c62e0ecf..b81009edef 100644
--- a/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.styles.scss
+++ b/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.styles.scss
@@ -30,6 +30,11 @@
display: flex;
flex-direction: column;
}
+ .view-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
.views-tabs-container {
padding: 16px 15px;
@@ -88,28 +93,10 @@
}
}
- .infra-placeholder {
- height: 50vh;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- padding: 2rem;
- box-sizing: border-box;
-
- .infra-placeholder-content {
- text-align: center;
- color: var(--bg-slate-400);
-
- svg {
- margin-bottom: 1rem;
- color: var(--bg-slate-400);
- }
-
- .ant-typography {
- font-size: 16px;
- color: var(--bg-slate-400);
- }
+ .infra-metrics-container {
+ padding-inline: 16px;
+ .infra-metrics-card {
+ border: 1px solid var(--bg-slate-400);
}
}
}
diff --git a/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.tsx b/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.tsx
index caca1ca873..fdc20ed140 100644
--- a/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.tsx
+++ b/frontend/src/container/SpanDetailsDrawer/SpanRelatedSignals/SpanRelatedSignals.tsx
@@ -11,17 +11,20 @@ import {
initialQueryState,
} from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
+import InfraMetrics from 'container/LogDetailedView/InfraMetrics/InfraMetrics';
import { getEmptyLogsListConfig } from 'container/LogsExplorerList/utils';
+import dayjs from 'dayjs';
import { useIsDarkMode } from 'hooks/useDarkMode';
-import { Compass, X } from 'lucide-react';
+import { BarChart2, Compass, X } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Span } from 'types/api/trace/getTraceV2';
-import { LogsAggregatorOperator } from 'types/common/queryBuilder';
+import { DataSource, LogsAggregatorOperator } from 'types/common/queryBuilder';
import { RelatedSignalsViews } from '../constants';
import SpanLogs from '../SpanLogs/SpanLogs';
import { useSpanContextLogs } from '../SpanLogs/useSpanContextLogs';
+import { hasInfraMetadata } from '../utils';
const FIVE_MINUTES_IN_MS = 5 * 60 * 1000;
@@ -47,6 +50,21 @@ function SpanRelatedSignals({
);
const isDarkMode = useIsDarkMode();
+ // Extract infrastructure metadata from span attributes
+ const infraMetadata = useMemo(() => {
+ // Only return metadata if span has infrastructure metadata
+ if (!hasInfraMetadata(selectedSpan)) {
+ return null;
+ }
+
+ return {
+ clusterName: selectedSpan.tagMap['k8s.cluster.name'] || '',
+ podName: selectedSpan.tagMap['k8s.pod.name'] || '',
+ nodeName: selectedSpan.tagMap['k8s.node.name'] || '',
+ hostName: selectedSpan.tagMap['host.name'] || '',
+ spanTimestamp: dayjs(selectedSpan.timestamp).format(),
+ };
+ }, [selectedSpan]);
const {
logs,
isLoading,
@@ -68,10 +86,34 @@ function SpanRelatedSignals({
setSelectedView(e.target.value);
}, []);
- const handleClose = useCallback((): void => {
- setSelectedView(RelatedSignalsViews.LOGS);
- onClose();
- }, [onClose]);
+ const tabOptions = useMemo(() => {
+ const baseOptions = [
+ {
+ label: (
+ <div className="view-title">
+ <LogsIcon width={14} height={14} />
+ Logs
+ </div>
+ ),
+ value: RelatedSignalsViews.LOGS,
+ },
+ ];
+
+ // Add Infra option if infrastructure metadata is available
+ if (infraMetadata) {
+ baseOptions.push({
+ label: (
+ <div className="view-title">
+ <BarChart2 size={14} />
+ Metrics
+ </div>
+ ),
+ value: RelatedSignalsViews.INFRA,
+ });
+ }
+
+ return baseOptions;
+ }, [infraMetadata]);
const handleExplorerPageRedirect = useCallback((): void => {
const startTimeMs = traceStartTime - FIVE_MINUTES_IN_MS;
@@ -145,7 +187,7 @@ function SpanRelatedSignals({
</>
}
placement="right"
- onClose={handleClose}
+ onClose={onClose}
open={isOpen}
style={{
overscrollBehavior: 'contain',
@@ -160,35 +202,7 @@ function SpanRelatedSignals({
<div className="views-tabs-container">
<SignozRadioGroup
value={selectedView}
- options={[
- {
- label: (
- <div className="view-title">
- <LogsIcon width={14} height={14} />
- Logs
- </div>
- ),
- value: RelatedSignalsViews.LOGS,
- },
- // {
- // label: (
- // <div className="view-title">
- // <LogsIcon width={14} height={14} />
- // Metrics
- // </div>
- // ),
- // value: RelatedSignalsViews.METRICS,
- // },
- // {
- // label: (
- // <div className="view-title">
- // <Server size={14} />
- // Infra
- // </div>
- // ),
- // value: RelatedSignalsViews.INFRA,
- // },
- ]}
+ options={tabOptions}
onChange={handleTabChange}
className="related-signals-radio"
/>
@@ -197,6 +211,7 @@ function SpanRelatedSignals({
icon={<Compass size={18} />}
className="open-in-explorer"
onClick={handleExplorerPageRedirect}
+ data-testid="open-in-explorer-button"
>
Open in Logs Explorer
</Button>
@@ -220,6 +235,17 @@ function SpanRelatedSignals({
emptyStateConfig={!hasTraceIdLogs ? emptyStateConfig : undefined}
/>
)}
+
+ {selectedView === RelatedSignalsViews.INFRA && infraMetadata && (
+ <InfraMetrics
+ clusterName={infraMetadata.clusterName}
+ podName={infraMetadata.podName}
+ nodeName={infraMetadata.nodeName}
+ hostName={infraMetadata.hostName}
+ timestamp={infraMetadata.spanTimestamp}
+ dataSource={DataSource.TRACES}
+ />
+ )}
</div>
)}
</Drawer>
diff --git a/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.infraMetrics.test.tsx b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.infraMetrics.test.tsx
new file mode 100644
index 0000000000..f4119d4ad6
--- /dev/null
+++ b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.infraMetrics.test.tsx
@@ -0,0 +1,502 @@
+import ROUTES from 'constants/routes';
+import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
+import { server } from 'mocks-server/server';
+import { QueryBuilderContext } from 'providers/QueryBuilder';
+import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
+import { DataSource } from 'types/common/queryBuilder';
+
+import SpanDetailsDrawer from '../SpanDetailsDrawer';
+import {
+ expectedHostOnlyMetadata,
+ expectedInfraMetadata,
+ expectedNodeOnlyMetadata,
+ expectedPodOnlyMetadata,
+ mockEmptyMetricsResponse,
+ mockNodeMetricsResponse,
+ mockPodMetricsResponse,
+ mockSpanWithHostOnly,
+ mockSpanWithInfraMetadata,
+ mockSpanWithNodeOnly,
+ mockSpanWithoutInfraMetadata,
+ mockSpanWithPodOnly,
+} from './infraMetricsTestData';
+
+// Mock external dependencies
+jest.mock('react-router-dom', () => ({
+ ...jest.requireActual('react-router-dom'),
+ useLocation: (): { pathname: string } => ({
+ pathname: `${ROUTES.TRACE_DETAIL}`,
+ }),
+}));
+
+const mockSafeNavigate = jest.fn();
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): any => ({
+ safeNavigate: mockSafeNavigate,
+ }),
+}));
+
+const mockUpdateAllQueriesOperators = jest.fn().mockReturnValue({
+ builder: {
+ queryData: [
+ {
+ dataSource: 'logs',
+ queryName: 'A',
+ aggregateOperator: 'noop',
+ filters: { items: [], op: 'AND' },
+ expression: 'A',
+ disabled: false,
+ orderBy: [{ columnName: 'timestamp', order: 'desc' }],
+ groupBy: [],
+ limit: null,
+ having: [],
+ },
+ ],
+ queryFormulas: [],
+ },
+ queryType: 'builder',
+});
+
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): any => ({
+ updateAllQueriesOperators: mockUpdateAllQueriesOperators,
+ currentQuery: {
+ builder: {
+ queryData: [
+ {
+ dataSource: 'logs',
+ queryName: 'A',
+ filters: { items: [], op: 'AND' },
+ },
+ ],
+ },
+ },
+ }),
+}));
+
+const mockWindowOpen = jest.fn();
+Object.defineProperty(window, 'open', {
+ writable: true,
+ value: mockWindowOpen,
+});
+
+// Mock uplot to avoid rendering issues
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock = jest.fn(() => ({
+ paths,
+ }));
+ return {
+ paths,
+ default: uplotMock,
+ };
+});
+
+// Mock GetMetricQueryRange to track API calls
+jest.mock('lib/dashboard/getQueryResults', () => ({
+ GetMetricQueryRange: jest.fn(),
+}));
+
+// Mock generateColor
+jest.mock('lib/uPlotLib/utils/generateColor', () => ({
+ generateColor: jest.fn().mockReturnValue('#1f77b4'),
+}));
+
+// Mock OverlayScrollbar
+jest.mock(
+ 'components/OverlayScrollbar/OverlayScrollbar',
+ () =>
+ // eslint-disable-next-line func-names, @typescript-eslint/explicit-function-return-type, react/display-name
+ function ({ children }: any) {
+ return <div data-testid="overlay-scrollbar">{children}</div>;
+ },
+);
+
+// Mock Virtuoso
+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>
+ )),
+}));
+
+// Mock InfraMetrics component for focused testing
+jest.mock(
+ 'container/LogDetailedView/InfraMetrics/InfraMetrics',
+ () =>
+ // eslint-disable-next-line func-names, @typescript-eslint/explicit-function-return-type, react/display-name
+ function MockInfraMetrics({
+ podName,
+ nodeName,
+ hostName,
+ clusterName,
+ timestamp,
+ dataSource,
+ }: any) {
+ return (
+ <div data-testid="infra-metrics">
+ <div data-testid="infra-pod-name">{podName}</div>
+ <div data-testid="infra-node-name">{nodeName}</div>
+ <div data-testid="infra-host-name">{hostName}</div>
+ <div data-testid="infra-cluster-name">{clusterName}</div>
+ <div data-testid="infra-timestamp">{timestamp}</div>
+ <div data-testid="infra-data-source">{dataSource}</div>
+ </div>
+ );
+ },
+);
+
+// Mock PreferenceContextProvider
+jest.mock('providers/preferences/context/PreferenceContextProvider', () => ({
+ PreferenceContextProvider: ({ children }: any): JSX.Element => (
+ <div>{children}</div>
+ ),
+}));
+
+describe('SpanDetailsDrawer - Infra Metrics', () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, sonarjs/no-unused-collection
+ let apiCallHistory: any[] = [];
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ apiCallHistory = [];
+ mockSafeNavigate.mockClear();
+ mockWindowOpen.mockClear();
+ mockUpdateAllQueriesOperators.mockClear();
+
+ // Setup API call tracking for infra metrics
+ (GetMetricQueryRange as jest.Mock).mockImplementation((query) => {
+ apiCallHistory.push(query);
+
+ // Return mock responses for different query types
+ if (
+ query?.query?.builder?.queryData?.[0]?.filters?.items?.some(
+ (item: any) => item.key?.key === 'k8s_pod_name',
+ )
+ ) {
+ return Promise.resolve(mockPodMetricsResponse);
+ }
+
+ if (
+ query?.query?.builder?.queryData?.[0]?.filters?.items?.some(
+ (item: any) => item.key?.key === 'k8s_node_name',
+ )
+ ) {
+ return Promise.resolve(mockNodeMetricsResponse);
+ }
+
+ return Promise.resolve(mockEmptyMetricsResponse);
+ });
+ });
+
+ afterEach(() => {
+ server.resetHandlers();
+ });
+
+ // Mock QueryBuilder context value
+ const mockQueryBuilderContextValue = {
+ currentQuery: {
+ builder: {
+ queryData: [
+ {
+ dataSource: 'logs',
+ queryName: 'A',
+ filters: { items: [], op: 'AND' },
+ },
+ ],
+ },
+ },
+ stagedQuery: {
+ builder: {
+ queryData: [
+ {
+ dataSource: 'logs',
+ queryName: 'A',
+ filters: { items: [], op: 'AND' },
+ },
+ ],
+ },
+ },
+ updateAllQueriesOperators: mockUpdateAllQueriesOperators,
+ panelType: 'list',
+ redirectWithQuery: jest.fn(),
+ handleRunQuery: jest.fn(),
+ handleStageQuery: jest.fn(),
+ resetQuery: jest.fn(),
+ };
+
+ const renderSpanDetailsDrawer = (props = {}): void => {
+ render(
+ <QueryBuilderContext.Provider value={mockQueryBuilderContextValue as any}>
+ <SpanDetailsDrawer
+ isSpanDetailsDocked={false}
+ setIsSpanDetailsDocked={jest.fn()}
+ selectedSpan={mockSpanWithInfraMetadata}
+ traceStartTime={1640995200000} // 2022-01-01 00:00:00
+ traceEndTime={1640995260000} // 2022-01-01 00:01:00
+ // eslint-disable-next-line react/jsx-props-no-spreading
+ {...props}
+ />
+ </QueryBuilderContext.Provider>,
+ );
+ };
+
+ it('should detect infra metadata from span attributes', async () => {
+ renderSpanDetailsDrawer();
+
+ // Click on metrics tab
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+ expect(infraMetricsButton).toBeInTheDocument();
+
+ fireEvent.click(infraMetricsButton);
+
+ // Wait for infra metrics to load
+ await waitFor(() => {
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Verify metadata extraction
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('infra-pod-name')).toHaveTextContent(
+ expectedInfraMetadata.podName,
+ );
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('infra-node-name')).toHaveTextContent(
+ expectedInfraMetadata.nodeName,
+ );
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('infra-host-name')).toHaveTextContent(
+ expectedInfraMetadata.hostName,
+ );
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('infra-cluster-name')).toHaveTextContent(
+ expectedInfraMetadata.clusterName,
+ );
+ expect(screen.getByTestId('infra-data-source')).toHaveTextContent(
+ DataSource.TRACES,
+ );
+ });
+
+ it('should not show infra tab when span lacks infra metadata', async () => {
+ render(
+ <QueryBuilderContext.Provider value={mockQueryBuilderContextValue as any}>
+ <SpanDetailsDrawer
+ isSpanDetailsDocked={false}
+ setIsSpanDetailsDocked={jest.fn()}
+ selectedSpan={mockSpanWithoutInfraMetadata}
+ traceStartTime={1640995200000}
+ traceEndTime={1640995260000}
+ />
+ </QueryBuilderContext.Provider>,
+ );
+
+ // Should NOT show infra tab, only logs tab
+ expect(
+ screen.queryByRole('radio', { name: /metrics/i }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole('radio', { name: /logs/i })).toBeInTheDocument();
+ });
+
+ it('should show infra tab when span has infra metadata', async () => {
+ renderSpanDetailsDrawer();
+
+ // Should show both logs and infra tabs
+ expect(screen.getByRole('radio', { name: /metrics/i })).toBeInTheDocument();
+ expect(screen.getByRole('radio', { name: /logs/i })).toBeInTheDocument();
+ });
+
+ it('should handle pod-only metadata correctly', async () => {
+ render(
+ <QueryBuilderContext.Provider value={mockQueryBuilderContextValue as any}>
+ <SpanDetailsDrawer
+ isSpanDetailsDocked={false}
+ setIsSpanDetailsDocked={jest.fn()}
+ selectedSpan={mockSpanWithPodOnly}
+ traceStartTime={1640995200000}
+ traceEndTime={1640995260000}
+ />
+ </QueryBuilderContext.Provider>,
+ );
+
+ // Click on infra tab
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+ fireEvent.click(infraMetricsButton);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Verify pod-only metadata
+ expect(screen.getByTestId('infra-pod-name')).toHaveTextContent(
+ expectedPodOnlyMetadata.podName,
+ );
+ expect(screen.getByTestId('infra-cluster-name')).toHaveTextContent(
+ expectedPodOnlyMetadata.clusterName,
+ );
+ expect(screen.getByTestId('infra-node-name')).toHaveTextContent(
+ expectedPodOnlyMetadata.nodeName,
+ );
+ expect(screen.getByTestId('infra-host-name')).toHaveTextContent(
+ expectedPodOnlyMetadata.hostName,
+ );
+ });
+
+ it('should handle node-only metadata correctly', async () => {
+ render(
+ <QueryBuilderContext.Provider value={mockQueryBuilderContextValue as any}>
+ <SpanDetailsDrawer
+ isSpanDetailsDocked={false}
+ setIsSpanDetailsDocked={jest.fn()}
+ selectedSpan={mockSpanWithNodeOnly}
+ traceStartTime={1640995200000}
+ traceEndTime={1640995260000}
+ />
+ </QueryBuilderContext.Provider>,
+ );
+
+ // Click on infra tab
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+ fireEvent.click(infraMetricsButton);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Verify node-only metadata
+ expect(screen.getByTestId('infra-node-name')).toHaveTextContent(
+ expectedNodeOnlyMetadata.nodeName,
+ );
+ expect(screen.getByTestId('infra-pod-name')).toHaveTextContent(
+ expectedNodeOnlyMetadata.podName,
+ );
+ expect(screen.getByTestId('infra-cluster-name')).toHaveTextContent(
+ expectedNodeOnlyMetadata.clusterName,
+ );
+ expect(screen.getByTestId('infra-host-name')).toHaveTextContent(
+ expectedNodeOnlyMetadata.hostName,
+ );
+ });
+
+ it('should handle host-only metadata correctly', async () => {
+ render(
+ <QueryBuilderContext.Provider value={mockQueryBuilderContextValue as any}>
+ <SpanDetailsDrawer
+ isSpanDetailsDocked={false}
+ setIsSpanDetailsDocked={jest.fn()}
+ selectedSpan={mockSpanWithHostOnly}
+ traceStartTime={1640995200000}
+ traceEndTime={1640995260000}
+ />
+ </QueryBuilderContext.Provider>,
+ );
+
+ // Click on infra tab
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+ fireEvent.click(infraMetricsButton);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Verify host-only metadata
+ expect(screen.getByTestId('infra-host-name')).toHaveTextContent(
+ expectedHostOnlyMetadata.hostName,
+ );
+ expect(screen.getByTestId('infra-pod-name')).toHaveTextContent(
+ expectedHostOnlyMetadata.podName,
+ );
+ expect(screen.getByTestId('infra-node-name')).toHaveTextContent(
+ expectedHostOnlyMetadata.nodeName,
+ );
+ expect(screen.getByTestId('infra-cluster-name')).toHaveTextContent(
+ expectedHostOnlyMetadata.clusterName,
+ );
+ });
+
+ it('should switch between logs and infra tabs correctly', async () => {
+ renderSpanDetailsDrawer();
+
+ // Initially should show logs tab content
+ const logsButton = screen.getByRole('radio', { name: /logs/i });
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+
+ expect(logsButton).toBeInTheDocument();
+ expect(infraMetricsButton).toBeInTheDocument();
+
+ // Ensure logs tab is active and wait for content to load
+ fireEvent.click(logsButton);
+
+ await waitFor(() => {
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ expect(screen.getByTestId('open-in-explorer-button')).toBeInTheDocument();
+ });
+
+ // Click on infra tab
+ fireEvent.click(infraMetricsButton);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Should not show logs content anymore
+ expect(
+ screen.queryByTestId('open-in-explorer-button'),
+ ).not.toBeInTheDocument();
+
+ // Switch back to logs tab
+ fireEvent.click(logsButton);
+
+ // Should not show infra metrics anymore
+ await waitFor(() => {
+ expect(screen.queryByTestId('infra-metrics')).not.toBeInTheDocument();
+ });
+
+ // Verify logs content is shown again
+ await waitFor(() => {
+ expect(screen.getByTestId('open-in-explorer-button')).toBeInTheDocument();
+ });
+ });
+
+ it('should pass correct data source and handle multiple infra identifiers', async () => {
+ renderSpanDetailsDrawer();
+
+ // Should show infra tab when span has any of: clusterName, podName, nodeName, hostName
+ expect(screen.getByRole('radio', { name: /metrics/i })).toBeInTheDocument();
+
+ // Click on infra tab
+ const infraMetricsButton = screen.getByRole('radio', { name: /metrics/i });
+ fireEvent.click(infraMetricsButton);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('infra-metrics')).toBeInTheDocument();
+ });
+
+ // Verify TRACES data source is passed
+ expect(screen.getByTestId('infra-data-source')).toHaveTextContent(
+ DataSource.TRACES,
+ );
+
+ // All infra identifiers should be passed through
+ expect(screen.getByTestId('infra-pod-name')).toHaveTextContent(
+ 'test-pod-abc123',
+ );
+ expect(screen.getByTestId('infra-node-name')).toHaveTextContent(
+ 'test-node-456',
+ );
+ expect(screen.getByTestId('infra-host-name')).toHaveTextContent(
+ 'test-host.example.com',
+ );
+ expect(screen.getByTestId('infra-cluster-name')).toHaveTextContent(
+ 'test-cluster',
+ );
+ });
+});
diff --git a/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
index ba84123b0e..b857260f0b 100644
--- a/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
+++ b/frontend/src/container/SpanDetailsDrawer/__tests__/SpanDetailsDrawer.test.tsx
@@ -27,8 +27,9 @@ import {
// Mock external dependencies
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
+ useLocation: (): { pathname: string; search: string } => ({
pathname: `${ROUTES.TRACE_DETAIL}`,
+ search: 'trace_id=test-trace-id',
}),
}));
diff --git a/frontend/src/container/SpanDetailsDrawer/__tests__/infraMetricsTestData.ts b/frontend/src/container/SpanDetailsDrawer/__tests__/infraMetricsTestData.ts
new file mode 100644
index 0000000000..7e5b37b9d4
--- /dev/null
+++ b/frontend/src/container/SpanDetailsDrawer/__tests__/infraMetricsTestData.ts
@@ -0,0 +1,169 @@
+import { Span } from 'types/api/trace/getTraceV2';
+
+// Constants
+const TEST_TRACE_ID = 'test-trace-id';
+const TEST_CLUSTER_NAME = 'test-cluster';
+const TEST_POD_NAME = 'test-pod-abc123';
+const TEST_NODE_NAME = 'test-node-456';
+const TEST_HOST_NAME = 'test-host.example.com';
+
+// Mock span with infrastructure metadata (pod + node + host)
+export const mockSpanWithInfraMetadata: Span = {
+ spanId: 'infra-span-id',
+ traceId: TEST_TRACE_ID,
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ name: 'api-service',
+ serviceName: 'api-service',
+ timestamp: 1640995200000000, // 2022-01-01 00:00:00 in microseconds
+ durationNano: 2000000000, // 2 seconds in nanoseconds
+ spanKind: 'server',
+ statusCodeString: 'STATUS_CODE_OK',
+ statusMessage: '',
+ parentSpanId: '',
+ references: [],
+ event: [],
+ tagMap: {
+ 'k8s.cluster.name': TEST_CLUSTER_NAME,
+ 'k8s.pod.name': TEST_POD_NAME,
+ 'k8s.node.name': TEST_NODE_NAME,
+ 'host.name': TEST_HOST_NAME,
+ 'service.name': 'api-service',
+ 'http.method': 'GET',
+ },
+ hasError: false,
+ rootSpanId: '',
+ kind: 0,
+ rootName: '',
+ hasChildren: false,
+ hasSibling: false,
+ subTreeNodeCount: 0,
+ level: 0,
+};
+
+// Mock span with only pod metadata
+export const mockSpanWithPodOnly: Span = {
+ ...mockSpanWithInfraMetadata,
+ spanId: 'pod-only-span-id',
+ tagMap: {
+ 'k8s.cluster.name': TEST_CLUSTER_NAME,
+ 'k8s.pod.name': TEST_POD_NAME,
+ 'service.name': 'api-service',
+ },
+};
+
+// Mock span with only node metadata
+export const mockSpanWithNodeOnly: Span = {
+ ...mockSpanWithInfraMetadata,
+ spanId: 'node-only-span-id',
+ tagMap: {
+ 'k8s.node.name': TEST_NODE_NAME,
+ 'service.name': 'api-service',
+ },
+};
+
+// Mock span with only host metadata
+export const mockSpanWithHostOnly: Span = {
+ ...mockSpanWithInfraMetadata,
+ spanId: 'host-only-span-id',
+ tagMap: {
+ 'host.name': TEST_HOST_NAME,
+ 'service.name': 'api-service',
+ },
+};
+
+// Mock span without any infrastructure metadata
+export const mockSpanWithoutInfraMetadata: Span = {
+ ...mockSpanWithInfraMetadata,
+ spanId: 'no-infra-span-id',
+ tagMap: {
+ 'service.name': 'api-service',
+ 'http.method': 'GET',
+ 'http.status_code': '200',
+ },
+};
+
+// Mock infrastructure metrics API responses
+export const mockPodMetricsResponse = {
+ payload: {
+ data: {
+ newResult: {
+ data: {
+ result: [
+ {
+ metric: { pod_name: TEST_POD_NAME },
+ values: [
+ [1640995200, '0.5'], // CPU usage
+ [1640995260, '0.6'],
+ ],
+ },
+ ],
+ },
+ },
+ },
+ },
+};
+
+export const mockNodeMetricsResponse = {
+ payload: {
+ data: {
+ newResult: {
+ data: {
+ result: [
+ {
+ metric: { node_name: TEST_NODE_NAME },
+ values: [
+ [1640995200, '2.1'], // Memory usage
+ [1640995260, '2.3'],
+ ],
+ },
+ ],
+ },
+ },
+ },
+ },
+};
+
+export const mockEmptyMetricsResponse = {
+ payload: {
+ data: {
+ newResult: {
+ data: {
+ result: [],
+ },
+ },
+ },
+ },
+};
+
+// Expected infrastructure metadata extractions
+export const expectedInfraMetadata = {
+ clusterName: TEST_CLUSTER_NAME,
+ podName: TEST_POD_NAME,
+ nodeName: TEST_NODE_NAME,
+ hostName: TEST_HOST_NAME,
+};
+
+export const expectedPodOnlyMetadata = {
+ clusterName: TEST_CLUSTER_NAME,
+ podName: TEST_POD_NAME,
+ nodeName: '',
+ hostName: '',
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ spanTimestamp: '2022-01-01T00:00:00.000Z',
+};
+
+export const expectedNodeOnlyMetadata = {
+ clusterName: '',
+ podName: '',
+ nodeName: TEST_NODE_NAME,
+ hostName: '',
+ spanTimestamp: '2022-01-01T00:00:00.000Z',
+};
+
+export const expectedHostOnlyMetadata = {
+ clusterName: '',
+ podName: '',
+ nodeName: '',
+ hostName: TEST_HOST_NAME,
+ spanTimestamp: '2022-01-01T00:00:00.000Z',
+};
diff --git a/frontend/src/container/SpanDetailsDrawer/constants.ts b/frontend/src/container/SpanDetailsDrawer/constants.ts
index b93c431837..9fd159ed0f 100644
--- a/frontend/src/container/SpanDetailsDrawer/constants.ts
+++ b/frontend/src/container/SpanDetailsDrawer/constants.ts
@@ -1,11 +1,11 @@
export enum RelatedSignalsViews {
LOGS = 'logs',
// METRICS = 'metrics',
- // INFRA = 'infra',
+ INFRA = 'infra',
}
export const RELATED_SIGNALS_VIEW_TYPES = {
LOGS: RelatedSignalsViews.LOGS,
// METRICS: RelatedSignalsViews.METRICS,
- // INFRA: RelatedSignalsViews.INFRA,
+ INFRA: RelatedSignalsViews.INFRA,
};
diff --git a/frontend/src/container/SpanDetailsDrawer/utils.ts b/frontend/src/container/SpanDetailsDrawer/utils.ts
new file mode 100644
index 0000000000..b0d3ce5fdb
--- /dev/null
+++ b/frontend/src/container/SpanDetailsDrawer/utils.ts
@@ -0,0 +1,22 @@
+import { Span } from 'types/api/trace/getTraceV2';
+
+/**
+ * Infrastructure metadata keys that indicate infra signals are available
+ */
+export const INFRA_METADATA_KEYS = [
+ 'k8s.cluster.name',
+ 'k8s.pod.name',
+ 'k8s.node.name',
+ 'host.name',
+] as const;
+
+/**
+ * Checks if a span has any infrastructure metadata attributes
+ * @param span - The span to check for infrastructure metadata
+ * @returns true if the span has at least one infrastructure metadata key, false otherwise
+ */
+export function hasInfraMetadata(span: Span | undefined): boolean {
+ if (!span?.tagMap) return false;
+
+ return INFRA_METADATA_KEYS.some((key) => span.tagMap?.[key]);
+}