Compare commits

..

1 Commits

Author SHA1 Message Date
srikanthccv
bdd7e9adf6 feat(semconv): add migration product surfaces
Span-metrics label keys keep the collector's spelling until the metrics
rename ships. The related-values table holds no metrics rows, so the
migration report covers traces and logs. The response meta reports a
resolution only when family resolution is on for the org, so a literal
query does not claim one. db.system keeps its old name in product code,
because that family is off until a value map reader exists.

Assisted-by: Claude Fable 5.2
2026-11-27 12:49:43 +05:30
61 changed files with 1928 additions and 49 deletions

View File

@@ -10178,6 +10178,13 @@ components:
nothing about whether data exists.'
minimum: 0
type: integer
semconvResolutions:
description: The semantic-convention families that the builder queries in
the request resolved. Absent when no query named a family member or when
family resolution is off.
items:
$ref: '#/components/schemas/Querybuildertypesv5SemconvResolution'
type: array
stepIntervals:
additionalProperties:
minimum: 0
@@ -11358,6 +11365,28 @@ components:
description: 'The time bucket for this aggregation: seconds as a number
or a Go duration string. Uses the primary aggregation step when omitted.'
type: object
Querybuildertypesv5SemconvResolution:
properties:
current:
description: The current name of the family.
type: string
kind:
description: 'The family kind: attribute or metric.'
type: string
members:
description: Every name the query read, the current name first.
items:
type: string
type: array
requested:
description: The name as the request spelled it.
type: string
required:
- requested
- current
- members
- kind
type: object
Querybuildertypesv5Step:
description: Step interval. Accepts a Go duration string (e.g., "60s", "1m",
"1h") or a number representing seconds (e.g., 60).
@@ -13705,6 +13734,62 @@ components:
- values
- complete
type: object
TelemetrytypesGettableSemconvMigrationReport:
properties:
endUnixMilli:
description: End of the window the report covers, in Unix milliseconds.
format: int64
type: integer
entries:
description: One entry for each family, old name and signal with at least
one service that sends only the old name. Empty when there is none.
items:
$ref: '#/components/schemas/TelemetrytypesSemconvMigrationReportEntry'
type: array
startUnixMilli:
description: Start of the window the report covers, in Unix milliseconds.
format: int64
type: integer
required:
- startUnixMilli
- endUnixMilli
- entries
type: object
TelemetrytypesSemconvMigrationReportEntry:
properties:
current:
description: The current name of the family.
type: string
lastSeenUnixMilli:
description: Latest time the metadata recorded such a set, in Unix milliseconds.
format: int64
type: integer
old:
description: The old name that the listed services still send.
type: string
resourceSets:
description: Number of distinct resource and attribute sets that carry the
old name and no current name.
minimum: 0
type: integer
services:
description: Services that sent the old name and no current name in the
window, sorted by name. A resource without service.name is listed as <unknown>.
items:
type: string
type: array
signal:
allOf:
- $ref: '#/components/schemas/TelemetrytypesSignal'
description: 'The signal the old name was seen in: traces or logs.'
required:
- current
- old
- signal
- services
- resourceSets
- lastSeenUnixMilli
type: object
TelemetrytypesSignal:
enum:
- traces
@@ -16166,6 +16251,73 @@ paths:
tags:
- fields
x-signoz-stability: alpha
/api/v1/fields/semconv-migration:
get:
deprecated: false
description: Returns services that still emit old semantic-convention names
without the current family name
operationId: GetSemconvMigrationReport
parameters:
- description: Start of the lookup window in Unix milliseconds. Omit for 24
hours before the current time.
in: query
name: startUnixMilli
schema:
description: Start of the lookup window in Unix milliseconds. Omit for 24
hours before the current time.
format: int64
type: integer
- description: End of the lookup window in Unix milliseconds. Omit for the current
time.
in: query
name: endUnixMilli
schema:
description: End of the lookup window in Unix milliseconds. Omit for the
current time.
format: int64
type: integer
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/TelemetrytypesGettableSemconvMigrationReport'
status:
type: string
required:
- status
- data
type: object
description: OK
"401":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Unauthorized
"403":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
security:
- api_key:
- VIEWER
- tokenizer:
- VIEWER
summary: Get semantic-convention migration report
tags:
- fields
x-signoz-stability: alpha
/api/v1/fields/values:
get:
deprecated: false

View File

@@ -15,6 +15,8 @@
content="frame-src 'self' blob: data:"
/>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script>
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
// /public/locales does not ship; pin it to the bundled language instead.

View File

@@ -22,7 +22,6 @@ import i18n from '../src/ReactI18';
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
// not report because the requests look like static assets.
import '../src/lib/monaco/loader';
import '../src/lib/uPlotStylesheet';
import '../src/styles.scss';

View File

@@ -157,6 +157,7 @@
})(document, 'script');
}
</script>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

1
frontend/public/css/uPlot.min.css vendored Normal file
View File

@@ -0,0 +1 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}

View File

@@ -19,6 +19,8 @@ import type {
GetFieldsKeysParams,
GetFieldsValues200,
GetFieldsValuesParams,
GetSemconvMigrationReport200,
GetSemconvMigrationReportParams,
RenderErrorResponseDTO,
} from '../sigNoz.schemas';
@@ -140,6 +142,108 @@ export const invalidateGetFieldsKeys = async (
return queryClient;
};
/**
* Returns services that still emit old semantic-convention names without the current family name
* @summary Get semantic-convention migration report
*/
export const getSemconvMigrationReport = (
params?: GetSemconvMigrationReportParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetSemconvMigrationReport200>({
url: `/api/v1/fields/semconv-migration`,
method: 'GET',
params,
signal,
});
};
export const getGetSemconvMigrationReportQueryKey = (
params?: GetSemconvMigrationReportParams,
) => {
return [
`/api/v1/fields/semconv-migration`,
...(params ? [params] : []),
] as const;
};
export const getGetSemconvMigrationReportQueryOptions = <
TData = Awaited<ReturnType<typeof getSemconvMigrationReport>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
params?: GetSemconvMigrationReportParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getSemconvMigrationReport>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getGetSemconvMigrationReportQueryKey(params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof getSemconvMigrationReport>>
> = ({ signal }) => getSemconvMigrationReport(params, signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof getSemconvMigrationReport>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetSemconvMigrationReportQueryResult = NonNullable<
Awaited<ReturnType<typeof getSemconvMigrationReport>>
>;
export type GetSemconvMigrationReportQueryError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get semantic-convention migration report
*/
export function useGetSemconvMigrationReport<
TData = Awaited<ReturnType<typeof getSemconvMigrationReport>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
params?: GetSemconvMigrationReportParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getSemconvMigrationReport>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetSemconvMigrationReportQueryOptions(params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Get semantic-convention migration report
*/
export const invalidateGetSemconvMigrationReport = async (
queryClient: QueryClient,
params?: GetSemconvMigrationReportParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetSemconvMigrationReportQueryKey(params) },
options,
);
return queryClient;
};
/**
* This endpoint returns field values
* @summary Get field values

View File

@@ -12148,6 +12148,29 @@ export type Querybuildertypesv5ExecStatsDTOStepIntervals = {
[key: string]: number;
};
export interface Querybuildertypesv5SemconvResolutionDTO {
/**
* @type string
* @description The current name of the family.
*/
current: string;
/**
* @type string
* @description The family kind: attribute or metric.
*/
kind: string;
/**
* @type array
* @description Every name the query read, the current name first.
*/
members: string[];
/**
* @type string
* @description The name as the request spelled it.
*/
requested: string;
}
/**
* Execution cost of the request: rows and bytes scanned and execution time. A measure of cost, not of whether data exists.
*/
@@ -12170,6 +12193,11 @@ export interface Querybuildertypesv5ExecStatsDTO {
* @description Rows scanned to answer every query in the request. A cost indicator only: rows are scanned whether or not any matched, so it says nothing about whether data exists.
*/
rowsScanned?: number;
/**
* @type array
* @description The semantic-convention families that the builder queries in the request resolved. Absent when no query named a family member or when family resolution is off.
*/
semconvResolutions?: Querybuildertypesv5SemconvResolutionDTO[];
/**
* @type object
* @description The step interval in seconds that was used for each query, keyed by query name.
@@ -14861,6 +14889,60 @@ export interface TelemetrytypesGettableFieldValuesDTO {
values: TelemetrytypesTelemetryFieldValuesDTO;
}
export interface TelemetrytypesSemconvMigrationReportEntryDTO {
/**
* @type string
* @description The current name of the family.
*/
current: string;
/**
* @type integer
* @format int64
* @description Latest time the metadata recorded such a set, in Unix milliseconds.
*/
lastSeenUnixMilli: number;
/**
* @type string
* @description The old name that the listed services still send.
*/
old: string;
/**
* @type integer
* @minimum 0
* @description Number of distinct resource and attribute sets that carry the old name and no current name.
*/
resourceSets: number;
/**
* @type array
* @description Services that sent the old name and no current name in the window, sorted by name. A resource without service.name is listed as <unknown>.
*/
services: string[];
/**
* @description The signal the old name was seen in: traces or logs.
*/
signal: TelemetrytypesSignalDTO;
}
export interface TelemetrytypesGettableSemconvMigrationReportDTO {
/**
* @type integer
* @format int64
* @description End of the window the report covers, in Unix milliseconds.
*/
endUnixMilli: number;
/**
* @type array
* @description One entry for each family, old name and signal with at least one service that sends only the old name. Empty when there is none.
*/
entries: TelemetrytypesSemconvMigrationReportEntryDTO[];
/**
* @type integer
* @format int64
* @description Start of the window the report covers, in Unix milliseconds.
*/
startUnixMilli: number;
}
export interface TypesChangePasswordRequestDTO {
/**
* @type string
@@ -15568,6 +15650,29 @@ export type GetFieldsKeys200 = {
status: string;
};
export type GetSemconvMigrationReportParams = {
/**
* @type integer
* @format int64
* @description Start of the lookup window in Unix milliseconds. Omit for 24 hours before the current time.
*/
startUnixMilli?: number;
/**
* @type integer
* @format int64
* @description End of the lookup window in Unix milliseconds. Omit for the current time.
*/
endUnixMilli?: number;
};
export type GetSemconvMigrationReport200 = {
data: TelemetrytypesGettableSemconvMigrationReportDTO;
/**
* @type string
*/
status: string;
};
export type GetFieldsValuesParams = {
/**
* @description The signal to look up keys in: traces, logs or metrics. Empty searches every signal.

View File

@@ -0,0 +1,3 @@
.warning {
margin: var(--spacing-4) 0;
}

View File

@@ -0,0 +1,38 @@
import { Callout } from '@signozhq/ui/callout';
import { TriangleAlert } from '@signozhq/icons';
import { findOldSemconvNames } from 'utils/semconv';
import styles from './SemconvEditorWarning.module.scss';
interface SemconvEditorWarningProps {
value: unknown;
editor: string;
}
function SemconvEditorWarning({
value,
editor,
}: SemconvEditorWarningProps): JSX.Element | null {
const text = typeof value === 'string' ? value : JSON.stringify(value ?? '');
const renames = findOldSemconvNames(text);
if (renames.length === 0) {
return null;
}
return (
<div className={styles.warning}>
<Callout
color="warning"
size="sm"
icon={<TriangleAlert />}
testId="semconv-editor-warning"
>
{`${editor} contains renamed OpenTelemetry fields: ${renames
.map(({ old, current }) => `${old} → ${current}`)
.join(', ')}`}
</Callout>
</div>
);
}
export default SemconvEditorWarning;

View File

@@ -0,0 +1,24 @@
import { Badge } from '@signozhq/ui/badge';
interface SemconvOldNameBadgeProps {
old: string;
current: string;
}
function SemconvOldNameBadge({
old,
current,
}: SemconvOldNameBadgeProps): JSX.Element {
return (
<Badge
color="warning"
variant="outlined"
textTransform="none"
testId={`semconv-old-name-badge-${old}`}
>
{`old name, renamed to ${current}`}
</Badge>
);
}
export default SemconvOldNameBadge;

View File

@@ -0,0 +1,55 @@
import { render, screen } from 'tests/test-utils';
import SemconvEditorWarning from '../SemconvEditorWarning';
const WARNING_ID = 'semconv-editor-warning';
describe('SemconvEditorWarning', () => {
it('names the editor and each old name with its current name', () => {
render(
<SemconvEditorWarning
value="SELECT resources_string['deployment.environment'] FROM t"
editor="ClickHouse SQL"
/>,
);
expect(screen.getByTestId(WARNING_ID)).toHaveTextContent(
'ClickHouse SQL contains renamed OpenTelemetry fields: deployment.environment → deployment.environment.name',
);
});
it('reads a pipeline filter object', () => {
render(
<SemconvEditorWarning
value={{
op: 'AND',
items: [
{ key: { key: 'deployment.environment' }, op: '=', value: 'prod' },
],
}}
editor="Pipeline filter"
/>,
);
expect(screen.getByTestId(WARNING_ID)).toHaveTextContent(
'Pipeline filter contains renamed OpenTelemetry fields: deployment.environment → deployment.environment.name',
);
});
it('shows nothing for a current name', () => {
render(
<SemconvEditorWarning
value={'{deployment.environment.name="prod"}'}
editor="PromQL"
/>,
);
expect(screen.queryByTestId(WARNING_ID)).not.toBeInTheDocument();
});
it('shows nothing for an empty editor', () => {
render(<SemconvEditorWarning value={undefined} editor="PromQL" />);
expect(screen.queryByTestId(WARNING_ID)).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,43 @@
import { render, screen } from 'tests/test-utils';
import { renderOldNameBadge } from '../renderOldNameBadge';
const BADGE_ID = 'semconv-old-name-badge-deployment.environment';
describe('renderOldNameBadge', () => {
it('badges an old resource attribute with its current name', () => {
render(<>{renderOldNameBadge(['resource', 'deployment.environment'])}</>);
expect(screen.getByTestId(BADGE_ID)).toHaveTextContent(
'old name, renamed to deployment.environment.name',
);
});
it('badges an old name in the attributes map', () => {
render(<>{renderOldNameBadge(['attributes', 'deployment.environment'])}</>);
expect(screen.getByTestId(BADGE_ID)).toBeInTheDocument();
});
it('returns nothing for a current name', () => {
expect(
renderOldNameBadge(['resource', 'deployment.environment.name']),
).toBeNull();
});
it('returns nothing for the same spelling inside a JSON body', () => {
expect(renderOldNameBadge(['body', 'deployment.environment'])).toBeNull();
});
it('returns nothing for a key nested under an old-name attribute', () => {
expect(
renderOldNameBadge(['attributes', 'deployment.environment', 'region']),
).toBeNull();
});
it('returns nothing for an old metric name', () => {
expect(
renderOldNameBadge(['attributes', 'k8s.pod.cpu.utilization']),
).toBeNull();
});
});

View File

@@ -0,0 +1,27 @@
import { ReactNode } from 'react';
import { getSemconvRename } from 'utils/semconv';
import SemconvOldNameBadge from './SemconvOldNameBadge';
const ATTRIBUTE_MAPS = new Set(['attributes', 'resource']);
// A span and a log record hold their attributes in these two maps. A key of
// the same spelling at another depth, for example in a JSON body, is not an
// attribute name.
export function renderOldNameBadge(
fieldKeyPath: readonly (string | number)[],
): ReactNode {
if (
fieldKeyPath.length !== 2 ||
!ATTRIBUTE_MAPS.has(String(fieldKeyPath[0]))
) {
return null;
}
const rename = getSemconvRename(String(fieldKeyPath[1]));
if (!rename || rename.family.kind !== 'attribute') {
return null;
}
return <SemconvOldNameBadge old={rename.old} current={rename.current} />;
}

View File

@@ -10,7 +10,7 @@ export const AllTraceFilterKeyValue: Record<string, string> = {
durationNano: 'Duration',
duration_nano: 'Duration',
durationNanoMax: 'Duration',
'deployment.environment': 'Environment',
'deployment.environment.name': 'Environment',
hasError: 'Status',
has_error: 'Status',
serviceName: 'Service Name',
@@ -55,11 +55,11 @@ export const traceFilterKeys: Record<AllTraceFilterKeys, BaseAutocompleteData> =
id: 'serviceName--string--tag--true',
},
'deployment.environment': {
key: 'deployment.environment',
'deployment.environment.name': {
key: 'deployment.environment.name',
dataType: DataTypes.String,
type: 'resource',
id: 'deployment.environment--string--resource--false',
id: 'deployment.environment.name--string--resource--false',
},
name: {
key: 'name',

View File

@@ -14,6 +14,7 @@ import uPlot from 'uplot';
import tooltipPlugin from './tooltipPlugin';
import 'uplot/dist/uPlot.min.css';
import './AnomalyAlertEvaluationView.styles.scss';
const { Search } = Input;

View File

@@ -169,7 +169,7 @@ function DomainList(): JSX.Element {
queryData={query}
onChange={handleSearchChange}
onRun={handleStageAndRunQuery}
placeholder="Enter your filter query (e.g., deployment.environment = 'otel-demo' AND service.name = 'frontend')"
placeholder="Enter your filter query (e.g., deployment.environment.name = 'otel-demo' AND service.name = 'frontend')"
hardcodedAttributeKeys={ApiMonitoringHardcodedAttributeKeys}
/>
</div>

View File

@@ -6,9 +6,9 @@ import { SPAN_ATTRIBUTES } from './Explorer/Domains/DomainDetails/constants';
export const ApiMonitoringHardcodedAttributeKeys: QueryKeyDataSuggestionsProps[] =
[
{
label: 'deployment.environment',
label: 'deployment.environment.name',
type: 'resource',
name: 'deployment.environment',
name: 'deployment.environment.name',
signal: 'traces',
fieldDataType: QUERY_BUILDER_KEY_TYPES.STRING,
},

View File

@@ -128,7 +128,7 @@ export const INFRA_MONITORING_ATTR_KEYS = {
K8S_OBJECT_NAME: 'k8s.object.name',
// Environment
DEPLOYMENT_ENVIRONMENT: 'deployment.environment',
DEPLOYMENT_ENVIRONMENT: 'deployment.environment.name',
// Host System
OS_TYPE: 'os.type',
@@ -906,7 +906,7 @@ export const ENTITY_FILTER_PLACEHOLDERS: Record<InfraMonitoringEntity, string> =
[InfraMonitoringEntity.NAMESPACES]:
"Enter your filter query (e.g., k8s.namespace.name = 'production' AND k8s.cluster.name = 'prod-cluster')",
[InfraMonitoringEntity.CLUSTERS]:
"Enter your filter query (e.g., k8s.cluster.name = 'prod-cluster' AND deployment.environment = 'production')",
"Enter your filter query (e.g., k8s.cluster.name = 'prod-cluster' AND deployment.environment.name = 'production')",
[InfraMonitoringEntity.DEPLOYMENTS]:
"Enter your filter query (e.g., k8s.deployment.name = 'api-server' AND k8s.namespace.name = 'production')",
[InfraMonitoringEntity.STATEFULSETS]:

View File

@@ -7,6 +7,7 @@ import { useAppContext } from 'providers/App/App';
import { IngestionDataType } from 'types/api/settings/ingestion';
import styles from './IngestionSettings.module.scss';
import SemconvMigrationReport from './SemconvMigrationReport/SemconvMigrationReport';
import './IngestionSettings.styles.scss';
export default function IngestionSettings(): JSX.Element {
@@ -118,6 +119,7 @@ export default function IngestionSettings(): JSX.Element {
dataSource={data}
bordered
/>
<SemconvMigrationReport />
</div>
);
}

View File

@@ -98,6 +98,8 @@ import { MeterAggregateOperator } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
import { getDaysUntilExpiry } from 'utils/timeUtils';
import SemconvMigrationReport from './SemconvMigrationReport/SemconvMigrationReport';
import 'components/LearnMore/LearnMore.styles.scss';
import './IngestionSettings.styles.scss';
@@ -1871,6 +1873,7 @@ function MultiIngestionSettings(): JSX.Element {
className="ingestion-keys-table"
/>
</AuthZGuardContent>
<SemconvMigrationReport />
</div>
{/* Delete Key Modal */}

View File

@@ -0,0 +1,17 @@
.report {
display: flex;
flex-direction: column;
gap: var(--spacing-6);
margin-top: var(--spacing-16);
}
.empty {
padding: var(--spacing-8) 0;
}
// The table breaks cell text at any character. A list of services reads
// better when it wraps between names.
.services {
word-break: normal;
overflow-wrap: anywhere;
}

View File

@@ -0,0 +1,94 @@
import { useMemo } from 'react';
import { Callout } from '@signozhq/ui/callout';
import { Typography } from '@signozhq/ui/typography';
import { SolidAlertCircle } from '@signozhq/icons';
import { useGetSemconvMigrationReport } from 'api/generated/services/fields';
import TanStackTable from 'components/TanStackTableView';
import { useTimezone } from 'providers/Timezone';
import styles from './SemconvMigrationReport.module.scss';
import {
getSemconvMigrationReportColumns,
getSemconvMigrationRowKey,
} from './table.config';
const SKELETON_ROW_COUNT = 3;
// The ingestion keys column is narrow, so a long name or a long list of
// services wraps instead of ending in an ellipsis.
const NAME_AND_SERVICES_MAX_LINES = 3;
function SemconvMigrationReport(): JSX.Element {
const { data, isLoading, isError } = useGetSemconvMigrationReport();
const { formatTimezoneAdjustedTimestamp } = useTimezone();
const columns = useMemo(
() => getSemconvMigrationReportColumns(formatTimezoneAdjustedTimestamp),
[formatTimezoneAdjustedTimestamp],
);
const entries = data?.data.entries ?? [];
return (
<section className={styles.report} data-testid="semconv-migration-report">
<Typography
variant="label"
size="large"
weight="bold"
color="inherit"
as="h4"
textOverflow="wrap"
>
Semantic convention migration
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="p"
textOverflow="wrap"
>
Services in this report sent an old OpenTelemetry field during the last 24
hours without sending its current replacement. Update their SDK or
instrumentation when practical; SigNoz queries remain backward compatible.
</Typography>
{isError && (
<Callout
color="danger"
size="sm"
icon={<SolidAlertCircle />}
testId="semconv-migration-report-error"
>
Could not load the semantic convention migration report
</Callout>
)}
{!isError && !isLoading && entries.length === 0 && (
<div className={styles.empty}>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="tertiary"
as="p"
textOverflow="wrap"
testId="semconv-migration-report-empty"
>
No old-only services found in the last 24 hours
</Typography>
</div>
)}
{!isError && (isLoading || entries.length > 0) && (
<TanStackTable
data={entries}
columns={columns}
isLoading={isLoading}
skeletonRowCount={SKELETON_ROW_COUNT}
getRowKey={getSemconvMigrationRowKey}
plainTextCellLineClamp={NAME_AND_SERVICES_MAX_LINES}
disableVirtualScroll
testId="semconv-migration-report-table"
/>
)}
</section>
);
}
export default SemconvMigrationReport;

View File

@@ -0,0 +1,89 @@
import {
type GetSemconvMigrationReport200,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen } from 'tests/test-utils';
import SemconvMigrationReport from '../SemconvMigrationReport';
const REPORT_URL = '*/api/v1/fields/semconv-migration';
const report: GetSemconvMigrationReport200 = {
status: 'success',
data: {
startUnixMilli: 1764115200000,
endUnixMilli: 1764201600000,
entries: [
{
current: 'deployment.environment.name',
old: 'deployment.environment',
signal: TelemetrytypesSignalDTO.traces,
services: ['cart', 'checkout'],
resourceSets: 3,
lastSeenUnixMilli: 1764180000000,
},
],
},
};
describe('SemconvMigrationReport', () => {
it('lists the services that send only the old name', async () => {
server.use(
rest.get(REPORT_URL, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(report)),
),
);
render(<SemconvMigrationReport />);
await expect(
screen.findByTestId(
'semconv-migration-services-traces-deployment.environment',
),
).resolves.toHaveTextContent('cart, checkout');
});
it('says that no service is behind when the report is empty', async () => {
const empty: GetSemconvMigrationReport200 = {
...report,
data: { ...report.data, entries: [] },
};
server.use(
rest.get(REPORT_URL, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(empty)),
),
);
render(<SemconvMigrationReport />);
await expect(
screen.findByTestId('semconv-migration-report-empty'),
).resolves.toHaveTextContent(
'No old-only services found in the last 24 hours',
);
});
it('shows an error when the report does not load', async () => {
server.use(
rest.get(REPORT_URL, (_req, res, ctx) =>
res(
ctx.status(500),
ctx.json({
status: 'error',
error: { code: 'internal', message: 'boom' },
}),
),
),
);
render(<SemconvMigrationReport />);
await expect(
screen.findByTestId('semconv-migration-report-error'),
).resolves.toHaveTextContent(
'Could not load the semantic convention migration report',
);
});
});

View File

@@ -0,0 +1,95 @@
import type { TelemetrytypesSemconvMigrationReportEntryDTO } from 'api/generated/services/sigNoz.schemas';
import type { TableColumnDef } from 'components/TanStackTableView';
import TanStackTable from 'components/TanStackTableView';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import styles from './SemconvMigrationReport.module.scss';
export function getSemconvMigrationRowKey(
entry: TelemetrytypesSemconvMigrationReportEntryDTO,
): string {
return JSON.stringify([entry.current, entry.old, entry.signal]);
}
export function getSemconvMigrationReportColumns(
formatTimezoneAdjustedTimestamp: (date: number, format: string) => string,
): TableColumnDef<TelemetrytypesSemconvMigrationReportEntryDTO>[] {
return [
{
id: 'old',
header: 'Old name',
accessorKey: 'old',
width: { default: '180px', min: '140px' },
enableSort: false,
enableMove: false,
enableRemove: false,
cell: ({ row }): JSX.Element => (
<TanStackTable.Text title={row.old}>{row.old}</TanStackTable.Text>
),
},
{
id: 'current',
header: 'Current name',
accessorKey: 'current',
width: { default: '220px', min: '160px' },
enableSort: false,
enableMove: false,
enableRemove: false,
cell: ({ row }): JSX.Element => (
<TanStackTable.Text title={row.current}>{row.current}</TanStackTable.Text>
),
},
{
id: 'signal',
header: 'Signal',
accessorKey: 'signal',
width: { default: '70px', min: '70px' },
enableSort: false,
enableMove: false,
enableRemove: false,
cell: ({ row }): JSX.Element => (
<TanStackTable.Text>{row.signal}</TanStackTable.Text>
),
},
{
id: 'services',
header: 'Services',
accessorKey: 'services',
width: { default: '100%', min: '120px' },
enableSort: false,
enableMove: false,
enableRemove: false,
cell: ({ row }): JSX.Element => {
// While the report loads, the table calls this with a placeholder
// row that has no fields.
const services = row.services?.join(', ');
return (
<TanStackTable.Text
className={styles.services}
title={services}
data-testid={`semconv-migration-services-${row.signal}-${row.old}`}
>
{services}
</TanStackTable.Text>
);
},
},
{
id: 'lastSeen',
header: 'Last seen',
accessorKey: 'lastSeenUnixMilli',
width: { default: '130px', min: '130px', passLastColumnFill: true },
enableSort: false,
enableMove: false,
enableRemove: false,
cell: ({ row }): JSX.Element => (
<TanStackTable.Text>
{formatTimezoneAdjustedTimestamp(
row.lastSeenUnixMilli,
DATE_TIME_FORMATS.ISO_DATETIME,
)}
</TanStackTable.Text>
),
},
];
}

View File

@@ -18,7 +18,7 @@ export const SAMPLE_SPAN_JSON = `{
},
"resource": {
"service.name": "llm-gateway",
"deployment.environment": "production"
"deployment.environment.name": "production"
}
}`;

View File

@@ -1,4 +1,5 @@
import { ReactNode } from 'react';
import { renderOldNameBadge } from 'components/Semconv/renderOldNameBadge';
import { ChangeViewFunctionType } from 'hooks/useHandleExplorerTabChange';
import { DataViewer } from 'periscope/components/DataViewer';
import { ILog } from 'types/api/logs/log';
@@ -47,6 +48,7 @@ function Overview({
prettyViewProps={{
actions,
visibleActions,
labelSuffixRenderer: renderOldNameBadge,
renderLeafValue: (value, keyPath): ReactNode | undefined => {
// Sanitize (unescape + ANSI→color) string values under `body`.
// Skip huge ones (render raw, still safe) to avoid the sanitize

View File

@@ -0,0 +1,50 @@
import { ILog } from 'types/api/logs/log';
import {
getFiltersFromResources,
isServiceOrEnvironmentAttribute,
} from '../utils';
const filtersOf = (resources: Record<string, string>): unknown[][] =>
getFiltersFromResources(resources as ILog['resources_string']).map((item) => [
item.key?.key,
item.value,
]);
describe('getFiltersFromResources', () => {
it('keeps the old name of a log that has only the old name', () => {
expect(
filtersOf({
'service.name': 'cart',
'deployment.environment': 'production',
}),
).toStrictEqual([
['service.name', 'cart'],
['deployment.environment', 'production'],
]);
});
it('keeps the current name of a log that has only the current name', () => {
expect(
filtersOf({ 'deployment.environment.name': 'production' }),
).toStrictEqual([['deployment.environment.name', 'production']]);
});
it('keeps only the current name of a log that has both names', () => {
expect(
filtersOf({
'deployment.environment': 'production',
'deployment.environment.name': 'staging',
}),
).toStrictEqual([['deployment.environment.name', 'staging']]);
});
});
describe('isServiceOrEnvironmentAttribute', () => {
it.each(['deployment.environment.name', 'deployment.environment'])(
'always includes %s',
(key) => {
expect(isServiceOrEnvironmentAttribute(key)).toBe(true);
},
);
});

View File

@@ -6,13 +6,14 @@ import {
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
import { v4 as uuid } from 'uuid';
import { getSemconvRename } from 'utils/semconv';
const FALLBACK_STARTS_WITH_REGEX = /^(k8s|cloud|host|deployment)/; // regex to filter out resources that start with the specified keywords
const FALLBACK_CONTAINS_REGEX = /(env|service|file|container|tenant)/; // regex to filter out resources that contains the specified keywords
// Priority categories for filter selection
// Strategy:
// - Always include: service.name, deployment.environment, env, environment
// - Always include: service.name, deployment.environment.name, deployment.environment, env, environment
// - Select ONE category only: stops at the first category with a matching attribute
// - Within category: picks the first available attribute by order
// - Order (highest to lowest priority): Kubernetes > Cloud > Host > Container
@@ -26,6 +27,7 @@ const PRIORITY_CATEGORIES = [
const SERVICE_AND_ENVIRONMENT_KEYS = [
'service.name',
'deployment.environment.name',
'deployment.environment',
'env',
'environment',
@@ -33,20 +35,36 @@ const SERVICE_AND_ENVIRONMENT_KEYS = [
export const getFiltersFromResources = (
resources: ILog['resources_string'],
): TagFilterItem[] =>
Object.keys(resources).map((key: string) => {
const resourceValue = resources[key] as string;
return {
id: uuid(),
key: {
key,
dataType: DataTypes.String,
type: 'resource',
},
op: OPERATORS['='],
value: resourceValue,
};
});
): TagFilterItem[] => {
const keys = Object.keys(resources);
return (
keys
// The filter keeps the name the log has, so it matches the log with
// family resolution on or off. A log with both names of a family
// keeps the current one: resolution reads that value, and a second
// filter on the old value would exclude the log.
.filter((key) => {
const rename = getSemconvRename(key);
return !(
rename?.family.kind === 'attribute' && keys.includes(rename.current)
);
})
.map((key: string) => {
const resourceValue = resources[key] as string;
return {
id: uuid(),
key: {
key,
dataType: DataTypes.String,
type: 'resource',
},
op: OPERATORS['='],
value: resourceValue,
};
})
);
};
export const isServiceOrEnvironmentAttribute = (key: string): boolean =>
SERVICE_AND_ENVIRONMENT_KEYS.includes(key);

View File

@@ -1,6 +1,7 @@
import { useTranslation } from 'react-i18next';
import { Form } from 'antd';
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
import SemconvEditorWarning from 'components/Semconv/SemconvEditorWarning';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import isEqual from 'lodash-es/isEqual';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
@@ -57,6 +58,7 @@ function TagFilterInputWithLogsResultPreview({
value={value}
onChange={onChange}
/>
<SemconvEditorWarning value={value} editor="Pipeline filter" />
<div className="pipeline-filter-input-preview-container">
<LogsFilterPreview filter={value} />
</div>

View File

@@ -2,6 +2,7 @@ import { ChangeEvent, useCallback } from 'react';
import MEditor, { Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Input } from 'antd';
import SemconvEditorWarning from 'components/Semconv/SemconvEditorWarning';
import { LEGEND } from 'constants/global';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useIsDarkMode } from 'hooks/useDarkMode';
@@ -118,6 +119,7 @@ function ClickHouseQueryBuilder({
theme={isDarkMode ? 'my-theme' : 'light'}
beforeMount={setEditorTheme}
/>
<SemconvEditorWarning value={queryData?.query} editor="ClickHouse SQL" />
<Input
onChange={handleUpdateInput}
name="legend"

View File

@@ -1,6 +1,7 @@
import { ChangeEvent, useCallback } from 'react';
import { Input } from 'antd';
import { LEGEND } from 'constants/global';
import SemconvEditorWarning from 'components/Semconv/SemconvEditorWarning';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { IPromQLQuery } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
@@ -68,6 +69,7 @@ function PromQLQueryBuilder({
style={{ marginBottom: '0.5rem' }}
data-testid="promql-query-input"
/>
<SemconvEditorWarning value={queryData?.query} editor="PromQL" />
<Input
onChange={handleUpdateQuery}

View File

@@ -18,7 +18,6 @@ import 'lib/monaco/loader';
import './ReactI18';
import 'styles.scss';
import 'lib/uPlotStylesheet';
installTranslationResilience();
configureOverlayScrollbars();

View File

@@ -1,7 +0,0 @@
import href from 'uplot/dist/uPlot.min.css?url';
// Appended to the end of <body> so uPlot's rules win ties over the app's stylesheets.
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.body.appendChild(link);

View File

@@ -293,6 +293,15 @@ export const handlers = [
rest.delete('http://localhost/api/v2/rules/:id', (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success' })),
),
rest.get('http://localhost/api/v1/fields/semconv-migration', (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: { startUnixMilli: 0, endUnixMilli: 0, entries: [] },
}),
),
),
rest.get('http://localhost/locales/en/translation.json', (_, res, ctx) =>
res(ctx.status(200), ctx.json(enTranslation)),
),

View File

@@ -14,6 +14,8 @@ import {
openAIQueryBuilder,
openClickHouseQuery,
writeClickHouseQuery,
writeClickHouseQueryWithOldName,
writePromQLQueryWithOldName,
openPanelTypeSwitcher,
openPromQLQuery,
pickHeatmapTracesField,
@@ -65,11 +67,24 @@ export const ClickHouseQueryWritten: Story = {
play: writeClickHouseQuery,
};
/**
* A ClickHouse query that reads an attribute by its old name: the tab names the
* attribute that replaced it and keeps the query as written.
*/
export const ClickHouseQueryOldName: Story = {
play: writeClickHouseQueryWithOldName,
};
/** The PromQL query tab, its query and legend fields empty. */
export const PromQLQuery: Story = {
play: openPromQLQuery,
};
/** A PromQL query that matches on an old attribute name, with the same warning. */
export const PromQLQueryOldName: Story = {
play: writePromQLQueryWithOldName,
};
/** The create route, seeding an unsaved panel of the chosen kind. */
export const NewPanel: Story = {
args: { panel: 'new' },

View File

@@ -183,6 +183,34 @@ export const writeClickHouseQuery = async (
blurActiveElement();
};
const CLICKHOUSE_SQL_OLD_NAME = `SELECT
toStartOfInterval(timestamp, INTERVAL 1 MINUTE) AS ts,
resources_string['deployment.environment'] AS environment,
count() AS value
FROM signoz_traces.distributed_signoz_index_v3
WHERE timestamp BETWEEN {{.start_datetime}} AND {{.end_datetime}}
GROUP BY ts, environment
ORDER BY ts`;
export const writeClickHouseQueryWithOldName = async (
context: PlayContext,
): Promise<void> => {
if (!hasClickHouseTab(context.args)) {
return;
}
await openClickHouseQuery(context);
// The editor paints before it listens for changes, and an edit made in
// between never reaches the query. Write again until the page has it.
await waitFor(async () => {
await setMonacoText('sql', '');
await setMonacoText('sql', CLICKHOUSE_SQL_OLD_NAME);
await expect(screen.getByTestId('semconv-editor-warning')).toBeVisible();
}, EDITOR_LOAD);
await findMonacoEditor(document, 'deployment.environment');
blurActiveElement();
};
export const openPromQLQuery = async ({
canvasElement,
args,
@@ -201,6 +229,23 @@ export const openPromQLQuery = async ({
});
};
const PROMQL_OLD_NAME =
'sum(rate(http_server_request_duration_seconds_count{"deployment.environment"="production"}[5m]))';
export const writePromQLQueryWithOldName = async (
context: PlayContext,
): Promise<void> => {
if (!hasPromQLTab(context.args)) {
return;
}
await openPromQLQuery(context);
await userEvent.click(screen.getByTestId('promql-query-input'));
await userEvent.paste(PROMQL_OLD_NAME);
await screen.findByTestId('semconv-editor-warning', undefined, EDITOR_LOAD);
blurActiveElement();
};
export const enterInvalidDisconnectThreshold = async ({
args,
}: PlayContext): Promise<void> => {

View File

@@ -11,6 +11,7 @@ import {
openChangeHistory,
openEditMode,
openEditPipeline,
openEditPipelineWithOldName,
openPreviewLogDetails,
openProcessingPreview,
openSeverityParserProcessor,
@@ -86,6 +87,15 @@ export const EditPipeline: Story = {
play: openEditPipeline,
};
/**
* A pipeline whose filter reads an attribute by its old name: the form names
* the attribute that replaced it.
*/
export const EditPipelineOldName: Story = {
args: { pipelines: 5 },
play: openEditPipelineWithOldName,
};
/** Adding an operator to a pipeline: the type decides the rest of the form. */
export const AddProcessor: Story = {
play: openAddProcessor,

View File

@@ -10,6 +10,7 @@ import { hoverTruncatableText } from '@/storybook/play/truncatedText';
import { LONG_HTTP_ROUTE } from '../../../stories/__story_mockdata__/logs';
import type { PipelinesArgs } from '../Pipelines.stories.mocks';
import { OLD_NAME_PIPELINE } from './pipelines';
interface PlayContext {
canvasElement: HTMLElement;
@@ -197,6 +198,24 @@ export const openEditPipeline = async ({
await screen.findByText(/edit pipeline/i);
};
export const openEditPipelineWithOldName = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args) || args.pipelines <= OLD_NAME_PIPELINE) {
return;
}
await enterEditMode(canvasElement);
const editActions = await within(canvasElement).findAllByTestId(
'pipeline-edit-action',
undefined,
untilLoaded,
);
await userEvent.click(editActions[OLD_NAME_PIPELINE]);
await screen.findByTestId('semconv-editor-warning');
};
export const openAddProcessor = async ({
canvasElement,
args,

View File

@@ -146,6 +146,13 @@ const PIPELINES: PipelineSeed[] = [
export const PIPELINE_MAX = PIPELINES.length;
/** The pipeline whose filter reads an attribute by a name OpenTelemetry has renamed. */
export const OLD_NAME_PIPELINE = PIPELINES.findIndex((pipeline) =>
pipeline.filter.items.some(
(item) => item.key?.key === 'deployment.environment',
),
);
export const VERSION_MAX = 6;
export interface PipelinesOptions {

View File

@@ -30,10 +30,13 @@ import {
legacyIngestionResponse,
LIMIT_SIGNALS,
type LimitSignal,
MIGRATION_ENTRY_MAX,
semconvMigrationReportResponse,
} from './__story_mockdata__/ingestion';
const KEYS = 'Ingestion · keys';
const LIMITS = 'Ingestion · limits';
const MIGRATION = 'Ingestion · migration';
const rejectCreate: MockResolver = (_req, res, ctx) =>
res(ctx.status(409), ctx.json(ingestionKeyCreateError()));
@@ -75,6 +78,13 @@ export const ingestionMocks = defineStoryMocks({
options: LIMIT_SIGNALS,
value: ['logs', 'traces'],
}),
oldNameEntries: countControl('Old-name report entries', {
group: MIGRATION,
description:
'Rows of the semantic convention migration report: one for each old attribute name and signal that some service still sends on its own. At 0 the report says there is nothing to migrate.',
value: MIGRATION_ENTRY_MAX,
max: MIGRATION_ENTRY_MAX,
}),
},
handlers: (values, response) => [
rest.get(
@@ -142,6 +152,11 @@ export const ingestionMocks = defineStoryMocks({
'http://localhost/api/v1/settings/ingestion_key',
response.json(() => legacyIngestionResponse()),
),
rest.get(
'http://localhost/api/v1/fields/semconv-migration',
response.json(() => semconvMigrationReportResponse(values.oldNameEntries)),
),
],
config: ({ gateway }) => ({
route: ROUTES.INGESTION_SETTINGS,

View File

@@ -24,7 +24,8 @@ const pageStory = storyMocks(ingestionMocks, { layout: 'app' });
/**
* Ingestion keys, their expiry and their per signal limits, against the gateway
* that owns them. Every action on it is gated on an `ingestion-key` or
* that owns them, and under them the services that still send an old semantic
* convention name. Every action on a key is gated on an `ingestion-key` or
* `ingestion-limit` permission, one story per permission under `Ingestion/Authz`.
*
* Route: `/settings/ingestion-settings`.

View File

@@ -3,12 +3,16 @@
* Do not hand-edit: regenerate instead.
*/
import type {
GatewaytypesIngestionKeyDTO,
GatewaytypesLimitDTO,
GetIngestionKeys200,
RenderErrorResponseDTO,
import {
type GatewaytypesIngestionKeyDTO,
type GatewaytypesLimitDTO,
type GetIngestionKeys200,
type GetSemconvMigrationReport200,
type RenderErrorResponseDTO,
type TelemetrytypesSemconvMigrationReportEntryDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SEMCONV_FAMILIES } from 'constants/generated/semconvFamilies.gen';
import type { IngestionInfo } from 'types/api/settings/ingestion';
/** `per_page` the page asks for, so a longer page is a body the gateway never sends. */
@@ -152,3 +156,43 @@ export const legacyIngestionResponse = (): IngestionInfo[] => [
dataRegion: 'us-east-1',
},
];
const OLD_NAME_SERVICES = ['checkout', 'cart', 'payments'];
/**
* The report reads metadata that holds traces and logs rows, so an old
* attribute name is listed for those two signals at most.
*/
const MIGRATION_ENTRIES: TelemetrytypesSemconvMigrationReportEntryDTO[] =
SEMCONV_FAMILIES.filter((family) => family.kind === 'attribute').flatMap(
(family) =>
family.members.flatMap((member) =>
[TelemetrytypesSignalDTO.traces, TelemetrytypesSignalDTO.logs]
.filter((signal) =>
[family.signals, member.signals].every(
(scope) => scope.length === 0 || scope.includes(signal),
),
)
.map((signal, index) => ({
current: family.current,
old: member.name,
signal,
services: OLD_NAME_SERVICES.slice(index),
resourceSets: 12 - index * 5,
lastSeenUnixMilli: CREATED_AT - index * 6 * 3600_000,
})),
),
);
export const MIGRATION_ENTRY_MAX = MIGRATION_ENTRIES.length;
export const semconvMigrationReportResponse = (
entries: number,
): GetSemconvMigrationReport200 => ({
status: 'success',
data: {
startUnixMilli: CREATED_AT - DAY,
endUnixMilli: CREATED_AT,
entries: MIGRATION_ENTRIES.slice(0, entries),
},
});

View File

@@ -7,6 +7,7 @@ import cx from 'classnames';
import { DetailsHeader, DetailsPanelDrawer } from 'components/DetailsPanel';
import { HeaderAction } from 'components/DetailsPanel/DetailsHeader/DetailsHeader';
import { DetailsPanelState } from 'components/DetailsPanel/types';
import { renderOldNameBadge } from 'components/Semconv/renderOldNameBadge';
import { QueryParams } from 'constants/query';
import {
initialQueryBuilderFormValuesMap,
@@ -335,6 +336,7 @@ function SpanDetailsContent({
visibleActions: VISIBLE_ACTIONS,
pinnedFieldsValue,
onPinnedFieldsChange,
labelSuffixRenderer: renderOldNameBadge,
}}
/>
</>

View File

@@ -238,6 +238,22 @@
padding-left: 6px !important;
}
&__label {
display: inline-flex;
align-items: baseline;
gap: var(--spacing-3);
}
// A key with a suffix can fill most of a narrow row. Its value then moves
// to the next line instead of wrapping in the few pixels that are left.
&__row:has(> label &__label) {
flex-wrap: wrap;
> span {
min-width: 40%;
}
}
&__pinned-icon {
flex-shrink: 0;
color: var(--text-robin-400);

View File

@@ -68,6 +68,14 @@ export interface PrettyViewProps {
value: unknown,
keyPath: readonly (string | number)[],
) => React.ReactNode | undefined;
/**
* Optional node rendered after the key of a row. It receives the path of
* the key from the root of `data`, e.g. `['resource', 'service.name']`.
* Return `null` to leave the row as it is.
*/
labelSuffixRenderer?: (
fieldKeyPath: readonly (string | number)[],
) => React.ReactNode;
}
function PrettyView({
@@ -80,6 +88,7 @@ function PrettyView({
pinnedFieldsValue,
onPinnedFieldsChange,
renderLeafValue,
labelSuffixRenderer,
}: PrettyViewProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const [, setCopy] = useCopyToClipboard();
@@ -310,8 +319,15 @@ function PrettyView({
(keyPath: KeyPath): React.ReactNode => {
const displayKey = String(keyPath[0]);
const entry = pinnedEntries.find((e) => e.displayKey === displayKey);
const suffix = entry && labelSuffixRenderer?.(entry.forwardPath);
return (
<span className="pretty-view__pinned-label">
<span
className={
suffix
? 'pretty-view__pinned-label pretty-view__label'
: 'pretty-view__pinned-label'
}
>
<Pin
size={12}
className="pretty-view__pinned-icon"
@@ -322,10 +338,29 @@ function PrettyView({
}}
/>
<span>{displayKey}</span>
{suffix}
</span>
);
},
[togglePin, pinnedEntries],
[togglePin, pinnedEntries, labelSuffixRenderer],
);
// A row without a suffix keeps the markup of react-json-tree's own label.
const labelRenderer = useCallback(
(keyPath: KeyPath): React.ReactNode => {
const label = <span>{`${keyPath[0]}:`}</span>;
const suffix = labelSuffixRenderer?.(keyPathToForward(keyPath));
if (!suffix) {
return label;
}
return (
<span className="pretty-view__label">
{label}
{suffix}
</span>
);
},
[labelSuffixRenderer],
);
return (
@@ -370,6 +405,7 @@ function PrettyView({
shouldExpandNodeInitially={shouldExpandNodeInitially}
valueRenderer={valueRenderer}
getItemString={getItemString}
labelRenderer={labelSuffixRenderer ? labelRenderer : undefined}
/>
</div>
);

View File

@@ -1,3 +1,4 @@
import { ReactNode } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import PrettyView from '../PrettyView';
@@ -28,4 +29,42 @@ describe('PrettyView', () => {
expect(screen.getByText(/checkout/)).toBeInTheDocument();
});
it('renders the label suffix after the key whose path it accepts', () => {
render(
<PrettyView
data={{ resource: { 'service.name': 'checkout', 'host.name': 'h1' } }}
searchable={false}
labelSuffixRenderer={renderServiceNameSuffix}
/>,
);
expect(screen.getByTestId('label-suffix')).toHaveTextContent(
'resource/service.name',
);
});
it('gives a pinned row the path of the key it was pinned from', () => {
render(
<PrettyView
data={{ resource: { 'service.name': 'checkout' } }}
searchable={false}
showPinned
pinnedFieldsValue={['["resource","service.name"]']}
labelSuffixRenderer={renderServiceNameSuffix}
/>,
);
expect(screen.getAllByTestId('label-suffix')).toHaveLength(2);
});
});
function renderServiceNameSuffix(
fieldKeyPath: readonly (string | number)[],
): ReactNode {
const path = fieldKeyPath.join('/');
if (path !== 'resource/service.name') {
return null;
}
return <span data-testid="label-suffix">{path}</span>;
}

View File

@@ -0,0 +1,29 @@
import { findOldSemconvNames, getSemconvRename } from 'utils/semconv';
describe('semantic convention helpers', () => {
it('returns the current name for an old attribute', () => {
expect(getSemconvRename('deployment.environment')).toMatchObject({
old: 'deployment.environment',
current: 'deployment.environment.name',
});
});
it('finds old names in editor text without matching larger custom names', () => {
expect(
findOldSemconvNames(
"deployment.environment = 'prod' AND custom.db.system.value = 'x'",
),
).toStrictEqual([
expect.objectContaining({
old: 'deployment.environment',
current: 'deployment.environment.name',
}),
]);
});
it('does not warn for current names', () => {
expect(
findOldSemconvNames('deployment.environment.name = prod'),
).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,54 @@
import {
SEMCONV_FAMILIES,
SemconvFamily,
} from 'constants/generated/semconvFamilies.gen';
export type SemconvRename = {
old: string;
current: string;
family: SemconvFamily;
};
const OLD_NAMES = SEMCONV_FAMILIES.flatMap((family) =>
family.members.map((member) => ({
old: member.name,
current: family.current,
family,
})),
);
const OLD_NAME_INDEX = new Map(OLD_NAMES.map((rename) => [rename.old, rename]));
export function getSemconvRename(name: string): SemconvRename | undefined {
return OLD_NAME_INDEX.get(name);
}
export function findOldSemconvNames(text: string): SemconvRename[] {
if (!text) {
return [];
}
return OLD_NAMES.filter(({ old }) => containsSemconvName(text, old));
}
function containsSemconvName(text: string, name: string): boolean {
let offset = 0;
while (offset < text.length) {
const index = text.indexOf(name, offset);
if (index === -1) {
return false;
}
const before = index === 0 ? '' : text[index - 1];
const afterIndex = index + name.length;
const after = afterIndex === text.length ? '' : text[afterIndex];
if (!isSemconvNameCharacter(before) && !isSemconvNameCharacter(after)) {
return true;
}
offset = index + 1;
}
return false;
}
function isSemconvNameCharacter(value: string): boolean {
return /[A-Za-z0-9_.-]/.test(value);
}

View File

@@ -46,5 +46,23 @@ func (provider *provider) addFieldsRoutes(router *mux.Router) error {
return err
}
if err := router.Handle("/api/v1/fields/semconv-migration", handler.New(provider.authzMiddleware.ViewAccess(provider.fieldsHandler.GetSemconvMigrationReport), handler.OpenAPIDef{
ID: "GetSemconvMigrationReport",
Tags: []string{"fields"},
Summary: "Get semantic-convention migration report",
Description: "Returns services that still emit old semantic-convention names without the current family name",
Request: nil,
RequestQuery: new(telemetrytypes.PostableSemconvMigrationReportParams),
RequestContentType: "",
Response: new(telemetrytypes.GettableSemconvMigrationReport),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
})).Methods(http.MethodGet).GetError(); err != nil {
return err
}
return nil
}

View File

@@ -8,4 +8,7 @@ type Handler interface {
// Gets the fields values for the given field value selector
GetFieldsValues(http.ResponseWriter, *http.Request)
// Gets services that still emit only historical semantic-convention names.
GetSemconvMigrationReport(http.ResponseWriter, *http.Request)
}

View File

@@ -2,6 +2,7 @@ package implfields
import (
"net/http"
"time"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/http/binding"
@@ -16,6 +17,43 @@ type handler struct {
telemetryMetadataStore telemetrytypes.MetadataStore
}
func (handler *handler) GetSemconvMigrationReport(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
var params telemetrytypes.PostableSemconvMigrationReportParams
if err := binding.Query.BindQuery(req.URL.Query(), &params); err != nil {
render.Error(rw, err)
return
}
now := time.Now()
if params.EndUnixMilli == 0 {
params.EndUnixMilli = now.UnixMilli()
}
if params.StartUnixMilli == 0 {
params.StartUnixMilli = now.Add(-24 * time.Hour).UnixMilli()
}
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
report, err := handler.telemetryMetadataStore.GetSemconvMigrationReport(
ctx,
valuer.MustNewUUID(claims.OrgID),
params.StartUnixMilli,
params.EndUnixMilli,
)
if err != nil {
render.Error(rw, err)
return
}
render.Success(rw, http.StatusOK, report)
}
func NewHandler(settings factory.ProviderSettings, telemetryMetadataStore telemetrytypes.MetadataStore) fields.Handler {
return &handler{
telemetryMetadataStore: telemetryMetadataStore,

View File

@@ -115,6 +115,13 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
// UnmarshalJSON, so normalise here too.
req.Start = qbtypes.ToMilliSecs(req.Start)
req.End = qbtypes.ToMilliSecs(req.End)
// Key resolution rewrites parts of the builder queries, so the caller's
// spelling is read before that. With the flag off no key resolves, so
// the response reports nothing.
var semconvResolutions []qbtypes.SemconvResolution
if querybuilder.SemconvFamiliesEnabled(ctx, orgID, q.fl) {
semconvResolutions = semconvResolutionsForRequest(req)
}
event := &qbtypes.QBEvent{
Version: "v5",
@@ -163,6 +170,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
qbResp, qbErr := q.run(ctx, orgID, queries, req, steps, event, preseededResults)
if qbResp != nil {
qbResp.QBEvent = event
qbResp.Meta.SemconvResolutions = semconvResolutions
if len(intervalWarnings) != 0 && req.RequestType == qbtypes.RequestTypeTimeSeries {
if qbResp.Warning == nil {
qbResp.Warning = &qbtypes.QueryWarnData{

View File

@@ -0,0 +1,131 @@
package querier
import (
"encoding/json"
"strings"
"unicode"
"github.com/SigNoz/signoz/pkg/querybuilder"
"github.com/SigNoz/signoz/pkg/semconv"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
// semconvResolutionsForRequest reports the family spellings a query builder
// request names. Raw ClickHouse SQL and PromQL are not rewritten, so they
// report nothing.
func semconvResolutionsForRequest(req *qbtypes.QueryRangeRequest) []qbtypes.SemconvResolution {
if req == nil {
return nil
}
resolutions := make([]qbtypes.SemconvResolution, 0)
seen := make(map[string]struct{})
for _, envelope := range req.CompositeQuery.Queries {
signal, metric, applies := semconvResolutionSignal(envelope.Spec)
if !applies {
continue
}
payload, err := json.Marshal(envelope.Spec)
if err != nil {
continue
}
text := string(payload)
for family := range semconv.All() {
if family.Kind() == semconv.KindMetric && signal != telemetrytypes.SignalMetrics {
continue
}
selector := telemetrytypes.FieldKeySelector{Name: family.Current(), Signal: signal, MetricContext: metric}
spellings := semconv.Members(family.Kind(), selector)
if family.Kind() == semconv.KindAttribute && signal == telemetrytypes.SignalMetrics {
spellings = querybuilder.MetricLabelSpellings(selector)
}
if len(spellings) <= 1 {
continue
}
for _, requested := range spellings {
if !containsSemconvName(text, requested) {
continue
}
identity := family.Kind().StringValue() + "\x00" + requested + "\x00" + family.Current()
if _, ok := seen[identity]; ok {
continue
}
seen[identity] = struct{}{}
resolutions = append(resolutions, qbtypes.SemconvResolution{
Requested: requested,
Current: family.Current(),
Members: append([]string{family.Current()}, family.Old()...),
Kind: family.Kind().StringValue(),
})
}
}
}
if len(resolutions) == 0 {
return nil
}
return resolutions
}
func semconvResolutionSignal(spec any) (telemetrytypes.Signal, *telemetrytypes.MetricContext, bool) {
switch query := spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation], qbtypes.QueryBuilderTraceOperator:
return telemetrytypes.SignalTraces, nil, true
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
return telemetrytypes.SignalLogs, nil, true
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
var metric *telemetrytypes.MetricContext
if len(query.Aggregations) > 0 {
metric = &telemetrytypes.MetricContext{MetricName: query.Aggregations[0].MetricName}
}
return telemetrytypes.SignalMetrics, metric, true
case qbtypes.QueryBuilderJoin:
// A join can hold several signals. The unspecified signal keeps the
// family signal gates in force and admits every applicable family.
return telemetrytypes.SignalUnspecified, nil, true
default:
return telemetrytypes.SignalUnspecified, nil, false
}
}
// containsSemconvName reports whether name occurs in text as a whole key. A
// field context prefix counts as a boundary, so `resource.x` names `x`.
func containsSemconvName(text, name string) bool {
for offset := 0; offset < len(text); {
index := strings.Index(text[offset:], name)
if index < 0 {
return false
}
start := offset + index
end := start + len(name)
if hasSemconvNameStartBoundary(text, start) &&
(end == len(text) || !isSemconvNameRune(rune(text[end]))) {
return true
}
offset = start + 1
}
return false
}
func hasSemconvNameStartBoundary(text string, start int) bool {
if start == 0 || !isSemconvNameRune(rune(text[start-1])) {
return true
}
for _, qualifier := range []string{"resource.", "attribute.", "tag.", "point."} {
qualifierStart := start - len(qualifier)
if qualifierStart >= 0 && text[qualifierStart:start] == qualifier &&
(qualifierStart == 0 || !isSemconvNameRune(rune(text[qualifierStart-1]))) {
return true
}
}
return false
}
func isSemconvNameRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.' || r == '-'
}

View File

@@ -0,0 +1,118 @@
package querier
import (
"encoding/json"
"testing"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSemconvResolutionsReportsOldTraceAttribute(t *testing.T) {
req := &qbtypes.QueryRangeRequest{
CompositeQuery: qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{{
Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
Signal: telemetrytypes.SignalTraces,
Filter: &qbtypes.Filter{Expression: "deployment.environment = 'prod'"},
},
}}},
}
assert.Equal(t, []qbtypes.SemconvResolution{{
Requested: "deployment.environment",
Current: "deployment.environment.name",
Members: []string{"deployment.environment.name", "deployment.environment"},
Kind: "attribute",
}}, semconvResolutionsForRequest(req), "old trace attribute should be reported as a family resolution")
}
func TestSemconvResolutionsReportsContextQualifiedOldAttribute(t *testing.T) {
var req qbtypes.QueryRangeRequest
err := json.Unmarshal([]byte(`{
"start": 1,
"end": 2,
"requestType": "raw",
"compositeQuery": {
"queries": [{
"type": "builder_query",
"spec": {
"signal": "traces",
"name": "A",
"filter": {"expression": "resource.deployment.environment EXISTS"}
}
}]
}
}`), &req)
require.NoError(t, err)
assert.Equal(t, []qbtypes.SemconvResolution{{
Requested: "deployment.environment",
Current: "deployment.environment.name",
Members: []string{"deployment.environment.name", "deployment.environment"},
Kind: "attribute",
}}, semconvResolutionsForRequest(&req), "qualified old trace attribute should be reported after request decoding")
}
func TestSemconvResolutionsReportsCurrentLogAttribute(t *testing.T) {
req := &qbtypes.QueryRangeRequest{
CompositeQuery: qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{{
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
Signal: telemetrytypes.SignalLogs,
SelectFields: []telemetrytypes.TelemetryFieldKey{{
Name: "deployment.environment.name",
}},
},
}}},
}
assert.Equal(t, []qbtypes.SemconvResolution{{
Requested: "deployment.environment.name",
Current: "deployment.environment.name",
Members: []string{"deployment.environment.name", "deployment.environment"},
Kind: "attribute",
}}, semconvResolutionsForRequest(req), "current log attribute should identify its complete family")
}
func TestSemconvResolutionsReportsSpanMetricResourceLabel(t *testing.T) {
req := &qbtypes.QueryRangeRequest{
CompositeQuery: qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{{
Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{
Signal: telemetrytypes.SignalMetrics,
Aggregations: []qbtypes.MetricAggregation{{MetricName: "signoz_calls_total"}},
Filter: &qbtypes.Filter{Expression: "resource_deployment.environment = 'prod'"},
},
}}},
}
assert.Equal(t, []qbtypes.SemconvResolution{{
Requested: "resource_deployment.environment",
Current: "deployment.environment.name",
Members: []string{"deployment.environment.name", "deployment.environment"},
Kind: "attribute",
}}, semconvResolutionsForRequest(req), "a span-metrics resource label is reported under its stored spelling")
}
func TestSemconvResolutionsIgnoresRawSQL(t *testing.T) {
req := &qbtypes.QueryRangeRequest{
CompositeQuery: qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{{
Spec: qbtypes.ClickHouseQuery{Query: "SELECT attributes_string['deployment.environment']"},
}}},
}
assert.Empty(t, semconvResolutionsForRequest(req), "raw SQL is not rewritten and should not report a resolution")
}
func TestSemconvResolutionsRequiresNameBoundary(t *testing.T) {
req := &qbtypes.QueryRangeRequest{
CompositeQuery: qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{{
Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
Signal: telemetrytypes.SignalTraces,
Filter: &qbtypes.Filter{Expression: "custom.deployment.environment = 'prod'"},
},
}}},
}
assert.Empty(t, semconvResolutionsForRequest(req), "a family name embedded in a larger custom key must not match")
}

View File

@@ -0,0 +1,149 @@
package telemetrymetadata
import (
"context"
"fmt"
"slices"
"strings"
"github.com/huandu/go-sqlbuilder"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/semconv"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
type semconvMigrationRow struct {
current string
old string
signal string
service string
resourceSets uint64
lastSeenUnixMilli int64
}
// GetSemconvMigrationReport lists the services whose metadata carries an old
// family spelling and no current one. It reads attributes_metadata, a
// deduplicated set of resource and attribute fingerprints, not the raw
// telemetry tables.
func (t *telemetryMetaStore) GetSemconvMigrationReport(
ctx context.Context,
_ valuer.UUID,
startUnixMilli, endUnixMilli int64,
) (*telemetrytypes.GettableSemconvMigrationReport, error) {
query, args := t.semconvMigrationReportQuery(startUnixMilli, endUnixMilli)
report := &telemetrytypes.GettableSemconvMigrationReport{
StartUnixMilli: startUnixMilli,
EndUnixMilli: endUnixMilli,
Entries: []*telemetrytypes.SemconvMigrationReportEntry{},
}
if query == "" {
return report, nil
}
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
if err != nil {
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, "failed to build semantic-convention migration report")
}
defer rows.Close()
grouped := make(map[string]*telemetrytypes.SemconvMigrationReportEntry)
serviceSets := make(map[string]map[string]struct{})
for rows.Next() {
var row semconvMigrationRow
if err := rows.Scan(&row.current, &row.old, &row.signal, &row.service, &row.resourceSets, &row.lastSeenUnixMilli); err != nil {
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, "failed to scan semantic-convention migration report")
}
identity := row.current + "\x00" + row.old + "\x00" + row.signal
entry, ok := grouped[identity]
if !ok {
signal, _ := telemetrytypes.SignalFromText(row.signal)
entry = &telemetrytypes.SemconvMigrationReportEntry{
Current: row.current,
Old: row.old,
Signal: signal,
Services: []string{},
}
grouped[identity] = entry
serviceSets[identity] = make(map[string]struct{})
report.Entries = append(report.Entries, entry)
}
serviceSets[identity][row.service] = struct{}{}
entry.ResourceSets += row.resourceSets
entry.LastSeenUnixMilli = max(entry.LastSeenUnixMilli, row.lastSeenUnixMilli)
}
if err := rows.Err(); err != nil {
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, "failed to read semantic-convention migration report")
}
for identity, entry := range grouped {
for service := range serviceSets[identity] {
entry.Services = append(entry.Services, service)
}
slices.Sort(entry.Services)
}
slices.SortFunc(report.Entries, func(a, b *telemetrytypes.SemconvMigrationReportEntry) int {
return strings.Compare(a.Current+"\x00"+a.Old+"\x00"+a.Signal.StringValue(), b.Current+"\x00"+b.Old+"\x00"+b.Signal.StringValue())
})
return report, nil
}
func (t *telemetryMetaStore) semconvMigrationReportQuery(startUnixMilli, endUnixMilli int64) (string, []any) {
builders := make([]sqlbuilder.Builder, 0)
for family := range semconv.All() {
if family.Kind() != semconv.KindAttribute {
continue
}
for _, old := range family.Old() {
signals := semconvFamilySignals(family.Current(), old)
if len(signals) == 0 {
continue
}
sb := sqlbuilder.NewSelectBuilder()
sb.Select(
fmt.Sprintf("%s AS current_name", sb.Var(family.Current())),
fmt.Sprintf("%s AS old_name", sb.Var(old)),
"data_source",
"if(empty(resource_attributes['service.name']), '<unknown>', resource_attributes['service.name']) AS service_name",
"uniqExact(tuple(resource_fingerprint, attrs_fingerprint)) AS resource_sets",
"toInt64(max(unix_milli)) AS last_seen_unix_milli",
)
sb.From(t.relatedMetadataDBName + "." + t.relatedMetadataTblName)
sb.Where(sb.GE("unix_milli", startUnixMilli))
sb.Where(sb.LE("unix_milli", endUnixMilli))
sb.Where(sb.In("data_source", signals...))
sb.Where(sb.Or(semconvMetadataPresenceConditions(sb, old)...))
sb.Where(fmt.Sprintf("NOT (%s)", sb.Or(semconvMetadataPresenceConditions(sb, family.Current())...)))
sb.GroupBy("data_source", "service_name")
builders = append(builders, sb)
}
}
if len(builders) == 0 {
return "", nil
}
return sqlbuilder.UnionAll(builders...).BuildWithFlavor(sqlbuilder.ClickHouse)
}
// semconvFamilySignals lists the signals under which old resolves to
// current. The metadata table holds traces and logs rows.
func semconvFamilySignals(current, old string) []any {
signals := make([]any, 0, 2)
for _, signal := range []telemetrytypes.Signal{telemetrytypes.SignalTraces, telemetrytypes.SignalLogs} {
members := semconv.Members(semconv.KindAttribute, telemetrytypes.FieldKeySelector{Name: old, Signal: signal})
if slices.Contains(members, current) {
signals = append(signals, signal.StringValue())
}
}
return signals
}
func semconvMetadataPresenceConditions(sb *sqlbuilder.SelectBuilder, name string) []string {
return []string{
fmt.Sprintf("mapContains(resource_attributes, %s)", sb.Var(name)),
fmt.Sprintf("mapContains(attributes, %s)", sb.Var(name)),
}
}

View File

@@ -25,10 +25,22 @@ type Result struct {
}
type ExecStats struct {
RowsScanned uint64 `json:"rowsScanned" description:"Rows scanned to answer every query in the request. A cost indicator only: rows are scanned whether or not any matched, so it says nothing about whether data exists."`
BytesScanned uint64 `json:"bytesScanned" description:"Bytes scanned to answer every query in the request. A cost indicator only; it does not indicate whether any data matched."`
DurationMS uint64 `json:"durationMs" description:"Total execution time across the queries in the request, in milliseconds. A cost indicator only, not the request latency and not a sign that data exists."`
StepIntervals map[string]uint64 `json:"stepIntervals,omitempty" description:"The step interval in seconds that was used for each query, keyed by query name."`
RowsScanned uint64 `json:"rowsScanned" description:"Rows scanned to answer every query in the request. A cost indicator only: rows are scanned whether or not any matched, so it says nothing about whether data exists."`
BytesScanned uint64 `json:"bytesScanned" description:"Bytes scanned to answer every query in the request. A cost indicator only; it does not indicate whether any data matched."`
DurationMS uint64 `json:"durationMs" description:"Total execution time across the queries in the request, in milliseconds. A cost indicator only, not the request latency and not a sign that data exists."`
StepIntervals map[string]uint64 `json:"stepIntervals,omitempty" description:"The step interval in seconds that was used for each query, keyed by query name."`
SemconvResolutions []SemconvResolution `json:"semconvResolutions,omitempty" description:"The semantic-convention families that the builder queries in the request resolved. Absent when no query named a family member or when family resolution is off."`
}
// SemconvResolution records a semantic-convention family that the query
// builder resolved. Requested preserves the spelling supplied by the caller so
// agents and editors can update their next query without changing response
// labels in the current response.
type SemconvResolution struct {
Requested string `json:"requested" required:"true" description:"The name as the request spelled it."`
Current string `json:"current" required:"true" description:"The current name of the family."`
Members []string `json:"members" required:"true" nullable:"false" description:"Every name the query read, the current name first."`
Kind string `json:"kind" required:"true" description:"The family kind: attribute or metric."`
}
var _ jsonschema.Preparer = &ExecStats{}

View File

@@ -288,6 +288,28 @@ type GettableFieldValues struct {
Complete bool `json:"complete" required:"true" description:"True when every matching value was returned; false when the result was cut off by limit."`
}
// PostableSemconvMigrationReportParams selects the metadata window used to
// find services that still emit only historical semantic-convention names.
type PostableSemconvMigrationReportParams struct {
StartUnixMilli int64 `query:"startUnixMilli" description:"Start of the lookup window in Unix milliseconds. Omit for 24 hours before the current time."`
EndUnixMilli int64 `query:"endUnixMilli" description:"End of the lookup window in Unix milliseconds. Omit for the current time."`
}
type SemconvMigrationReportEntry struct {
Current string `json:"current" required:"true" description:"The current name of the family."`
Old string `json:"old" required:"true" description:"The old name that the listed services still send."`
Signal Signal `json:"signal" required:"true" description:"The signal the old name was seen in: traces or logs."`
Services []string `json:"services" required:"true" nullable:"false" description:"Services that sent the old name and no current name in the window, sorted by name. A resource without service.name is listed as <unknown>."`
ResourceSets uint64 `json:"resourceSets" required:"true" description:"Number of distinct resource and attribute sets that carry the old name and no current name."`
LastSeenUnixMilli int64 `json:"lastSeenUnixMilli" required:"true" description:"Latest time the metadata recorded such a set, in Unix milliseconds."`
}
type GettableSemconvMigrationReport struct {
StartUnixMilli int64 `json:"startUnixMilli" required:"true" description:"Start of the window the report covers, in Unix milliseconds."`
EndUnixMilli int64 `json:"endUnixMilli" required:"true" description:"End of the window the report covers, in Unix milliseconds."`
Entries []*SemconvMigrationReportEntry `json:"entries" required:"true" nullable:"false" description:"One entry for each family, old name and signal with at least one service that sends only the old name. Empty when there is none."`
}
type PostableFieldValueParams struct {
PostableFieldKeysParams
Name string `query:"name" description:"The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level."`

View File

@@ -30,6 +30,10 @@ type MetadataStore interface {
// GetAllValues returns a list of all values.
GetAllValues(ctx context.Context, orgID valuer.UUID, fieldValueSelector *FieldValueSelector) (*TelemetryFieldValues, bool, error)
// GetSemconvMigrationReport returns services whose metadata contains an old
// semantic-convention name but no current member of that family.
GetSemconvMigrationReport(ctx context.Context, orgID valuer.UUID, startUnixMilli, endUnixMilli int64) (*GettableSemconvMigrationReport, error)
// FetchTemporality fetches the temporality for metric
FetchTemporality(ctx context.Context, orgID valuer.UUID, queryTimeRangeStartTs, queryTimeRangeEndTs uint64, metricName string) (metrictypes.Temporality, error)

View File

@@ -24,7 +24,19 @@ type MockMetadataStore struct {
ColumnEvolutionMetadataMap map[string][]*telemetrytypes.EvolutionEntry
LookupKeysMap map[telemetrytypes.MetricMetadataLookupKey]int64
// StaticFields holds signal-specific intrinsic field definitions (e.g. logstelemetryschema.IntrinsicFields).
StaticFields map[string]telemetrytypes.TelemetryFieldKey
StaticFields map[string]telemetrytypes.TelemetryFieldKey
SemconvMigrationReport *telemetrytypes.GettableSemconvMigrationReport
}
func (m *MockMetadataStore) GetSemconvMigrationReport(_ context.Context, _ valuer.UUID, startUnixMilli, endUnixMilli int64) (*telemetrytypes.GettableSemconvMigrationReport, error) {
if m.SemconvMigrationReport != nil {
return m.SemconvMigrationReport, nil
}
return &telemetrytypes.GettableSemconvMigrationReport{
StartUnixMilli: startUnixMilli,
EndUnixMilli: endUnixMilli,
Entries: []*telemetrytypes.SemconvMigrationReportEntry{},
}, nil
}
// NewMockMetadataStore creates a new instance of MockMetadataStore with initialized maps.

View File

@@ -125,6 +125,15 @@ def get_field_values(signoz: types.SigNoz, token: str, params: dict, path: str =
)
def get_semconv_migration_report(signoz: types.SigNoz, token: str, params: dict) -> requests.Response:
return requests.get(
signoz.self.host_configs["8080"].get("/api/v1/fields/semconv-migration"),
timeout=30,
headers={"authorization": f"Bearer {token}"},
params=params,
)
@pytest.fixture(name="insert_attributes_metadata", scope="function")
def insert_attributes_metadata(
clickhouse: types.TestContainerClickhouse,

View File

@@ -1,12 +1,12 @@
from collections.abc import Callable
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
import pytest
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.metadata import AttributesMetadata, get_field_keys, get_field_values
from fixtures.metadata import AttributesMetadata, get_field_keys, get_field_values, get_semconv_migration_report
from fixtures.querier import (
RequestType,
build_aggregation,
@@ -465,3 +465,94 @@ def test_related_values_search_matches_merged_value(
# The BOTH row reads as staging, so its old production value must not
# satisfy the search.
assert set(response.json()["data"]["values"].get("relatedValues") or []) == {"production"}
def test_response_meta_reports_the_resolved_family(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
family_fleet: datetime,
) -> None:
"""Raw SQL and PromQL are not rewritten, so only a builder query reports."""
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = make_query_request(
signoz,
token,
start_ms=int((family_fleet - timedelta(minutes=2)).timestamp() * 1000),
end_ms=int((family_fleet + timedelta(minutes=1)).timestamp() * 1000),
request_type=RequestType.RAW,
queries=[
build_raw_query(
"A",
"traces",
limit=1,
filter_expression=f"resource.{OLD_KEY} EXISTS",
order=[build_order_by("timestamp", "asc")],
select_fields=[{"name": "span.name"}],
)
],
)
assert response.status_code == HTTPStatus.OK, response.text
assert {
"requested": OLD_KEY,
"current": CURRENT_KEY,
"members": [CURRENT_KEY, OLD_KEY],
"kind": "attribute",
} in response.json()["data"]["meta"]["semconvResolutions"]
def test_response_meta_reports_nothing_with_flag_off(
signoz_families_off: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
family_fleet: datetime,
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = make_query_request(
signoz_families_off,
token,
start_ms=int((family_fleet - timedelta(minutes=2)).timestamp() * 1000),
end_ms=int((family_fleet + timedelta(minutes=1)).timestamp() * 1000),
request_type=RequestType.RAW,
queries=[
build_raw_query(
"A",
"traces",
limit=1,
filter_expression=f"resource.{OLD_KEY} EXISTS",
order=[build_order_by("timestamp", "asc")],
select_fields=[{"name": "span.name"}],
)
],
)
assert response.status_code == HTTPStatus.OK, response.text
assert "semconvResolutions" not in response.json()["data"]["meta"]
def test_migration_report_lists_old_only_services(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_attributes_metadata: Callable[[list[AttributesMetadata]], None],
) -> None:
now = datetime.now(tz=UTC).replace(microsecond=0)
insert_attributes_metadata(
[
AttributesMetadata(data_source="traces", resource_attributes={"service.name": OLD, OLD_KEY: "production"}, timestamp=now),
AttributesMetadata(data_source="traces", resource_attributes={"service.name": NEW, CURRENT_KEY: "production"}, timestamp=now),
AttributesMetadata(data_source="traces", resource_attributes={"service.name": BOTH, CURRENT_KEY: "staging", OLD_KEY: "production"}, timestamp=now),
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = get_semconv_migration_report(
signoz,
token,
{
"startUnixMilli": int((now - timedelta(hours=1)).timestamp() * 1000),
"endUnixMilli": int((now + timedelta(hours=1)).timestamp() * 1000),
},
)
assert response.status_code == HTTPStatus.OK, response.text
entry = next(item for item in response.json()["data"]["entries"] if item["current"] == CURRENT_KEY and item["old"] == OLD_KEY and item["signal"] == "traces")
# NEW carries the current spelling, BOTH carries both. Only OLD is behind.
assert set(entry["services"]) == {OLD}