Compare commits

...

11 Commits

Author SHA1 Message Date
Vinícius Lourenço
49066ad192 test(storybook): cover workspace domain conflict and onboarding facing issues 2026-11-10 18:17:45 -03:00
Vinícius Lourenço
c0d4d22046 test(storybook): cover invite roles and move members plays to a play file 2026-11-10 18:17:41 -03:00
Vinícius Lourenço
141a420509 test(storybook): add changelog modal stories for cloud and self-hosted 2026-11-10 18:17:33 -03:00
Vinícius Lourenço
e487b0e16e test(stories): cover the channel edit form, editable and read-only 2026-11-10 14:37:54 -03:00
Vinícius Lourenço
b32e6689ef test(stories): add K8s drawer depth and pods log details stories 2026-11-09 21:39:13 -03:00
Manika Malhotra
5c067d75fc test(stories): cover the states the component migration changes 2026-11-09 21:39:13 -03:00
Srikanth Chekuri
4b1b3092d5 fix(querier): skip the cache for logs and traces queries with a limited group by (#13472)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- A logs or traces time series query with a group by and a limit ranks
its groups over the statement window. On a partial cache hit the gap
statement ranked over the gap, so the response was a union of the
winners of each piece, each with points for part of the window. A
narrower window served from a wider cached entry got the wider window's
winners.
- No piece of a window can stand in for the window, so such a query is
no longer served from the cache. Its fingerprint is empty, the same way
an AI builder query opts out today. Metrics are not affected, their
limit is applied after the full series set is read.
- Integration tests: a top-2 over a window whose first half is cached
must return the window's two winners with points for the whole window,
and a top-1 over the second half of a cached window must return that
half's winner. Both match the request with noCache.

#### Issues closed by this PR

Closes SigNoz/nerve-pod#627

#### Additional Information

- The first commit adds the tests alone. CI ran them against main and
both failed. The second commit is the fix.
- This is the stop gap. Caching these queries exactly needs the ranking
summary of each piece, top-K totals with a threshold, so the merge can
rank with bounds and fall back when it cannot prove the top-N. That is a
design item, not a cache patch.
2026-11-09 20:33:56 +00:00
Srikanth Chekuri
d6017f88fd fix(querier): do not shift the gap of a timeShift query twice (#13470)
#### Description

- A timeShift query's window is moved into the shifted clock when the
query is built. On a partial cache hit the missing range comes from that
window, and the ranged gap query shifted it again, so the gap was read
one shift too far back, and the wrong points were served and written
back to the cache.
- The ranged query now takes the range as given. The spec copy already
carries the shift, so the gap statement reads the right data and the
postprocess shift moves it forward once.
- Integration test: a timeShift(3600) logs query with its first 30
minutes cached must return the same points for the next 20 minutes as
the request with noCache.

#### Issues closed by this PR

Closes SigNoz/nerve-pod#625

#### Additional Information

- The first commit adds the test alone. CI ran it against main and it
failed with only that test failing in the suite. The second commit is
the fix.
2026-11-09 20:33:48 +00:00
Srikanth Chekuri
9d28014664 feat(querier): apply the having of a formula (#13452)
#### Description

The querier computes a formula in Go after its queries return, so a
formula having cannot run as SQL HAVING. It was accepted and ignored.

The having now filters the formula values in Go. It uses the having
grammar, validation, and messages of a builder query, with the formula
name and __result as the only references. A time series keeps the
points that match and drops a series with no points left. A scalar
result keeps the rows that match. The having runs before functions,
order, and limit, as HAVING does in SQL. A bad having fails the
request before any query runs.

#### Issues closed by this PR

Closes SigNoz/nerve-pod#612

#### Additional Information

Assisted-by: Claude Opus 5.5
2026-11-09 20:33:22 +00:00
Srikanth Chekuri
1997901102 fix(querier): validate formula limits, raw order keys, and request types (#13426)
#### Description

- A negative formula `limit` now returns 400, as for builder queries.
Before, validation accepted it, and the series limit treated it as no
limit.
- An empty order key on a `raw`, `raw_stream`, or `trace` request now
returns 400. Before, validation accepted it. Aggregation requests keep
their own order key check, which lists the valid keys.
- A missing `requestType` returned `invalid request type: {}` and
suggested `timeseries`, which the decoder rejects. It now returns
`requestType is required`, with the valid request types as suggestions.
The decoder error for an unknown value lists the same set.
- Validation now accepts exactly what `RequestType.Enum` lists. The
spec, the decoder error, and validation read one list, so they cannot
drift apart.

#### Issues closed by this PR

Closes SigNoz/nerve-pod#609

#### Additional Information

- Existing alerts should not be affected. Stored rules load without
validation, and the querier validates only in the `query_range` handler.
The UI does not send a negative formula limit or an empty order key.
- Part of https://github.com/SigNoz/nerve-pod/issues/428
2026-11-09 20:33:14 +00:00
Srikanth Chekuri
84268d00c8 docs(querier): add query_range examples for every builder function (#13475)
#### Description

- The query_range examples cover signals and request types but none of
the functions a builder query can carry, so a client has no place to
learn the argument shapes.
- Adds one example per function family: timeShift, fillZero, the four
threshold functions, runningDiff, ewma, median, cumulativeSum, log,
anomaly. Each description says what the function does to the series,
which arguments it takes, their units and their defaults.
- A test unmarshals every example into a `QueryRangeRequest` and
validates it, so an example cannot drift from the request type.
- The OpenAPI spec is regenerated in its own commit.
2026-11-09 20:32:41 +00:00
63 changed files with 3224 additions and 508 deletions

View File

@@ -10231,8 +10231,10 @@ components:
having:
allOf:
- $ref: '#/components/schemas/Querybuildertypesv5Having'
description: Accepted but currently ignored; the computed values are returned
unfiltered.
description: A filter on the formula values, referencing the formula by
its name or as __result, for example F1 > 0. A time series keeps only
the points that match and drops a series with none left; a scalar result
keeps only the rows that match.
legend:
description: The display name template for each series; {{field}} placeholders
are replaced by label values.
@@ -32729,6 +32731,305 @@ paths:
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_anomaly_request_rate:
description: 'anomaly is the one function with named arguments. seasonality
says which past periods predict the current value: hourly, daily
or weekly, daily when absent. z_score_threshold is how many standard
deviations from the prediction count as an anomaly. It has no default:
a request without it gets bounds of zero width, so send it. 3 is
the value the UI sends. The response carries, next to the values,
a predicted series, an upper and a lower bound series and an anomaly
score series. The scoring runs in the enterprise build; the community
build returns the series unchanged.'
summary: 'anomaly: request rate scored against its daily pattern'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: http.server.duration.count
spaceAggregation: sum
timeAggregation: rate
functions:
- args:
- name: seasonality
value: daily
- name: z_score_threshold
value: 3
name: anomaly
groupBy:
- fieldContext: resource
name: service.name
name: A
signal: metrics
stepInterval: 300s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_cumulativesum_errors_so_far:
description: cumulativeSum replaces each point with the sum of every
point up to and including it, so a per-step count becomes a running
total whose first point is the first count. It takes no arguments.
The total resets with the window, so a longer time range gives a
larger final value; it is a view of the window, not a counter.
summary: 'cumulativeSum: 5xx responses since the start of the window'
value:
compositeQuery:
queries:
- spec:
aggregations:
- alias: server_errors
expression: count()
filter:
expression: http.response.status_code >= 500
functions:
- name: cumulativeSum
groupBy:
- fieldContext: resource
name: service.name
name: A
signal: traces
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_cutoffmin_hide_idle_hosts:
description: The four threshold functions take one number. cutOffMin
and cutOffMax remove the points below or above the threshold, so
an idle host disappears from the chart instead of drawing a line
along the bottom. clampMin and clampMax keep the points and replace
the value with the threshold, which caps spikes without hiding them.
system.cpu.utilization is a ratio, so 0.05 is 5%.
summary: 'cutOffMin: drop hosts below 5% CPU from the chart'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: system.cpu.utilization
spaceAggregation: avg
timeAggregation: avg
functions:
- args:
- value: 0.05
name: cutOffMin
groupBy:
- fieldContext: resource
name: host.name
name: A
signal: metrics
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_ewma_smoothed_latency:
description: 'ewma3, ewma5 and ewma7 replace each point with an exponentially
weighted average of the point and the points before it. The number
in the name is the window the default weight is derived from: alpha
= 2 / (n + 1), so 0.5, 0.333 and 0.25. One optional argument overrides
alpha; a value close to 1 follows the raw series, a value close
to 0 smooths harder. 0.3 here smooths a little more than ewma5''s
default.'
summary: 'ewma5: smoothed p95 latency'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: http.server.duration.bucket
spaceAggregation: p95
functions:
- args:
- value: 0.3
name: ewma5
groupBy:
- fieldContext: resource
name: service.name
name: A
signal: metrics
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_fillzero_sparse_errors:
description: A count over sparse events returns a point only for steps
that had a match, so a chart of failed spans has gaps where nothing
failed. fillZero adds a zero at every missing step. With no arguments
the server fills the request window at the query's step, which is
the common case. The three optional arguments are start, end and
step in milliseconds, for callers that want to fill a different
grid.
summary: 'fillZero: a zero at every step with no failed spans'
value:
compositeQuery:
queries:
- spec:
aggregations:
- alias: failed_spans
expression: count()
filter:
expression: has_error = true
functions:
- name: fillZero
groupBy:
- fieldContext: resource
name: service.name
name: A
signal: traces
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_log10_network_bytes:
description: log2 and log10 replace each value with its logarithm,
so a loopback device moving kilobytes and an uplink moving gigabytes
fit on one chart. They take no arguments. Zero and negative values
have no logarithm and are not drawn. absolute, also without arguments,
is the usual companion for a signed series before a logarithm.
summary: 'log10: network throughput across devices that differ by
orders of magnitude'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: system.network.io
spaceAggregation: sum
timeAggregation: rate
filter:
expression: direction = 'transmit'
functions:
- name: log10
groupBy:
- fieldContext: attribute
name: device
name: A
signal: metrics
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_median_despiked_request_rate:
description: median3, median5 and median7 replace each point with
the median of the surrounding 3, 5 or 7 points. A spike that lasts
one step vanishes, a shift that lasts longer than half the window
stays. The first and last half window, 2 points each for median5,
have no full window and keep their values, so the newest spike stays
visible; a series shorter than the window is returned unchanged.
They take no arguments. Use them when the raw series is noisy and
the chart is for a trend, not for catching the spike.
summary: 'median5: request rate without one-step spikes'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: http.server.duration.count
spaceAggregation: sum
timeAggregation: rate
functions:
- name: median5
groupBy:
- fieldContext: resource
name: service.name
name: A
signal: metrics
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_runningdiff_disk_growth:
description: 'runningDiff turns a gauge into the change between consecutive
points, so a filesystem usage gauge becomes bytes written per step.
It takes no arguments and drops the first point of the window, since
that point has nothing to difference against; the server reads one
step before the window to keep the first interval. Functions apply
in order: clampMin with 0 runs on the differences and replaces the
negative value a cleanup or a volume reset produces with zero.'
summary: 'runningDiff then clampMin: bytes written to disk per step'
value:
compositeQuery:
queries:
- spec:
aggregations:
- metricName: system.filesystem.usage
spaceAggregation: sum
timeAggregation: latest
filter:
expression: state = 'used'
functions:
- name: runningDiff
- args:
- value: 0
name: clampMin
groupBy:
- fieldContext: resource
name: host.name
name: A
signal: metrics
stepInterval: 60s
type: builder_query
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
function_timeshift_week_over_week:
description: timeShift moves every point of its query forward by the
argument, in seconds, so a series read from the past lands on the
current timestamps. B here reads the hour exactly seven days (604800
s) before the requested window and comes back on this week's timestamps,
so it overlays A on a chart and the formula can subtract it point
by point. The argument is positive; it says how far back to read.
summary: 'timeShift: this week''s error logs next to last week''s'
value:
compositeQuery:
queries:
- spec:
aggregations:
- alias: errors
expression: count()
filter:
expression: severity_text = 'ERROR'
name: A
signal: logs
stepInterval: 60s
type: builder_query
- spec:
aggregations:
- alias: errors
expression: count()
filter:
expression: severity_text = 'ERROR'
functions:
- args:
- value: 604800
name: timeShift
name: B
signal: logs
stepInterval: 60s
type: builder_query
- spec:
expression: A - B
name: F1
type: builder_formula
end: 1640998800000
requestType: time_series
schemaVersion: v1
start: 1640995200000
logs_raw:
summary: 'Raw: fetch raw log records'
value:

View File

@@ -7079,7 +7079,7 @@ export interface Querybuildertypesv5QueryBuilderFormulaDTO {
*/
functions?: Querybuildertypesv5FunctionDTO[] | null;
/**
* @description Accepted but currently ignored; the computed values are returned unfiltered.
* @description A filter on the formula values, referencing the formula by its name or as __result, for example F1 > 0. A time series keeps only the points that match and drops a series with none left; a scalar result keeps only the rows that match.
*/
having?: Querybuildertypesv5HavingDTO;
/**

View File

@@ -0,0 +1,51 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { createAppContextMock } from 'tests/fixtures/appContextMock';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
import { USER_ROLES } from 'types/roles';
import { fn } from 'storybook/test';
import { storyChangelog } from './__story_mockdata__/changelog';
import {
showsCloudChangelog,
showsSelfHostedChangelog,
} from './__story_mockdata__/changelogModal.play';
import ChangelogModal from '../ChangelogModal';
const { activeLicense } = createAppContextMock(USER_ROLES.ADMIN);
/** `AppLayout` opens it one second after load, for a version the user has not seen. */
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
tags: ['play'],
parameters: { signoz: {} },
args: {
changelog: storyChangelog,
onClose: fn(),
},
} satisfies Meta<typeof ChangelogModal>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Cloud workspaces update on their own, so the footer has no update actions. */
export const Cloud: Story = {
play: showsCloudChangelog,
};
/** Self-hosted workspaces get "Skip for now" and "Update my workspace". */
export const SelfHosted: Story = {
parameters: {
signoz: {
appContext: {
activeLicense: activeLicense && {
...activeLicense,
platform: LicensePlatform.SELF_HOSTED,
},
},
},
},
play: showsSelfHostedChangelog,
};

View File

@@ -0,0 +1,62 @@
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const TIMESTAMP = '2026-11-03T12:00:00Z';
function feature(
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] {
return {
id,
documentId: `feature-${id}`,
title,
description,
media: null,
sort_order: id,
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
deployment_type: DeploymentType.ALL,
};
}
/** Long enough to scroll, so the "Scroll for more" button shows. */
export const storyChangelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0.99.0',
version: 'v0.99.0',
release_date: '2026-11-03',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
features: [
feature(
1,
'Dashboard sections',
'Group panels into **sections** you can collapse, rename and drag. Existing dashboards move into a single section the first time you edit them.',
),
feature(
2,
'Service accounts',
'Create service accounts with their own API keys and roles. Keys can expire, and you can revoke them without touching the account. See the [docs](https://signoz.io/docs/) for the API.',
),
feature(
3,
'Faster log search',
'Full-text search over log bodies now uses a token index:\n\n- queries over a day of logs return up to 4x faster\n- `has()` and `hasToken()` use the same index\n- the old behaviour stays behind a setting for a release',
),
feature(
4,
'Routing policies',
'Send an alert to a channel based on its labels instead of picking the channel in every rule. Policies are evaluated in order and the first match wins.',
),
],
bug_fixes:
'- Fixed the time picker losing the selected range after a refresh.\n- Fixed trace waterfall rows overlapping when a span name wraps.\n- Fixed CSV export dropping columns with dots in their names.',
maintenance:
'- Upgraded the OpenTelemetry collector to the latest release.\n- Reduced the memory used by the query service on large dashboards.',
};

View File

@@ -0,0 +1,19 @@
import { expect, screen, waitFor } from 'storybook/test';
const TITLE = /What’s New ⎯ Changelog : November 3, 2026/;
export const showsCloudChangelog = async (): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
await expect(
screen.queryByRole('button', { name: /Skip for now/ }),
).not.toBeInTheDocument();
};
export const showsSelfHostedChangelog = async (): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
await waitFor(() =>
expect(
screen.getByRole('button', { name: /Update my workspace/ }),
).toBeVisible(),
);
};

View File

@@ -98,6 +98,15 @@ export const noSavedFiltersHandler = rest.get(
),
);
export const noSavedTracesFiltersHandler = rest.get(
'http://localhost/api/v2/quick_filters/traces',
(_req, res, ctx) =>
res(
ctx.status(200),
ctx.json(quickFiltersResponse(QuickfiltertypesSourceDTO.traces, [])),
),
);
export const loadingFiltersHandlers = [
rest.get('http://localhost/api/v2/quick_filters/logs', (_req, res, ctx) =>
res(ctx.delay('infinite')),

View File

@@ -1,6 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps, ComponentType } from 'react';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
@@ -16,8 +17,9 @@ import {
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
noSavedTracesFiltersHandler,
} from './QuickFilters.stories.mocks';
import { QuickFiltersSource } from '../types';
import { FiltersType, QuickFiltersSource } from '../types';
const meta = {
title: 'Components/Quick Filters',
@@ -110,6 +112,29 @@ export const SelectedExpandedCheckbox: Story = {
},
};
/** The duration min/max row, which a checkbox-only config never reaches. */
export const DurationFilter: Story = {
args: {
quickFilterSource: QuickFiltersSource.TRACES_EXPLORER,
config: [
...checkboxConfig,
{
attributeKey: {
dataType: DataTypes.Float64,
key: 'duration_nano',
type: '',
},
defaultOpen: true,
title: 'Duration',
type: FiltersType.DURATION,
},
],
},
parameters: {
msw: { handlers: [noSavedTracesFiltersHandler, ...handlers] },
},
};
/**
* Every tooltip the panel renders, held open: the reveal on each truncated
* filter value. Nothing bounds those values, so the panel is answered with

View File

@@ -16,13 +16,42 @@ import {
} from './K8sBaseDetails.stories.mocks';
import type { K8sBaseDetailsProps } from './types';
import {
DrawerHistoryEntry,
getDrawerHistoryDepth,
pushDrawerHistory,
resetDrawerHistory,
useDrawerHistoryStore,
} from './useDrawerHistoryStore';
type DrawerArgs = PageStoryArgs<typeof drawerMocks> &
K8sBaseDetailsProps<unknown>;
K8sBaseDetailsProps<unknown> & { earlierSteps?: number };
const TRAIL: DrawerHistoryEntry[] = [
{
category: InfraMonitoringEntity.CLUSTERS,
label: 'mgmt',
queryKeyPrefix: 'cluster',
},
{
category: InfraMonitoringEntity.NAMESPACES,
label: 'generator',
queryKeyPrefix: 'namespace',
},
{
category: InfraMonitoringEntity.DEPLOYMENTS,
label: 'app-demo-loadgenerator',
queryKeyPrefix: 'deployment',
},
{
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
queryKeyPrefix: 'node',
},
].map(({ category, label, queryKeyPrefix }) => ({
params: { selectedItem: label, category },
category,
label,
entity: { name: label },
queryKeyPrefix,
}));
const route = `/infrastructure-monitoring/kubernetes?${INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY}=pods&${INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM}=${POD_UID}`;
@@ -33,19 +62,13 @@ const meta = {
decorators: [
(Story, context): JSX.Element => {
// The back control appears only for a resource opened from another
const depth = getDrawerHistoryDepth();
if (context.args.openedFromANode && depth === 0) {
pushDrawerHistory({
params: { selectedItem: NODE_NAME, category: InfraMonitoringEntity.NODES },
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
entity: { nodeName: NODE_NAME },
queryKeyPrefix: 'node',
const steps =
context.args.earlierSteps ?? (context.args.openedFromANode ? 1 : 0);
if (getDrawerHistoryDepth() !== steps) {
useDrawerHistoryStore.setState({
entries: TRAIL.slice(TRAIL.length - steps),
});
}
if (!context.args.openedFromANode && depth > 0) {
resetDrawerHistory();
}
return <Story />;
},
@@ -60,3 +83,19 @@ type Story = StoryObj<DrawerArgs>;
export const Default: Story = {
args: { ...podEntityConfig.details } as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod drilled through a cluster, namespace, deployment and node, so the back control names the node. */
export const DeepTrail: Story = {
args: {
...podEntityConfig.details,
earlierSteps: 4,
} as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod opened from the list, so the header shows the close control in place of back. */
export const OpenedFromTheList: Story = {
args: {
...podEntityConfig.details,
openedFromANode: false,
} as Partial<DrawerArgs> as DrawerArgs,
};

View File

@@ -139,6 +139,35 @@ export const AwaitingClarification: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
};
/** The severity select open, including the free-text option the form's Select renders. */
export const ClarificationSelectOpen: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
// Open from the keyboard, and retry: the message list remounts its items
// while it measures the thread, which can close the popup again. The
// "Other" checkbox in the Notify field carries the same text, so assert
// on the popup's option role.
await waitFor(async () => {
const severityLabel = canvas.getByText('Severity');
const field = severityLabel.closest('div');
if (!field) {
throw new Error('Severity field is not in the clarification form');
}
within(field).getByRole('combobox').focus();
await userEvent.keyboard('{Enter}');
await screen.findByRole(
'option',
{ name: 'Other (type your own)' },
{ timeout: 1_000 },
);
}, untilLoaded);
},
};
/** Reopening the page on a thread that has not come back yet. */
export const LoadingThread: Story = {
args: { dataState: 'loading' },
@@ -231,6 +260,23 @@ export const NegativeFeedback: Story = {
},
};
/** Renaming a thread: the title input the row swaps in. */
export const ConversationRename: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickUntil(async () => {
const [actions] = await within(canvasElement).findAllByLabelText(
/conversation actions/i,
undefined,
untilLoaded,
);
return actions;
}, /^Rename$/);
await userEvent.click(screen.getByText('Rename'));
await within(canvasElement).findByDisplayValue(/checkout p99 regression/i);
},
};
/** What a conversation row offers: rename, a link to it, and archiving. */
export const ConversationActions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -21,6 +21,10 @@ import {
WEBHOOK_AUTHS,
type WebhookAuthChoice,
} from '../../stories/__story_mockdata__/alerts';
import {
recordChannelTestRequest,
resetChannelTestRequests,
} from './__story_mockdata__/channelsEdit';
const STORY_CHANNEL_ID = '1';
@@ -87,6 +91,13 @@ export const channelsEditMocks = defineStoryMocks({
: resolveChannelActionSuccess,
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
async (req) => {
recordChannelTestRequest(await req.json());
},
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
values.testOutcome === 'fails'
@@ -95,4 +106,5 @@ export const channelsEditMocks = defineStoryMocks({
),
],
config: () => ({ route: `/alerts/channels/edit/${STORY_CHANNEL_ID}` }),
effect: () => resetChannelTestRequests(),
});

View File

@@ -4,6 +4,7 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { expectEditableForm } from './__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from './ChannelsEdit.stories.mocks';
import AlertList from '../../index';
@@ -36,8 +37,10 @@ type Story = StoryObj<ChannelsEditArgs>;
/**
* A saved notification channel opened for editing: the name and the type are
* fixed, and the integration's own settings are filled from what was stored.
* The Channel type control swaps the integration, and typing into any field
* unlocks Save.
*/
export const Default: Story = {};
export const Default: Story = { play: expectEditableForm };
/** Mutation: clearing the required webhook URL surfaces the form's validation feedback. */
export const InvalidRequiredFields: Story = {
@@ -110,21 +113,25 @@ export const SaveFailure: Story = {
*/
export const PagerDuty: Story = {
args: { channelType: 'pagerduty' },
play: expectEditableForm,
};
/** The webhook channel, saved with basic auth on the outgoing request. */
export const Webhook: Story = {
args: { channelType: 'webhook' },
play: expectEditableForm,
};
/** The webhook channel saved with a bearer token: only the token field shows. */
export const WebhookBearerToken: Story = {
args: { channelType: 'webhook', webhookAuth: 'bearer' },
play: expectEditableForm,
};
/** The webhook channel saved without credentials: the auth option is None. */
export const WebhookWithoutAuth: Story = {
args: { channelType: 'webhook', webhookAuth: 'none' },
play: expectEditableForm,
};
/**
@@ -133,6 +140,7 @@ export const WebhookWithoutAuth: Story = {
*/
export const Opsgenie: Story = {
args: { channelType: 'opsgenie' },
play: expectEditableForm,
};
/**
@@ -141,6 +149,7 @@ export const Opsgenie: Story = {
*/
export const Email: Story = {
args: { channelType: 'email' },
play: expectEditableForm,
};
/**
@@ -149,11 +158,13 @@ export const Email: Story = {
*/
export const MicrosoftTeams: Story = {
args: { channelType: 'msteams' },
play: expectEditableForm,
};
/** The Google Chat channel, filled from the space's incoming webhook. */
export const GoogleChat: Story = {
args: { channelType: 'googlechat' },
play: expectEditableForm,
};
/**
@@ -163,7 +174,8 @@ export const GoogleChat: Story = {
*/
export const Jira: Story = {
args: { channelType: 'jira' },
play: async ({ canvasElement }): Promise<void> => {
play: async ({ canvasElement, args }): Promise<void> => {
await expectEditableForm({ canvasElement, args });
// the advanced fields have their own card now, so nothing has to be
// expanded before they can be read
await expect(
@@ -183,7 +195,8 @@ export const Jira: Story = {
*/
export const JiraSelfHosted: Story = {
args: { channelType: 'jira', jiraDeployment: 'selfhosted' },
play: async ({ canvasElement }): Promise<void> => {
play: async ({ canvasElement, args }): Promise<void> => {
await expectEditableForm({ canvasElement, args });
const canvas = within(canvasElement);
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
@@ -202,6 +215,7 @@ export const JiraSelfHosted: Story = {
*/
export const JiraServiceManagementOps: Story = {
args: { channelType: 'jsmops' },
play: expectEditableForm,
};
/**
@@ -210,9 +224,11 @@ export const JiraServiceManagementOps: Story = {
*/
export const IncidentIO: Story = {
args: { channelType: 'incidentio' },
play: expectEditableForm,
};
/** A Telegram channel, with its bot token masked behind the password field. */
export const Telegram: Story = {
args: { channelType: 'telegram' },
play: expectEditableForm,
};

View File

@@ -0,0 +1,146 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { channelSpec } from '../../../stories/__story_mockdata__/alerts';
import { PAGE_LOAD } from '../../../stories/channelAuthz';
import type { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import { channelTestRequests } from './channelsEdit';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof channelsEditMocks>;
}
/** Native text controls only: the switches and radios keep a hidden input of their own. */
const FIELD_SELECTOR =
'form input:not([aria-hidden="true"]):not([type="hidden"]), form textarea';
const allFields = (canvasElement: HTMLElement): HTMLElement[] =>
Array.from(canvasElement.querySelectorAll<HTMLElement>(FIELD_SELECTOR));
/** A saved channel's name is fixed, so it is off whether or not the form is. */
const editableFields = (canvasElement: HTMLElement): HTMLElement[] =>
allFields(canvasElement).filter((field) => field.id !== 'channel-name');
const SLACK_ROW_BUTTONS = /^slack-(field|action)-(remove-\d+|add)$/;
const slackRowButtons = (canvasElement: HTMLElement): HTMLElement[] =>
within(canvasElement).queryAllByTestId(SLACK_ROW_BUTTONS);
export const expectEditableForm = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const save = await within(canvasElement).findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(
() => expect(editableFields(canvasElement).length).toBeGreaterThan(0),
PAGE_LOAD,
);
for (const field of editableFields(canvasElement)) {
await expect(field).toBeEnabled();
}
await expect(save).toHaveAttribute('aria-disabled', 'true');
await userEvent.type(editableFields(canvasElement)[0], 'x');
await waitFor(
() => expect(save).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
};
/**
* The permission check answers after the form has mounted editable, so the
* fields are polled until they lock rather than read once.
*/
export const expectReadOnlyForm = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const canvas = within(canvasElement);
const save = await canvas.findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(() => {
const fields = allFields(canvasElement);
void expect(fields.length).toBeGreaterThan(1);
fields.forEach((field) => {
void expect(field).toBeDisabled();
});
}, PAGE_LOAD);
await expect(save).toHaveAttribute('aria-disabled', 'true');
if (args.channelType === 'slack') {
const buttons = slackRowButtons(canvasElement);
const fieldCount = allFields(canvasElement).length;
// two field rows, one action row, and an add button for each list
await expect(buttons).toHaveLength(5);
for (const button of buttons) {
await userEvent.click(button);
}
await expect(slackRowButtons(canvasElement)).toHaveLength(5);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
}
};
/**
* Switching the mode swaps which credential fields render, so a click that
* landed would change how many fields the form holds.
*/
export const expectModeRadioLocked = async (
context: PlayContext,
radio: RegExp,
): Promise<void> => {
await expectReadOnlyForm(context);
const { canvasElement } = context;
const fieldCount = allFields(canvasElement).length;
await userEvent.click(
within(canvasElement).getByRole('radio', { name: radio }),
);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
};
export const expectWebhookAuthLocked = (context: PlayContext): Promise<void> =>
expectModeRadioLocked(context, /bearer/i);
export const expectJiraDeploymentLocked = (
context: PlayContext,
): Promise<void> => expectModeRadioLocked(context, /self-hosted/i);
export const sendSavedConfig = async (context: PlayContext): Promise<void> => {
const { canvasElement, args } = context;
await expectReadOnlyForm(context);
const test = await within(canvasElement).findByTestId('test-channel-button');
await waitFor(
() => expect(test).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
await userEvent.click(test);
await waitFor(() => expect(channelTestRequests()).toHaveLength(1), PAGE_LOAD);
await expect(channelTestRequests()[0].config).toMatchObject({
kind: args.channelType,
spec: channelSpec(args.channelType, args.webhookAuth, args.jiraDeployment),
});
};

View File

@@ -0,0 +1,22 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { AlertmanagertypesTestableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
/** Every test send the form made since the story mounted, oldest first. */
const testRequests: AlertmanagertypesTestableNotificationChannelDTO[] = [];
export const recordChannelTestRequest = (
request: AlertmanagertypesTestableNotificationChannelDTO,
): void => {
testRequests.push(request);
};
export const channelTestRequests =
(): readonly AlertmanagertypesTestableNotificationChannelDTO[] => testRequests;
export const resetChannelTestRequests = (): void => {
testRequests.length = 0;
};

View File

@@ -13,6 +13,12 @@ import {
READ,
UPDATE,
} from '../../../stories/channelAuthz';
import {
expectJiraDeploymentLocked,
expectReadOnlyForm,
expectWebhookAuthLocked,
sendSavedConfig,
} from '../__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import AlertList from '../../../index';
@@ -56,18 +62,12 @@ export const NoRead: Story = {
/**
* Reading is enough to open the page, so losing `update` alone leaves it
* standing read-only: the fields go disabled and Save is locked, not hidden.
* standing read-only: every field goes disabled and Save is locked, not hidden.
* The Channel type control walks the same check across every integration.
*/
export const NoUpdate: Story = {
args: { revoked: [UPDATE] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
);
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
play: expectReadOnlyForm,
};
/**
@@ -101,17 +101,24 @@ export const NoCreate: Story = {
*/
export const ReadOnly: Story = {
args: { revoked: [UPDATE, CREATE, DELETE] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
play: async (context) => {
await expectReadOnlyForm(context);
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
await within(context.canvasElement).findByTestId('test-channel-button'),
);
await expectDisabled(await canvas.findByTestId('test-channel-button'));
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
};
/**
* Read-only keeps Test: sending is a create on the collection, so a reader who
* cannot edit the channel can still test it. The request carries the saved
* config.
*/
export const NoUpdateTest: Story = {
args: { revoked: [UPDATE] },
play: sendSavedConfig,
};
/**
* The same denial on a Telegram channel. Its fields are the kind the form gained
* last, including the only toggle a settings panel renders, so this is where a
@@ -145,6 +152,25 @@ export const TelegramReadOnly: Story = {
},
};
/**
* The same denial on a webhook saved with basic auth. The credential fields are
* off, and so is the radio that would swap them for a bearer token.
*/
export const WebhookReadOnly: Story = {
args: { channelType: 'webhook', revoked: [UPDATE, CREATE, DELETE] },
play: expectWebhookAuthLocked,
};
/**
* The same denial on a Jira Cloud channel. Every field is off, including the
* advanced ones, and so is the radio that would swap the Atlassian email and API
* token for a personal access token.
*/
export const JiraReadOnly: Story = {
args: { channelType: 'jira', revoked: [UPDATE, CREATE, DELETE] },
play: expectJiraDeploymentLocked,
};
/** No channel permission at all: the page is denied before the form exists. */
export const NoChannelAccess: Story = {
args: { revoked: NOTIFICATION_CHANNEL },

View File

@@ -978,7 +978,7 @@ const CHANNEL_SPECS: Record<ChannelType, Record<string, unknown>> = {
},
};
const channelSpec = (
export const channelSpec = (
type: ChannelType,
webhookAuth: WebhookAuthChoice,
jiraDeployment: JiraDeploymentChoice,

View File

@@ -63,6 +63,20 @@ const expandConfigSections: Story['play'] = async ({ canvasElement }) => {
*/
export const Default: Story = {};
/** The ClickHouse query tab, including its info callout. */
export const ClickHouseQuery: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText('ClickHouse Query', undefined, {
timeout: 15000,
}),
);
await screen.findByText(/ClickHouse query agent skill/i, undefined, {
timeout: 15000,
});
},
};
/** The create route, seeding an unsaved panel of the chosen kind. */
export const NewPanel: Story = {
args: { panel: 'new' },
@@ -83,6 +97,21 @@ export const PieChartPanel: Story = {
args: { panel: 'traffic-share' },
};
/** A new area chart: the time series options with the area filled. */
export const AreaChartPanel: Story = {
args: { panel: 'new', newPanelKind: 'area-chart' },
};
/** A new histogram, where the display options are its buckets. */
export const HistogramPanel: Story = {
args: { panel: 'new', newPanelKind: 'histogram' },
};
/** A new text panel: a markdown body in place of the query builder. */
export const TextPanel: Story = {
args: { panel: 'new', newPanelKind: 'text' },
};
/** A list panel, where the config pane is the column editor. */
export const ListPanel: Story = {
args: { panel: 'recent-logs' },

View File

@@ -105,6 +105,19 @@ export const ChartAppearance: Story = {
},
};
/** Disconnect-values in threshold mode, with an invalid duration showing the inline error. */
export const ChartAppearanceDisconnectThreshold: Story = {
play: async (context) => {
await ChartAppearance.play?.(context);
await pickSegment('panel-editor-v2-span-gaps', 'threshold');
const input = await screen.findByTestId('panel-editor-v2-span-gaps-value');
await userEvent.clear(input);
await userEvent.type(input, '5x');
await screen.findByText(/enter a valid duration/i);
},
};
/** Dashed lines under a gradient fill, with the points drawn. */
export const ChartAppearanceDashedGradient: Story = {
play: async (context) => {

View File

@@ -191,6 +191,22 @@ export const TooltipsInViewPanelModal: Story = {
},
};
/** A list or table panel's search field, expanded and filled. */
export const PanelSearchExpanded: Story = {
play: async ({ canvasElement }) => {
// Both the table and the log list render a search trigger; expand the first.
const [trigger] = await within(canvasElement).findAllByTestId(
'panel-header-search-trigger',
{},
{ timeout: 15000 },
);
await userEvent.click(trigger);
const input = await screen.findByTestId('panel-header-search-input');
await userEvent.type(input, 'error');
},
};
/**
* The dashboard's own Actions menu, open: rename, clone, lock, full screen and
* delete, the menu the toolbar's Actions button carries.
@@ -243,6 +259,34 @@ export const SectionActionsMenu: Story = {
},
};
/** Delete dashboard, the confirm dialog the Actions menu opens. */
export const DeleteDashboardDialog: Story = {
play: async (context) => {
await ActionsMenu.play?.(context);
// The row stays inert until its authz checks resolve, so one click can
// land too early; keep clicking until the confirm dialog is up.
await waitFor(
async () => {
const item = screen.queryByTestId('dashboard-action-delete');
if (item) {
await userEvent.click(item);
}
screen.getByText('This action cannot be undone.');
},
{ timeout: 10000 },
);
},
};
/** Rename section, the title dialog a section menu opens. */
export const RenameSectionDialog: Story = {
play: async (context) => {
await SectionActionsMenu.play?.(context);
await userEvent.click(await screen.findByText('Rename section'));
await screen.findByRole('dialog', { name: /rename section/i });
},
};
const openNewPanelPicker = async (
canvasElement: HTMLElement,
): Promise<void> => {

View File

@@ -97,3 +97,20 @@ export const NavSettingsMenu: Story = {
await screen.findByRole('menu');
},
};
/** Impersonation mode: the warning banner above the page content. */
export const NoAuthBanner: Story = {
args: { banner: 'no-auth' },
play: async (): Promise<void> => {
await screen.findByTestId('no-auth-banner', undefined, { timeout: 10000 });
},
};
/** The command palette, opened with the same shortcut the shell listens for. */
export const CommandPalette: Story = {
play: async (): Promise<void> => {
await userEvent.keyboard('{Meta>}k{/Meta}');
await screen.findByPlaceholderText('Search…', undefined, { timeout: 10000 });
await screen.findByText('Go to Home');
},
};

View File

@@ -69,6 +69,28 @@ export const DetailsDrawerLogsTab: StoryObj<PodsArgs> = {
},
};
/** A log opened from the pod's logs tab, over the details drawer. */
export const DetailsDrawerLogDetails: StoryObj<PodsArgs> = {
args: { drawer: true },
play: async () => {
const drawer = within(
await screen.findByRole('dialog', {}, { timeout: 10000 }),
);
await userEvent.click(
await drawer.findByText('Logs', {}, { timeout: 10000 }),
);
const [line] = await drawer.findAllByText(
/handled request in/,
{},
{ timeout: 10000 },
);
await userEvent.click(line);
await screen.findByTestId('log-detail-drawer', {}, { timeout: 10000 });
},
};
/** The copy button beside the pod name in the drawer, which toasts the copy. */
export const PodNameCopiedToast: StoryObj<PodsArgs> = {
args: { drawer: true },

View File

@@ -117,6 +117,43 @@ export const ConnectAccount: Story = {
},
};
/** Azure's connect dialog, which the AWS regions form does not open. */
export const AzureConnectAccount: Story = {
args: { provider: 'azure', accounts: 0 },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/integrate now/i,
undefined,
untilLoaded,
),
);
await screen.findByRole('dialog', undefined, untilLoaded);
},
};
/** The GCP region combobox, opened from the connect drawer. */
export const GcpRegionDropdown: Story = {
args: { provider: 'gcp', accounts: 0 },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/integrate now/i,
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByTestId(
'gcp-deployment-region-select',
undefined,
untilLoaded,
),
);
await screen.findByRole('listbox');
},
};
/** The regions an already-connected account collects from. */
export const EditAccount: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -14,6 +14,7 @@ import {
type GroupSave,
MAPPING_GROUP_MAX,
spanMapperGroupsResponse,
spanMappersResponse,
wideConditionGroupsResponse,
} from './__story_mockdata__/attributeMapping';
@@ -28,6 +29,15 @@ export const wideConditionGroup = rest.get(
res(ctx.status(200), ctx.json(wideConditionGroupsResponse())),
);
export const groupMappers = rest.get(
'http://localhost/api/v1/span_mapper_groups/:groupId/span_mappers',
(req, res, ctx) =>
res(
ctx.status(200),
ctx.json(spanMappersResponse(String(req.params.groupId))),
),
);
export const attributeMappingMocks = defineStoryMocks({
controls: {
groups: countControl('Mapping groups', {

View File

@@ -7,6 +7,7 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import LLMObservabilityPage from '../../index';
import {
attributeMappingMocks,
groupMappers,
wideConditionGroup,
} from './AttributeMapping.stories.mocks';
@@ -79,6 +80,29 @@ export const GroupFormDrawer: Story = {
},
};
/** The drawer that adds a mapping to the first group. */
export const AddMappingDrawer: Story = {
parameters: { msw: { handlers: [groupMappers] } },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
const [firstGroup] = await canvas.findAllByTestId(
/^group-expand-/,
{},
{ timeout: 15000 },
);
await userEvent.click(firstGroup);
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /add mapping/i },
{ timeout: 15000 },
),
);
await screen.findByText('New custom mapping');
},
};
/**
* A group toggled off and saved: the toast announcing the saved changes, raised
* once the PATCH and the list refetch answer. Set Save changes to `error`,

View File

@@ -5,10 +5,15 @@
import type {
ListSpanMapperGroups200,
ListSpanMappers200,
SpantypesSpanMapperGroupConditionKeyDTO,
SpantypesSpanMapperGroupDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SpantypesSpanMapperOriginDTO } from 'api/generated/services/sigNoz.schemas';
import {
SpantypesFieldContextDTO,
SpantypesSpanMapperOperationDTO,
SpantypesSpanMapperOriginDTO,
} from 'api/generated/services/sigNoz.schemas';
const ORG_ID = 'org-signoz';
@@ -72,6 +77,38 @@ export const spanMapperGroupsResponse = (
data: { items: GROUPS.slice(0, count).map(group) },
});
/** The mappings an expanded group lists, which the groups response does not carry. */
export const spanMappersResponse = (groupId: string): ListSpanMappers200 => ({
status: 'success',
data: {
items: [
{
id: `${groupId}-mapper-1`,
groupId,
name: 'gen_ai.request.model',
enabled: true,
origin: SpantypesSpanMapperOriginDTO.user,
fieldContext: SpantypesFieldContextDTO.attribute,
config: {
sources: [
{
key: 'langchain.model',
context: SpantypesFieldContextDTO.attribute,
operation: SpantypesSpanMapperOperationDTO.copy,
priority: 0,
enabled: true,
},
],
},
createdAt: '2026-07-18T11:20:00Z',
createdBy: 'anna@signoz.io',
updatedAt: '2026-08-05T08:40:00Z',
updatedBy: 'anna@signoz.io',
},
],
},
});
const MANY_ATTRIBUTES = [
'langchain.model',
'langchain.prompt_tokens',

View File

@@ -39,6 +39,34 @@ export const NothingPriced: Story = {
args: { rules: 0 },
};
/** Models seen in spans that no rule prices yet. */
export const UnpricedModels: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'tab',
{ name: /unpriced models/i },
{ timeout: 15000 },
),
);
await screen.findByRole('tab', { name: /unpriced models/i, selected: true });
},
};
/** Creating a rule: the blank drawer, with the provider select enabled. */
export const ModelCostDrawerCreate: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /add model cost/i },
{ timeout: 15000 },
),
);
await screen.findByTestId('drawer-provider-select');
},
};
/**
* The first pricing rule's menu, open over the table: edit the rule or drop it.
*/

View File

@@ -116,6 +116,16 @@ export const AddProcessor: Story = {
},
};
/** Severity Parser is the type whose mapping fields are CSV inputs. */
export const AddSeverityParserProcessor: Story = {
play: async (context): Promise<void> => {
await AddProcessor.play?.(context);
await userEvent.click(await screen.findByText('Grok'));
await userEvent.click(await screen.findByTitle('Severity Parser'));
await screen.findByText('Parse Severity Value From');
},
};
/**
* The logs a pipeline matches, over the interval the preview asks for, with the
* simulation of its processors one click away.

View File

@@ -106,6 +106,21 @@ export const RawFormat: Story = {
args: { format: 'raw' },
};
/** The format popover: the format list, the max-lines stepper, and the font-size control. */
export const FormatMenuOpen: Story = {
args: { format: 'raw' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'periscope-btn-format-options',
undefined,
untilLoaded,
),
);
await screen.findByTestId('max-lines-per-row', undefined, untilLoaded);
},
};
/** An explorer with no configured quick filters. */
export const NoQuickFilters: Story = {
args: { quickFilters: 0 },

View File

@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -98,6 +98,21 @@ export const DropRate: Story = {
args: { view: MessagingQueuesViewTypeOptions.DropRate },
};
/** The custom-interval input inside the evaluation-time dropdown. */
export const DropRateIntervalOpen: Story = {
args: { view: MessagingQueuesViewTypeOptions.DropRate },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText('10ms', undefined, untilLoaded),
);
await screen.findByPlaceholderText(
'Enter custom time (ms)',
undefined,
untilLoaded,
);
},
};
/** The broker, producer, consumer and JVM metrics kafka itself reports. */
export const MetricView: Story = {
args: { view: MessagingQueuesViewTypeOptions.MetricPage },

View File

@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -76,3 +76,26 @@ export const DownloadMenu: Story = {
await screen.findByRole('menu');
},
};
/** The apdex threshold popover, opened from the overview's settings control. */
export const ApDexSettingsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
const trigger = await waitFor(
() => {
const found = canvasElement.querySelector<HTMLElement>(
'.ap-dex-settings-popover-content button',
);
if (!found) {
throw new Error('Apdex settings control is not rendered');
}
return found;
},
{ timeout: 15000 },
);
await userEvent.click(trigger);
await screen.findByText(/apdex threshold/i);
},
};

View File

@@ -86,6 +86,11 @@ export const onboardingV2Mocks = defineStoryMocks({
'http://localhost/api/v1/roles',
response.json(() => rolesListResponse(0)),
),
// Add Credit Card creates the subscription; an empty redirect keeps the
// story from opening a billing tab.
rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>
res(ctx.json({ status: 'success', data: { redirectURL: '' } })),
),
rest.post('http://localhost/api/v2/users', (_req, res, ctx) => {
if (values.invite === 'loading') {
return res(ctx.delay('infinite'));

View File

@@ -1,82 +1,20 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import OnboardingPageV2 from '../OnboardingPageV2';
import { onboardingV2Mocks } from './OnboardingPageV2.stories.mocks';
import {
onboardingV2Mocks,
SETUP_STEPS,
type SetupStep,
} from './OnboardingPageV2.stories.mocks';
openAddCreditCard,
openInviteModal,
searchWithoutResults,
sendInvite,
walkToStep,
} from './__story_mockdata__/onboardingV2.play';
type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;
type Canvas = ReturnType<typeof within>;
/** The catalogue mounts before the first group of sources paints. */
const untilRendered = { timeout: 15_000 };
/**
* Every option is a button wrapping its own logo, so the accessible name carries
* the label twice and matches the other sources with the label as a prefix
* (`Java`, `JavaScript`). The label's own text node is the one thing that is
* exact.
*/
const chooseOption = async (canvas: Canvas, label: string): Promise<void> => {
const option = await canvas.findByText(label, undefined, untilRendered);
await userEvent.click(option.closest('button') as HTMLElement);
};
const answerDataSource = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Java');
const answerFramework = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Spring Boot');
const answerEnvironment = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'VM');
const openConfigureProduct = async (canvas: Canvas): Promise<void> => {
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /configure your product/i },
untilRendered,
),
);
};
const ANSWER_STEP = [
answerDataSource,
answerFramework,
answerEnvironment,
openConfigureProduct,
];
const advanceToSetupStep = async (
canvasElement: HTMLElement,
step: SetupStep,
): Promise<void> => {
const canvas = within(canvasElement);
// A source that arrived through the param is already on the setup
// instructions, with no question left to answer.
if (!canvas.queryByText('Select your data source')) {
return;
}
const answers = ANSWER_STEP.slice(0, SETUP_STEPS.indexOf(step));
// Sequential: each answer is what renders the question the next one reads.
await answers.reduce(
(walked, answer) => walked.then(() => answer(canvas)),
Promise.resolve(),
);
};
const pageStory = storyMocks(onboardingV2Mocks, { layout: 'app' });
/**
@@ -89,16 +27,7 @@ const meta = {
title: 'Pages/Onboarding/Add Data Source',
tags: ['play'],
component: OnboardingPageV2,
/**
* Destructuring `mount` is what makes the step control a control: Storybook
* re-runs a play function on an arg change only for a story that asks to be
* remounted, and otherwise re-renders the one it already walked.
*/
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
},
play: walkToStep,
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<OnboardingV2Args>;
@@ -137,35 +66,12 @@ export const SourcePreselected: Story = {
/** The one thing the header offers besides support: bringing the team along. */
export const InviteTeammate: Story = {
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
await userEvent.click(
within(canvasElement).getByRole('button', { name: /invite a teammate/i }),
);
// antd portals the modal out of the story root.
await screen.findByText('Invite a team member', undefined, untilRendered);
},
play: openInviteModal,
};
/** A search nothing answers, where the catalogue offers to add the source instead. */
export const NoSearchResults: Story = {
play: async ({ mount, canvasElement }): Promise<void> => {
await mount();
const canvas = within(canvasElement);
await userEvent.type(
await canvas.findByPlaceholderText('Search', undefined, untilRendered),
'ledger',
);
// The search is debounced, so the miss lands a beat after the last keystroke.
await canvas.findByText(/no results for ledger/i, undefined, untilRendered);
},
play: searchWithoutResults,
};
/**
@@ -174,48 +80,14 @@ export const NoSearchResults: Story = {
* is accepted; Invite result changes how it answers.
*/
export const InvitesSentToast: Story = {
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
),
);
const dialog = await screen.findByRole('dialog', undefined, untilRendered);
const [email] = await within(dialog).findAllByTestId(
/^invite-email-/,
undefined,
untilRendered,
);
await userEvent.type(email, 'jon@winterfell.dev');
const [roles] = await within(dialog).findAllByRole('combobox');
await userEvent.click(roles);
const viewers = await screen.findAllByText(
'viewer',
undefined,
untilRendered,
);
await userEvent.click(
viewers[viewers.length - 1].closest(
'.ant-select-item-option',
) as HTMLElement,
);
await userEvent.keyboard('{Escape}');
await userEvent.click(
await within(dialog).findByRole('button', { name: /send invites/i }),
);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
);
}
},
play: sendInvite,
};
/**
* A cloud trial without premium support, whose Contact Support in the header asks
* for a card to unlock chat support instead of opening the chat.
*/
export const FacingIssuesAddCard: Story = {
args: { support: 'add-card' },
play: openAddCreditCard,
};

View File

@@ -0,0 +1,227 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
onboardingV2Mocks,
SETUP_STEPS,
type SetupStep,
} from '../OnboardingPageV2.stories.mocks';
type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;
interface PlayContext {
mount: () => Promise<unknown>;
args: OnboardingV2Args;
canvasElement: HTMLElement;
}
type Canvas = ReturnType<typeof within>;
/** The catalogue mounts before the first group of sources paints. */
const untilRendered = { timeout: 15_000 };
/**
* Every option is a button wrapping its own logo, so the accessible name carries
* the label twice and matches the other sources with the label as a prefix
* (`Java`, `JavaScript`). The label's own text node is the one thing that is
* exact.
*/
const chooseOption = async (canvas: Canvas, label: string): Promise<void> => {
const option = await canvas.findByText(label, undefined, untilRendered);
await userEvent.click(option.closest('button') as HTMLElement);
};
const answerDataSource = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Java');
const answerFramework = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Spring Boot');
const answerEnvironment = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'VM');
const openConfigureProduct = async (canvas: Canvas): Promise<void> => {
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /configure your product/i },
untilRendered,
),
);
};
const ANSWER_STEP = [
answerDataSource,
answerFramework,
answerEnvironment,
openConfigureProduct,
];
const advanceToSetupStep = async (
canvasElement: HTMLElement,
step: SetupStep,
): Promise<void> => {
const canvas = within(canvasElement);
// A source that arrived through the param is already on the setup
// instructions, with no question left to answer.
if (!canvas.queryByText('Select your data source')) {
return;
}
const answers = ANSWER_STEP.slice(0, SETUP_STEPS.indexOf(step));
// Sequential: each answer is what renders the question the next one reads.
await answers.reduce(
(walked, answer) => walked.then(() => answer(canvas)),
Promise.resolve(),
);
};
/**
* Destructuring `mount` is what makes the step control a control: Storybook
* re-runs a play function on an arg change only for a story that asks to be
* remounted, and otherwise re-renders the one it already walked.
*/
export const walkToStep = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
};
export const openInviteModal = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
await userEvent.click(
within(canvasElement).getByRole('button', { name: /invite a teammate/i }),
);
// antd portals the modal out of the story root.
await screen.findByText('Invite a team member', undefined, untilRendered);
};
export const searchWithoutResults = async ({
mount,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
const canvas = within(canvasElement);
await userEvent.type(
await canvas.findByPlaceholderText('Search', undefined, untilRendered),
'ledger',
);
// The search is debounced, so the miss lands a beat after the last keystroke.
await canvas.findByText(/no results for ledger/i, undefined, untilRendered);
};
export const sendInvite = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
),
);
const dialog = await screen.findByRole('dialog', undefined, untilRendered);
const [email] = await within(dialog).findAllByTestId(
/^invite-email-/,
undefined,
untilRendered,
);
await userEvent.type(email, 'jon@winterfell.dev');
const [roles] = await within(dialog).findAllByRole('combobox');
await userEvent.click(roles);
const viewers = await screen.findAllByText('viewer', undefined, untilRendered);
await userEvent.click(
viewers[viewers.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
await userEvent.keyboard('{Escape}');
await userEvent.click(
await within(dialog).findByRole('button', { name: /send invites/i }),
);
if (args.invite === 'success') {
await waitFor(
() => expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
{ timeout: 5_000 },
);
}
};
/** Banners that turn the cloud license into a self-hosted one. */
const SELF_HOSTED_BANNERS: readonly OnboardingV2Args['banner'][] = [
'license-expired',
'license-terminated',
];
/** Only a cloud workspace without premium support is offered the card. */
const offersAddCard = (args: OnboardingV2Args): boolean =>
args.support === 'add-card' &&
args.license === 'cloud' &&
!SELF_HOSTED_BANNERS.includes(args.banner);
const ADD_CARD_DIALOG = { name: /Add Credit Card for Chat Support/i };
export const openAddCreditCard = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
const canvas = within(canvasElement);
if (!offersAddCard(args)) {
await canvas.findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
);
await expect(
screen.queryByRole('dialog', ADD_CARD_DIALOG),
).not.toBeInTheDocument();
return;
}
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /contact support/i },
untilRendered,
),
);
// antd portals the modal out of the story root.
await screen.findByRole('dialog', ADD_CARD_DIALOG, untilRendered);
};

View File

@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { screen, userEvent } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -35,3 +36,20 @@ export const ExpiredLink: Story = {
// The deliberate 410 is the state under test.
parameters: { allowConsoleErrors: true },
};
/** The mismatch callout, after the two password fields disagree and blur. */
export const PasswordMismatch: Story = {
play: async ({ canvasElement }): Promise<void> => {
const password = await screen.findByTestId('password', undefined, {
timeout: 15000,
});
const confirm = await screen.findByPlaceholderText(
/confirm your new password/i,
);
await userEvent.type(password, 'password123');
await userEvent.type(confirm, 'password456');
await userEvent.click(canvasElement);
await screen.findByText(/passwords don't match/i);
},
};

View File

@@ -197,30 +197,8 @@ export const openMember = async (
await userEvent.click(cell.closest('tr') as HTMLElement);
};
/**
* Selects `viewer` in the roles dropdown at `index`. The option's content ignores
* pointer events, so the click goes to the option around it. A click on the
* label closes the dropdown, where Escape would close the dialog too.
*/
const pickRole = async (index: number): Promise<void> => {
const comboboxes = await screen.findAllByRole(
'combobox',
undefined,
untilLoaded,
);
await userEvent.click(comboboxes[index]);
const options = await screen.findAllByText('viewer', undefined, untilLoaded);
await userEvent.click(
options[options.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
await userEvent.click(await screen.findByText('Email address'));
};
export const sendInvites = async (
export const openInviteForm = async (
canvasElement: HTMLElement,
emails: string[],
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
@@ -229,6 +207,49 @@ export const sendInvites = async (
untilLoaded,
),
);
// The form opens with a row per seat, each carrying its own email field.
await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);
};
/** A click on the label closes the dropdown, where Escape would close the dialog too. */
export const closeRoles = async (): Promise<void> => {
await userEvent.click(await screen.findByText('Email address'));
};
/**
* Picks `role` in the open roles dropdown. The option's content ignores pointer
* events, so the click goes to the option around it.
*/
export const pickOpenRole = async (role: string): Promise<void> => {
const options = await screen.findAllByText(role, undefined, untilLoaded);
await userEvent.click(
options[options.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
};
/** Opens the roles dropdown of the invite row at `index`. */
export const openInviteRoleDropdown = async (index: number): Promise<void> => {
const comboboxes = await screen.findAllByRole(
'combobox',
undefined,
untilLoaded,
);
await userEvent.click(comboboxes[index]);
};
const pickRole = async (index: number): Promise<void> => {
await openInviteRoleDropdown(index);
await pickOpenRole('viewer');
await closeRoles();
};
export const sendInvites = async (
canvasElement: HTMLElement,
emails: string[],
): Promise<void> => {
await openInviteForm(canvasElement);
const fields = await screen.findAllByTestId(
/^invite-email-/,
undefined,

View File

@@ -1,16 +1,31 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
membersMocks,
openMember,
openResetLink,
sendInvites,
untilLoaded,
} from './Members.stories.mocks';
copyInviteLink,
copyResetLink,
deleteMember,
failResetLink,
filterDeletedOnly,
filterPendingOnly,
openAssignRoles,
openDeleteMemberConfirm,
openEditMember,
openFilterMenu,
openInviteMembers,
openInviteRoles,
openPendingMember,
openRevokeInviteConfirm,
revokeInvite,
saveMemberName,
searchNoResults,
selectInviteRoles,
sendInvitesPartiallyRefused,
sendInvitesToAll,
} from './__story_mockdata__/members.play';
import { membersMocks } from './Members.stories.mocks';
import SettingsPage from '../../Settings';
@@ -39,15 +54,6 @@ type Story = StoryObj<MembersArgs>;
/** One more than the twenty rows a page holds. */
const OVER_ONE_PAGE = 21;
const openPendingMember = async ({
canvasElement,
}: {
canvasElement: HTMLElement;
}): Promise<void> => {
await openMember(canvasElement, /podrick payne/i);
await screen.findByText(/invited on/i, undefined, untilLoaded);
};
/**
* Everyone with a seat in the workspace: who they are, whether they have taken
* up their invite, and when they joined.
@@ -61,68 +67,22 @@ export const AllPending: Story = {
/** Interaction: the status menu is open with the real member counts. */
export const FilterMenuOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/all members/i,
undefined,
untilLoaded,
),
);
await screen.findByText(/pending invites/i, undefined, untilLoaded);
},
play: openFilterMenu,
};
/** Interaction: the pending-invite filter narrows the real member table. */
export const PendingOnly: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/all members/i,
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByText(/^pending invites/i, undefined, untilLoaded),
);
// One badge per pending row.
await screen.findAllByText('INVITED', undefined, untilLoaded);
},
play: filterPendingOnly,
};
/** Interaction: the deleted-member filter exposes the read-only member rows. */
export const DeletedOnly: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/all members/i,
undefined,
untilLoaded,
),
);
await userEvent.click(
// The unfiltered table already shows a DELETED badge, so the menu option
// is matched on its own count suffix.
await screen.findByText(/^deleted ⎯/i, undefined, untilLoaded),
);
await screen.findAllByText('DELETED', undefined, untilLoaded);
},
play: filterDeletedOnly,
};
/** Empty: searching for a non-member renders the table's supported empty state. */
export const SearchNoResults: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.type(
await within(canvasElement).findByPlaceholderText(
/search by name or email/i,
undefined,
untilLoaded,
),
'no-such-member',
);
await screen.findByText(/no results for/i, undefined, untilLoaded);
},
play: searchNoResults,
};
/** More members than one page holds, which is where the pager appears. */
@@ -132,10 +92,7 @@ export const Paginated: Story = {
/** A member opened up: the name and roles that can be changed from here. */
export const EditMember: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await screen.findByPlaceholderText(/enter name/i, undefined, untilLoaded);
},
play: openEditMember,
};
/**
@@ -154,51 +111,32 @@ export const ExpiredInvite: Story = {
/** Interaction: deleting an active member is guarded by its confirmation dialog. */
export const DeleteMemberConfirm: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await userEvent.click(
await screen.findByRole('button', { name: 'Delete Member' }),
);
await screen.findByRole('dialog', { name: 'Delete Member' });
},
play: openDeleteMemberConfirm,
};
/** Interaction: revoking a pending invite uses its distinct confirmation copy. */
export const RevokeInviteConfirm: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: 'Revoke Invite' }),
);
await screen.findByRole('dialog', { name: 'Revoke Invite' });
},
play: openRevokeInviteConfirm,
};
/**
* The roles a member can be given. The dropdown opens off the inner combobox,
* not the wrapper the click lands on first.
*/
/** The roles a member can be given. */
export const AssignRoles: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await userEvent.click(await screen.findByRole('combobox'));
await screen.findByText('oncall-responder', undefined, untilLoaded);
},
play: openAssignRoles,
};
/** The form that mails seats out: an email and a role per row. */
export const InviteMembers: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/invite member/i,
undefined,
untilLoaded,
),
);
// The form opens with a row per seat, each carrying its own email field.
await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);
},
play: openInviteMembers,
};
/** The invite form with the first row's roles dropdown open. */
export const InviteRolesOpen: Story = {
play: openInviteRoles,
};
/** The invite form after three roles were picked on the first row. */
export const InviteRolesSelected: Story = {
play: selectInviteRoles,
};
/**
@@ -206,34 +144,14 @@ export const InviteMembers: Story = {
* to `error` or `loading` to see the form instead.
*/
export const InvitesSentToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@nightswatch.io',
]);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
);
}
},
play: sendInvitesToAll,
};
/** One address refused out of two: the warning that some invites failed. */
export const InvitesPartiallyFailedToast: Story = {
// The 409 for the refused address is the state under test.
parameters: { allowConsoleErrors: true },
play: async ({ canvasElement, args }): Promise<void> => {
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@blocked.example',
]);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/some invites failed/i)).toBeVisible(),
);
}
},
play: sendInvitesPartiallyRefused,
};
/**
@@ -241,27 +159,7 @@ export const InvitesPartiallyFailedToast: Story = {
* member to `error` or `loading` to see the drawer instead.
*/
export const MemberUpdatedToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
const name = await screen.findByPlaceholderText(
/enter name/i,
undefined,
untilLoaded,
);
await waitFor(() => expect(name).toHaveValue('Jon Snow'), untilLoaded);
await userEvent.type(name, ' Targaryen');
await userEvent.click(
await screen.findByRole('button', { name: 'Save Member Details' }),
);
if (args.memberUpdate === 'success') {
await waitFor(() =>
expect(
screen.getByText(/member details updated successfully/i),
).toBeVisible(),
);
}
},
play: saveMemberName,
};
/**
@@ -269,22 +167,7 @@ export const MemberUpdatedToast: Story = {
* the member to `error` or `loading` to see the dialog instead.
*/
export const MemberDeletedToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await userEvent.click(
await screen.findByRole('button', { name: 'Delete Member' }),
);
const dialog = await screen.findByRole('dialog', { name: 'Delete Member' });
await userEvent.click(
within(dialog).getByRole('button', { name: 'Delete Member' }),
);
if (args.memberDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/member deleted successfully/i)).toBeVisible(),
);
}
},
play: deleteMember,
};
/**
@@ -292,22 +175,7 @@ export const MemberDeletedToast: Story = {
* Deleting the member to `error` or `loading` to see the dialog instead.
*/
export const InviteRevokedToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: 'Revoke Invite' }),
);
const dialog = await screen.findByRole('dialog', { name: 'Revoke Invite' });
await userEvent.click(
within(dialog).getByRole('button', { name: 'Revoke Invite' }),
);
if (args.memberDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/invite revoked successfully/i)).toBeVisible(),
);
}
},
play: revokeInvite,
};
/**
@@ -315,13 +183,7 @@ export const InviteRevokedToast: Story = {
* confirming it.
*/
export const ResetLinkCopiedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openResetLink(canvasElement);
await userEvent.click(
await screen.findByRole('button', { name: /^copy$/i }, untilLoaded),
);
await screen.findByText(/reset link copied to clipboard/i);
},
play: copyResetLink,
};
/**
@@ -329,16 +191,7 @@ export const ResetLinkCopiedToast: Story = {
* confirming it.
*/
export const InviteLinkCopiedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: /invite link/i }, untilLoaded),
);
await userEvent.click(
await screen.findByRole('button', { name: /^copy$/i }, untilLoaded),
);
await screen.findByText(/invite link copied to clipboard/i);
},
play: copyInviteLink,
};
/**
@@ -347,14 +200,5 @@ export const InviteLinkCopiedToast: Story = {
*/
export const ResetLinkFailedToast: Story = {
args: { resetLink: 'no-token' },
play: async ({ canvasElement, args }): Promise<void> => {
await openResetLink(canvasElement);
if (args.resetLink === 'no-token') {
await waitFor(() =>
expect(
screen.getByText(/failed to generate password reset link/i),
).toBeVisible(),
);
}
},
play: failResetLink,
};

View File

@@ -0,0 +1,293 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
closeRoles,
membersMocks,
openInviteForm,
openInviteRoleDropdown,
openMember,
openResetLink,
pickOpenRole,
sendInvites,
untilLoaded,
} from '../Members.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof membersMocks>;
}
const openStatusFilter = async (canvasElement: HTMLElement): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/all members/i,
undefined,
untilLoaded,
),
);
};
export const openFilterMenu = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openStatusFilter(canvasElement);
await screen.findByText(/pending invites/i, undefined, untilLoaded);
};
export const filterPendingOnly = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openStatusFilter(canvasElement);
await userEvent.click(
await screen.findByText(/^pending invites/i, undefined, untilLoaded),
);
// One badge per pending row.
await screen.findAllByText('INVITED', undefined, untilLoaded);
};
export const filterDeletedOnly = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openStatusFilter(canvasElement);
await userEvent.click(
// The unfiltered table already shows a DELETED badge, so the menu option
// is matched on its own count suffix.
await screen.findByText(/^deleted ⎯/i, undefined, untilLoaded),
);
await screen.findAllByText('DELETED', undefined, untilLoaded);
};
export const searchNoResults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.type(
await within(canvasElement).findByPlaceholderText(
/search by name or email/i,
undefined,
untilLoaded,
),
'no-such-member',
);
await screen.findByText(/no results for/i, undefined, untilLoaded);
};
export const openEditMember = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await screen.findByPlaceholderText(/enter name/i, undefined, untilLoaded);
};
export const openPendingMember = async ({
canvasElement,
}: Pick<PlayContext, 'canvasElement'>): Promise<void> => {
await openMember(canvasElement, /podrick payne/i);
await screen.findByText(/invited on/i, undefined, untilLoaded);
};
export const openDeleteMemberConfirm = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await userEvent.click(
await screen.findByRole('button', { name: 'Delete Member' }),
);
await screen.findByRole('dialog', { name: 'Delete Member' });
};
export const openRevokeInviteConfirm = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: 'Revoke Invite' }),
);
await screen.findByRole('dialog', { name: 'Revoke Invite' });
};
export const openAssignRoles = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
// The dropdown opens off the inner combobox, not the wrapper the click lands on first.
await userEvent.click(await screen.findByRole('combobox'));
await screen.findByText('oncall-responder', undefined, untilLoaded);
};
export const openInviteMembers = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openInviteForm(canvasElement);
};
export const openInviteRoles = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openInviteForm(canvasElement);
await openInviteRoleDropdown(0);
await screen.findAllByText('viewer', undefined, untilLoaded);
};
export const selectInviteRoles = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openInviteForm(canvasElement);
await openInviteRoleDropdown(0);
for (const role of ['viewer', 'editor', 'oncall-responder']) {
await pickOpenRole(role);
}
await closeRoles();
// The open list titles its options too, so the check is scoped to the selected tags.
await waitFor(
() =>
expect(
document.querySelector(
'.ant-select-selection-item[title="oncall-responder"]',
),
).toBeVisible(),
untilLoaded,
);
};
export const sendInvitesToAll = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@nightswatch.io',
]);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
);
}
};
export const sendInvitesPartiallyRefused = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@blocked.example',
]);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/some invites failed/i)).toBeVisible(),
);
}
};
export const saveMemberName = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
const name = await screen.findByPlaceholderText(
/enter name/i,
undefined,
untilLoaded,
);
await waitFor(() => expect(name).toHaveValue('Jon Snow'), untilLoaded);
await userEvent.type(name, ' Targaryen');
await userEvent.click(
await screen.findByRole('button', { name: 'Save Member Details' }),
);
if (args.memberUpdate === 'success') {
await waitFor(() =>
expect(
screen.getByText(/member details updated successfully/i),
).toBeVisible(),
);
}
};
export const deleteMember = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await openMember(canvasElement, /jon snow/i);
await userEvent.click(
await screen.findByRole('button', { name: 'Delete Member' }),
);
const dialog = await screen.findByRole('dialog', {
name: 'Delete Member',
});
await userEvent.click(
within(dialog).getByRole('button', { name: 'Delete Member' }),
);
if (args.memberDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/member deleted successfully/i)).toBeVisible(),
);
}
};
export const revokeInvite = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: 'Revoke Invite' }),
);
const dialog = await screen.findByRole('dialog', {
name: 'Revoke Invite',
});
await userEvent.click(
within(dialog).getByRole('button', { name: 'Revoke Invite' }),
);
if (args.memberDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/invite revoked successfully/i)).toBeVisible(),
);
}
};
export const copyResetLink = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openResetLink(canvasElement);
await userEvent.click(
await screen.findByRole('button', { name: /^copy$/i }, untilLoaded),
);
await screen.findByText(/reset link copied to clipboard/i);
};
export const copyInviteLink = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await openPendingMember({ canvasElement });
await userEvent.click(
await screen.findByRole('button', { name: /invite link/i }, untilLoaded),
);
await userEvent.click(
await screen.findByRole('button', { name: /^copy$/i }, untilLoaded),
);
await screen.findByText(/invite link copied to clipboard/i);
};
export const failResetLink = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await openResetLink(canvasElement);
if (args.resetLink === 'no-token') {
await waitFor(() =>
expect(
screen.getByText(/failed to generate password reset link/i),
).toBeVisible(),
);
}
};

View File

@@ -100,6 +100,10 @@ export const workspaceMocks = defineStoryMocks({
)
: res(ctx.status(204));
}),
rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: { redirectURL: '' } })),
),
],
config: () => ({ route: ROUTES.SETTINGS }),
});

View File

@@ -1,9 +1,14 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
copyLicenseKey,
openAddCreditCardFromConflict,
openCustomDomainMenu,
updateCustomDomain,
} from './__story_mockdata__/workspace.play';
import { workspaceMocks } from './Workspace.stories.mocks';
import SettingsPage from '../../Settings';
@@ -61,16 +66,7 @@ export const NoColdStorage: Story = {
* of them is the active one.
*/
export const CustomDomainMenu: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'custom-domain-menu-trigger',
{},
{ timeout: 10000 },
),
);
await screen.findByRole('menu');
},
play: openCustomDomainMenu,
};
/**
@@ -79,38 +75,21 @@ export const CustomDomainMenu: Story = {
* instead.
*/
export const CustomDomainUpdatedToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /edit workspace link/i },
{ timeout: 10000 },
),
);
const input = await screen.findByRole('textbox');
await userEvent.clear(input);
await userEvent.type(input, 'watchers');
await userEvent.click(
await screen.findByRole('button', { name: /apply changes/i }),
);
if (args.domainUpdate === 'success') {
await waitFor(() =>
expect(screen.getByText(/workspace url is being updated/i)).toBeVisible(),
);
}
},
play: updateCustomDomain,
};
/**
* A workspace link change the instance refuses with a 409: the edit modal swaps
* Apply Changes for Contact Support, which on a cloud trial without a card opens
* the Add Credit Card modal.
*/
export const CustomDomainConflictAddCard: Story = {
args: { domainUpdate: 'error', support: 'add-card' },
parameters: { allowConsoleErrors: true },
play: openAddCreditCardFromConflict,
};
/** The license key copied: the toast confirming it. */
export const LicenseKeyCopiedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'license-key-row-copy-btn',
{},
{ timeout: 10000 },
),
);
await screen.findByText(/license key copied to clipboard/i);
},
play: copyLicenseKey,
};

View File

@@ -0,0 +1,109 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { USER_ROLES } from 'types/roles';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { accessFor } from '@/storybook/access/access';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { workspaceMocks } from '../Workspace.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof workspaceMocks>;
}
const untilLoaded = { timeout: 10000 };
/** The domain card only renders for an admin on cloud. */
const canEditDomain = ({ args }: Pick<PlayContext, 'args'>): boolean =>
args.license === 'cloud' &&
accessFor(args.access, args.permissions, args.revoked).legacyRole ===
USER_ROLES.ADMIN;
const submitNewSubdomain = async (
canvasElement: HTMLElement,
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /edit workspace link/i },
untilLoaded,
),
);
const input = await screen.findByRole('textbox');
await userEvent.clear(input);
await userEvent.type(input, 'watchers');
await userEvent.click(
await screen.findByRole('button', { name: /apply changes/i }),
);
};
export const openCustomDomainMenu = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'custom-domain-menu-trigger',
undefined,
untilLoaded,
),
);
await screen.findByRole('menu');
};
export const updateCustomDomain = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await submitNewSubdomain(canvasElement);
if (args.domainUpdate === 'success') {
await waitFor(() =>
expect(screen.getByText(/workspace url is being updated/i)).toBeVisible(),
);
}
};
export const copyLicenseKey = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'license-key-row-copy-btn',
undefined,
untilLoaded,
),
);
await screen.findByText(/license key copied to clipboard/i);
};
export const openAddCreditCardFromConflict = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canEditDomain({ args })) {
return;
}
await submitNewSubdomain(canvasElement);
if (args.domainUpdate !== 'error') {
return;
}
await userEvent.click(
await screen.findByRole('button', { name: /contact support/i }, untilLoaded),
);
// Only a plan without premium support is offered the modal over the chat widget.
if (args.support === 'add-card') {
await screen.findByRole(
'dialog',
{ name: /Add Credit Card for Chat Support/i },
untilLoaded,
);
}
};

View File

@@ -32,6 +32,7 @@ import {
timeSeriesPoints,
} from '@/storybook/msw/__story_mockdata__/queryRange';
import { traceFunnelsResponse } from '../../TracesModulePage/stories/__story_mockdata__/traces';
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
import {
focusSpanIndex,
@@ -221,6 +222,11 @@ export const traceDetailsMocks = defineStoryMocks({
}),
),
rest.get(
'http://localhost/api/v1/trace-funnels/list',
response.json(() => traceFunnelsResponse(3)),
),
rest.post(
'http://localhost/api/v1/span_percentile',
response.json(spanPercentilesResponse),

View File

@@ -248,6 +248,72 @@ export const SpanPercentileOpen: Story = {
},
};
/** Spans the backend never received, shown as the missing-spans callout. */
export const MissingSpans: Story = {
args: { missingSpans: true },
play: async (): Promise<void> => {
await screen.findByText(
/this trace has missing spans/i,
undefined,
untilLoaded,
);
},
};
/** The analytics panel the header toggle opens. */
export const AnalyticsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Analytics' },
untilLoaded,
),
);
await screen.findByTestId('trace-analytics-panel', undefined, untilLoaded);
},
};
/** The download progress panel, held open by an export that never answers. */
export const TraceDownload: Story = {
args: { exportState: 'loading' },
play: async ({ canvasElement }): Promise<void> => {
await startDownload(canvasElement);
await screen.findByTestId('trace-download-panel', undefined, untilLoaded);
},
};
const openAddSpanToFunnel = async (
canvasElement: HTMLElement,
): Promise<void> => {
const [button] = await within(canvasElement).findAllByTestId(
'span-add-to-funnel-btn',
undefined,
untilLoaded,
);
await fireEvent.click(button);
await screen.findByText('Add span to funnel', undefined, untilLoaded);
};
/** The funnel picker a span row's add-to-funnel action opens. */
export const AddSpanToFunnel: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openAddSpanToFunnel(canvasElement);
},
};
/** The name field behind "Create new funnel" in that picker. */
export const AddSpanToFunnelCreateStep: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openAddSpanToFunnel(canvasElement);
await userEvent.click(
await screen.findByRole('button', { name: /create new funnel/i }),
);
await screen.findByTestId('create-funnel-name-input');
},
};
/** The span has no logs of its own but its trace does, so the Logs tab points to the trace's. */
export const SpanPanelTraceOnlyLogs: Story = {
args: { traceOnlyLogs: true },

View File

@@ -123,6 +123,43 @@ export const Funnels: Story = {
args: { tab: 'funnels' },
};
/** The name field for a funnel that does not exist yet. */
export const CreateFunnel: Story = {
args: { tab: 'funnels' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /new funnel/i },
untilLoaded,
),
);
await screen.findByRole('dialog', { name: /create new funnel/i });
},
};
/** The rename field for a funnel already on the list. */
export const RenameFunnel: Story = {
args: { tab: 'funnels' },
play: async ({ canvasElement }): Promise<void> => {
const action = await waitFor(() => {
const found = canvasElement.querySelector<HTMLElement>(
'.funnel-item__action-icon',
);
if (!found) {
throw new Error('Funnel row actions are not rendered');
}
return found;
}, untilLoaded);
await userEvent.click(action);
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }));
await screen.findByRole('dialog', { name: /rename funnel/i });
},
};
/**
* A fresh workspace: nothing ingested in the window and no quick filters
* configured yet, so the table and the filter panel both show their empty

View File

@@ -64,6 +64,70 @@ export const LongMultilineToast: Story = {
},
};
/** A request still in flight: the loading toast stays until the promise settles. */
export const PromiseLoadingToast: Story = {
args: { state: 'promise-loading-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Enabling the alert rule'),
).toBeVisible();
},
};
/** A failed request: the rejected toast keeps a Dismiss action, stacked top-center. */
export const PromiseErrorToast: Story = {
args: { state: 'promise-error-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Could not clone the panel'),
).toBeVisible();
await screen.findByRole('button', { name: 'Dismiss' });
},
};
/** A warning that stays up, matching invites that only partly succeed. */
export const WarningToast: Story = {
args: { state: 'warning-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(await screen.findByText('Some invites failed')).toBeVisible();
},
};
/** An info toast pinned to the bottom-right stack, as export cancellation does. */
export const InfoToast: Story = {
args: { state: 'info-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(await screen.findByText('Export cancelled')).toBeVisible();
},
};
/** An error toast with a description and a Dismiss action, bottom-right. */
export const DangerWithDescription: Story = {
args: { state: 'danger-description-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Failed to update account settings'),
).toBeVisible();
await screen.findByText(/does not have permission/i);
await screen.findByRole('button', { name: 'Dismiss' });
},
};
/** Mutation: the inline application alert preserves its action affordance. */
export const InlineAlert: Story = {
args: { state: 'inline-alert' },

View File

@@ -10,6 +10,11 @@ export type FeedbackState =
| 'success-toast'
| 'actionable-error-toast'
| 'long-toast'
| 'promise-loading-toast'
| 'promise-error-toast'
| 'warning-toast'
| 'info-toast'
| 'danger-description-toast'
| 'inline-alert'
| 'confirmation'
| 'toast-over-confirmation';
@@ -21,6 +26,10 @@ interface FeedbackFixtureProps {
const longMessage =
'We could not apply the retention policy because the selected storage tier is unavailable. Review the workspace settings, then try again.';
const pendingSave = new Promise<void>(() => undefined);
const dismissAction = { label: 'Dismiss', onClick: (): void => undefined };
function FeedbackFixture({ state }: FeedbackFixtureProps): JSX.Element {
const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);
@@ -37,13 +46,62 @@ function FeedbackFixture({ state }: FeedbackFixtureProps): JSX.Element {
return;
}
if (state === 'promise-loading-toast') {
toast.promise(pendingSave, {
loading: 'Enabling the alert rule',
success: 'Alert rule enabled',
error: 'Could not enable the alert rule',
});
return;
}
if (state === 'promise-error-toast') {
toast.promise(Promise.reject(new Error('failed')), {
loading: 'Cloning the panel',
success: 'Panel cloned',
error: { message: 'Could not clone the panel', action: dismissAction },
position: 'top-center',
duration: Infinity,
});
return;
}
if (state === 'warning-toast') {
toast.warning('Some invites failed', { duration: Infinity });
return;
}
if (state === 'info-toast') {
toast.info('Export cancelled', {
position: 'bottom-right',
duration: Infinity,
});
return;
}
if (state === 'danger-description-toast') {
toast.error('Failed to update account settings', {
description:
'The service account does not have permission to change this connection.',
action: dismissAction,
position: 'bottom-right',
duration: Infinity,
});
return;
}
toast.error(longMessage, { duration: Infinity });
};
const isToastStory =
state === 'success-toast' ||
state === 'actionable-error-toast' ||
state === 'long-toast';
state === 'long-toast' ||
state === 'promise-loading-toast' ||
state === 'promise-error-toast' ||
state === 'warning-toast' ||
state === 'info-toast' ||
state === 'danger-description-toast';
const confirmationTitle = 'Delete environment';
return (

View File

@@ -30,7 +30,7 @@ func (provider *provider) addQuerierRoutes(router *mux.Router) error {
Description: "Execute a composite query over a time range. Supports builder queries (traces, logs, metrics), formulas, trace operators, PromQL, and ClickHouse SQL.",
Request: new(qbtypes.QueryRangeRequest),
RequestContentType: "application/json",
RequestExamples: []handler.OpenAPIExample{
RequestExamples: append([]handler.OpenAPIExample{
{
Name: "traces_time_series",
Summary: "Time series: count spans grouped by service",
@@ -598,7 +598,7 @@ func (provider *provider) addQuerierRoutes(router *mux.Router) error {
},
},
},
},
}, queryRangeFunctionExamples()...),
Response: new(qbtypes.QueryRangeResponse),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,

View File

@@ -0,0 +1,202 @@
package signozapiserver
import "github.com/SigNoz/signoz/pkg/http/handler"
// timeSeriesExample wraps builder query specs in a one hour time series
// request, the shape every function example shares.
func timeSeriesExample(name, summary, description string, queries ...map[string]any) handler.OpenAPIExample {
list := make([]any, 0, len(queries))
for _, query := range queries {
list = append(list, query)
}
return handler.OpenAPIExample{
Name: name,
Summary: summary,
Description: description,
Value: map[string]any{
"schemaVersion": "v1",
"start": 1640995200000,
"end": 1640998800000,
"requestType": "time_series",
"compositeQuery": map[string]any{"queries": list},
},
}
}
func builderQueryEnvelope(spec map[string]any) map[string]any {
return map[string]any{"type": "builder_query", "spec": spec}
}
// function builds a function entry with positional arguments; anomaly is the
// one function that takes named arguments and is written out in full.
func function(name string, args ...any) map[string]any {
list := make([]any, 0, len(args))
for _, arg := range args {
list = append(list, map[string]any{"value": arg})
}
entry := map[string]any{"name": name}
if len(list) > 0 {
entry["args"] = list
}
return entry
}
// queryRangeFunctionExamples shows every function a builder query can carry,
// what its arguments mean and the values they take. Functions run in the
// order listed, after the aggregation and before formulas.
func queryRangeFunctionExamples() []handler.OpenAPIExample {
return []handler.OpenAPIExample{
timeSeriesExample(
"function_timeshift_week_over_week",
"timeShift: this week's error logs next to last week's",
"timeShift moves every point of its query forward by the argument, in seconds, so a series read from the past lands on the current timestamps. B here reads the hour exactly seven days (604800 s) before the requested window and comes back on this week's timestamps, so it overlays A on a chart and the formula can subtract it point by point. The argument is positive; it says how far back to read.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "logs",
"aggregations": []any{map[string]any{"expression": "count()", "alias": "errors"}},
"stepInterval": "60s",
"filter": map[string]any{"expression": "severity_text = 'ERROR'"},
}),
builderQueryEnvelope(map[string]any{
"name": "B",
"signal": "logs",
"aggregations": []any{map[string]any{"expression": "count()", "alias": "errors"}},
"stepInterval": "60s",
"filter": map[string]any{"expression": "severity_text = 'ERROR'"},
"functions": []any{function("timeShift", 604800)},
}),
map[string]any{
"type": "builder_formula",
"spec": map[string]any{"name": "F1", "expression": "A - B"},
},
),
timeSeriesExample(
"function_fillzero_sparse_errors",
"fillZero: a zero at every step with no failed spans",
"A count over sparse events returns a point only for steps that had a match, so a chart of failed spans has gaps where nothing failed. fillZero adds a zero at every missing step. With no arguments the server fills the request window at the query's step, which is the common case. The three optional arguments are start, end and step in milliseconds, for callers that want to fill a different grid.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "traces",
"aggregations": []any{map[string]any{"expression": "count()", "alias": "failed_spans"}},
"stepInterval": "60s",
"filter": map[string]any{"expression": "has_error = true"},
"groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},
"functions": []any{function("fillZero")},
}),
),
timeSeriesExample(
"function_cutoffmin_hide_idle_hosts",
"cutOffMin: drop hosts below 5% CPU from the chart",
"The four threshold functions take one number. cutOffMin and cutOffMax remove the points below or above the threshold, so an idle host disappears from the chart instead of drawing a line along the bottom. clampMin and clampMax keep the points and replace the value with the threshold, which caps spikes without hiding them. system.cpu.utilization is a ratio, so 0.05 is 5%.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "system.cpu.utilization", "timeAggregation": "avg", "spaceAggregation": "avg"},
},
"stepInterval": "60s",
"groupBy": []any{map[string]any{"name": "host.name", "fieldContext": "resource"}},
"functions": []any{function("cutOffMin", 0.05)},
}),
),
timeSeriesExample(
"function_runningdiff_disk_growth",
"runningDiff then clampMin: bytes written to disk per step",
"runningDiff turns a gauge into the change between consecutive points, so a filesystem usage gauge becomes bytes written per step. It takes no arguments and drops the first point of the window, since that point has nothing to difference against; the server reads one step before the window to keep the first interval. Functions apply in order: clampMin with 0 runs on the differences and replaces the negative value a cleanup or a volume reset produces with zero.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "system.filesystem.usage", "timeAggregation": "latest", "spaceAggregation": "sum"},
},
"stepInterval": "60s",
"filter": map[string]any{"expression": "state = 'used'"},
"groupBy": []any{map[string]any{"name": "host.name", "fieldContext": "resource"}},
"functions": []any{function("runningDiff"), function("clampMin", 0)},
}),
),
timeSeriesExample(
"function_ewma_smoothed_latency",
"ewma5: smoothed p95 latency",
"ewma3, ewma5 and ewma7 replace each point with an exponentially weighted average of the point and the points before it. The number in the name is the window the default weight is derived from: alpha = 2 / (n + 1), so 0.5, 0.333 and 0.25. One optional argument overrides alpha; a value close to 1 follows the raw series, a value close to 0 smooths harder. 0.3 here smooths a little more than ewma5's default.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "http.server.duration.bucket", "spaceAggregation": "p95"},
},
"stepInterval": "60s",
"groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},
"functions": []any{function("ewma5", 0.3)},
}),
),
timeSeriesExample(
"function_median_despiked_request_rate",
"median5: request rate without one-step spikes",
"median3, median5 and median7 replace each point with the median of the surrounding 3, 5 or 7 points. A spike that lasts one step vanishes, a shift that lasts longer than half the window stays. The first and last half window, 2 points each for median5, have no full window and keep their values, so the newest spike stays visible; a series shorter than the window is returned unchanged. They take no arguments. Use them when the raw series is noisy and the chart is for a trend, not for catching the spike.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum"},
},
"stepInterval": "60s",
"groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},
"functions": []any{function("median5")},
}),
),
timeSeriesExample(
"function_cumulativesum_errors_so_far",
"cumulativeSum: 5xx responses since the start of the window",
"cumulativeSum replaces each point with the sum of every point up to and including it, so a per-step count becomes a running total whose first point is the first count. It takes no arguments. The total resets with the window, so a longer time range gives a larger final value; it is a view of the window, not a counter.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "traces",
"aggregations": []any{map[string]any{"expression": "count()", "alias": "server_errors"}},
"stepInterval": "60s",
"filter": map[string]any{"expression": "http.response.status_code >= 500"},
"groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},
"functions": []any{function("cumulativeSum")},
}),
),
timeSeriesExample(
"function_log10_network_bytes",
"log10: network throughput across devices that differ by orders of magnitude",
"log2 and log10 replace each value with its logarithm, so a loopback device moving kilobytes and an uplink moving gigabytes fit on one chart. They take no arguments. Zero and negative values have no logarithm and are not drawn. absolute, also without arguments, is the usual companion for a signed series before a logarithm.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "system.network.io", "timeAggregation": "rate", "spaceAggregation": "sum"},
},
"stepInterval": "60s",
"filter": map[string]any{"expression": "direction = 'transmit'"},
"groupBy": []any{map[string]any{"name": "device", "fieldContext": "attribute"}},
"functions": []any{function("log10")},
}),
),
timeSeriesExample(
"function_anomaly_request_rate",
"anomaly: request rate scored against its daily pattern",
"anomaly is the one function with named arguments. seasonality says which past periods predict the current value: hourly, daily or weekly, daily when absent. z_score_threshold is how many standard deviations from the prediction count as an anomaly. It has no default: a request without it gets bounds of zero width, so send it. 3 is the value the UI sends. The response carries, next to the values, a predicted series, an upper and a lower bound series and an anomaly score series. The scoring runs in the enterprise build; the community build returns the series unchanged.",
builderQueryEnvelope(map[string]any{
"name": "A",
"signal": "metrics",
"aggregations": []any{
map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum"},
},
"stepInterval": "300s",
"groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},
"functions": []any{
map[string]any{
"name": "anomaly",
"args": []any{
map[string]any{"name": "seasonality", "value": "daily"},
map[string]any{"name": "z_score_threshold", "value": 3},
},
},
},
}),
),
}
}

View File

@@ -0,0 +1,23 @@
package signozapiserver
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
func TestQueryRangeFunctionExamplesAreValidRequests(t *testing.T) {
for _, example := range queryRangeFunctionExamples() {
t.Run(example.Name, func(t *testing.T) {
raw, err := json.Marshal(example.Value)
require.NoError(t, err)
var req qbtypes.QueryRangeRequest
require.NoError(t, json.Unmarshal(raw, &req))
assert.NoError(t, req.Validate())
})
}
}

View File

@@ -9,12 +9,13 @@ import (
// NewValidReferences / NewSuggestionsOnLevenshteinDistance to phrase the
// "valid <noun> are ..." list consistently across the codebase.
const (
NounFields = "fields"
NounKeys = "keys"
NounServices = "services"
NounQueryTypes = "query types"
NounSignals = "signals"
NounReferences = "references"
NounFields = "fields"
NounKeys = "keys"
NounServices = "services"
NounQueryTypes = "query types"
NounRequestTypes = "request types"
NounSignals = "signals"
NounReferences = "references"
)
const (

View File

@@ -88,6 +88,13 @@ func (q *builderQuery[T]) Fingerprint() string {
return ""
}
// A limit ranks the groups over the statement window, so the pieces of a
// window rank differently from the window. Such a query is never served
// from the cache.
if (q.spec.Signal == telemetrytypes.SignalLogs || q.spec.Signal == telemetrytypes.SignalTraces) && len(q.spec.GroupBy) > 0 && q.spec.Limit > 0 {
return ""
}
// Create a deterministic fingerprint for builder queries
// This needs to include all fields that affect the query results
parts := []string{q.queryType.StringValue()}

View File

@@ -425,6 +425,12 @@ func (q *querier) processTimeSeriesFormula(
return nil
}
formulaSeries, err = applyFormulaHaving(formula, formulaSeries)
if err != nil {
q.logger.ErrorContext(ctx, "failed to apply formula having", errors.Attr(err), slog.String("formula", formula.Name))
return nil
}
// Create result for formula
formulaResult := &qbtypes.TimeSeriesData{
QueryName: formula.Name,
@@ -660,6 +666,12 @@ func (q *querier) processScalarFormula(
return nil
}
formulaSeries, err = applyFormulaHaving(formula, formulaSeries)
if err != nil {
q.logger.ErrorContext(ctx, "failed to apply formula having", errors.Attr(err), slog.String("formula", formula.Name))
return nil
}
// Apply ordering (and limit) before converting to scalar format.
formulaSeries = qbtypes.ApplySeriesLimit(formulaSeries, formula.Order, formula.Limit, formula.Offset)
@@ -710,6 +722,35 @@ func (q *querier) processScalarFormula(
}
}
// applyFormulaHaving keeps the values the formula having accepts, as SQL HAVING
// keeps rows for a builder query, so a series with no values left is removed. It
// runs before functions, order, limit, and offset, as HAVING runs before them in SQL.
func applyFormulaHaving(formula qbtypes.QueryBuilderFormula, series []*qbtypes.TimeSeries) ([]*qbtypes.TimeSeries, error) {
if formula.Having == nil || strings.TrimSpace(formula.Having.Expression) == "" {
return series, nil
}
keep, err := querybuilder.CompileFormulaHaving(formula.Name, formula.Having.Expression)
if err != nil {
return nil, err
}
kept := series[:0]
for _, s := range series {
values := s.Values[:0]
for _, value := range s.Values {
if keep(value.Value) {
values = append(values, value)
}
}
if len(values) > 0 {
s.Values = values
kept = append(kept, s)
}
}
return kept, nil
}
// filterDisabledQueries removes results for disabled queries.
func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]*qbtypes.Result {
filtered := make(map[string]*qbtypes.Result)

View File

@@ -212,6 +212,14 @@ func (q *querier) buildQueries(
}
switch query.Type {
case qbtypes.QueryTypeFormula:
// the querier evaluates a formula after its queries run, so a bad
// having must fail here, before they run
if formula, ok := query.Spec.(qbtypes.QueryBuilderFormula); ok && formula.Having != nil && strings.TrimSpace(formula.Having.Expression) != "" {
if _, err := querybuilder.CompileFormulaHaving(formula.Name, formula.Having.Expression); err != nil {
return nil, nil, err
}
}
case qbtypes.QueryTypePromQL:
promQuery, ok := query.Spec.(qbtypes.PromQuery)
if !ok {
@@ -922,32 +930,25 @@ func (q *querier) createRangedQuery(_ valuer.UUID, originalQuery qbtypes.Query,
copy(argsCopy, qt.args)
return newchSQLQuery(q.logger, q.telemetryStore, queryCopy, argsCopy, timeRange, qt.kind, qt.vars)
// A builder query's window was moved into the shifted clock when it was
// built, so a range taken from that window must not be shifted again.
case *builderQuery[qbtypes.TraceAggregation]:
specCopy := qt.spec.Copy()
specCopy.ShiftBy = extractShiftFromBuilderQuery(specCopy)
adjustedTimeRange := adjustTimeRangeForShift(specCopy, timeRange, qt.kind)
// reuse the original query's statement builder and type so an AI query
// keeps its AI builder and cache key
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, qt.stmtBuilder, qt.queryType, specCopy, adjustedTimeRange, qt.kind, qt.variables, qt.builderConfig)
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, qt.stmtBuilder, qt.queryType, qt.spec.Copy(), timeRange, qt.kind, qt.variables, qt.builderConfig)
case *builderQuery[qbtypes.LogAggregation]:
specCopy := qt.spec.Copy()
specCopy.ShiftBy = extractShiftFromBuilderQuery(specCopy)
adjustedTimeRange := adjustTimeRangeForShift(specCopy, timeRange, qt.kind)
shiftStmtBuilder := q.logStmtBuilder
if qt.spec.Source == telemetrytypes.SourceAudit {
shiftStmtBuilder = q.auditStmtBuilder
}
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, shiftStmtBuilder, qt.queryType, specCopy, adjustedTimeRange, qt.kind, qt.variables, q.builderConfig)
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, shiftStmtBuilder, qt.queryType, qt.spec.Copy(), timeRange, qt.kind, qt.variables, q.builderConfig)
case *builderQuery[qbtypes.MetricAggregation]:
specCopy := qt.spec.Copy()
specCopy.ShiftBy = extractShiftFromBuilderQuery(specCopy)
adjustedTimeRange := adjustTimeRangeForShift(specCopy, timeRange, qt.kind)
if qt.spec.Source == telemetrytypes.SourceMeter {
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, q.meterStmtBuilder, qt.queryType, specCopy, adjustedTimeRange, qt.kind, qt.variables, builderConfig{})
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, q.meterStmtBuilder, qt.queryType, qt.spec.Copy(), timeRange, qt.kind, qt.variables, builderConfig{})
}
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, q.metricStmtBuilder, qt.queryType, specCopy, adjustedTimeRange, qt.kind, qt.variables, builderConfig{})
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, q.metricStmtBuilder, qt.queryType, qt.spec.Copy(), timeRange, qt.kind, qt.variables, builderConfig{})
case *traceOperatorQuery:
specCopy := qt.spec.Copy()
return &traceOperatorQuery{

View File

@@ -0,0 +1,166 @@
package querybuilder
import (
"math"
"slices"
"strconv"
grammar "github.com/SigNoz/signoz/pkg/parser/havingexpression/grammar"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
// CompileFormulaHaving turns the having expression of a formula into a filter on
// its values. The querier computes a formula in Go after ClickHouse returns, so the
// having cannot run as SQL; it gets the same validation and messages as a
// builder-query having, with the formula name and __result as the only references.
func CompileFormulaHaving(formulaName, expression string) (func(value float64) bool, error) {
rewriter := &HavingExpressionRewriter{columnMap: map[string]string{
formulaName: qbtypes.DefaultOrderByKey,
qbtypes.DefaultOrderByKey: qbtypes.DefaultOrderByKey,
}}
_, tree, err := rewriter.parseAndValidate(expression)
if err != nil {
return nil, err
}
return compileOrExpression(tree.Expression().OrExpression()), nil
}
func compileOrExpression(ctx grammar.IOrExpressionContext) func(float64) bool {
andExpressions := ctx.AllAndExpression()
conditions := make([]func(float64) bool, len(andExpressions))
for i, andExpression := range andExpressions {
conditions[i] = compileAndExpression(andExpression)
}
return func(value float64) bool {
for _, condition := range conditions {
if condition(value) {
return true
}
}
return false
}
}
func compileAndExpression(ctx grammar.IAndExpressionContext) func(float64) bool {
primaries := ctx.AllPrimary()
conditions := make([]func(float64) bool, len(primaries))
for i, primary := range primaries {
conditions[i] = compilePrimary(primary)
}
return func(value float64) bool {
for _, condition := range conditions {
if !condition(value) {
return false
}
}
return true
}
}
func compilePrimary(ctx grammar.IPrimaryContext) func(float64) bool {
var condition func(float64) bool
if ctx.OrExpression() != nil {
condition = compileOrExpression(ctx.OrExpression())
} else {
condition = compileComparison(ctx.Comparison())
}
if ctx.NOT() == nil {
return condition
}
return func(value float64) bool { return !condition(value) }
}
func compileComparison(ctx grammar.IComparisonContext) func(float64) bool {
left := compileOperand(ctx.Operand(0))
if ctx.IN() != nil {
signedNumbers := ctx.InList().AllSignedNumber()
list := make([]float64, len(signedNumbers))
for i, signedNumber := range signedNumbers {
list[i] = parseHavingNumber(signedNumber.GetText())
}
notIn := ctx.NOT() != nil
return func(value float64) bool { return slices.Contains(list, left(value)) != notIn }
}
right := compileOperand(ctx.Operand(1))
compOp := ctx.CompOp()
switch {
case compOp.EQUALS() != nil:
return func(value float64) bool { return left(value) == right(value) }
case compOp.NOT_EQUALS() != nil, compOp.NEQ() != nil:
return func(value float64) bool { return left(value) != right(value) }
case compOp.LT() != nil:
return func(value float64) bool { return left(value) < right(value) }
case compOp.LE() != nil:
return func(value float64) bool { return left(value) <= right(value) }
case compOp.GT() != nil:
return func(value float64) bool { return left(value) > right(value) }
default:
return func(value float64) bool { return left(value) >= right(value) }
}
}
func compileOperand(ctx grammar.IOperandContext) func(float64) float64 {
if ctx.Operand() == nil {
return compileTerm(ctx.Term())
}
left := compileOperand(ctx.Operand())
right := compileTerm(ctx.Term())
if ctx.MINUS() != nil {
return func(value float64) float64 { return left(value) - right(value) }
}
return func(value float64) float64 { return left(value) + right(value) }
}
func compileTerm(ctx grammar.ITermContext) func(float64) float64 {
if ctx.Term() == nil {
return compileFactor(ctx.Factor())
}
left := compileTerm(ctx.Term())
right := compileFactor(ctx.Factor())
switch {
case ctx.SLASH() != nil:
return func(value float64) float64 { return left(value) / right(value) }
case ctx.PERCENT() != nil:
return func(value float64) float64 { return math.Mod(left(value), right(value)) }
default:
return func(value float64) float64 { return left(value) * right(value) }
}
}
func compileFactor(ctx grammar.IFactorContext) func(float64) float64 {
if ctx.Factor() != nil {
inner := compileFactor(ctx.Factor())
if ctx.MINUS() != nil {
return func(value float64) float64 { return -inner(value) }
}
return inner
}
if ctx.Operand() != nil {
return compileOperand(ctx.Operand())
}
if number := ctx.Atom().NUMBER(); number != nil {
constant := parseHavingNumber(number.GetText())
return func(float64) float64 { return constant }
}
// validation rejects function calls, strings, and unknown names, so the atom
// names the formula value
return func(value float64) float64 { return value }
}
// ParseFloat reads every form the lexer admits as a number; a literal outside the
// float64 range becomes the nearest value ParseFloat returns.
func parseHavingNumber(text string) float64 {
number, _ := strconv.ParseFloat(text, 64)
return number
}

View File

@@ -0,0 +1,86 @@
package querybuilder
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/errors"
)
func TestCompileFormulaHaving_Matches(t *testing.T) {
values := []float64{-2, 0, 1, 2.5, 3, 10}
testCases := []struct {
name string
expression string
want []float64
}{
{name: "Name_GreaterThan", expression: "F1 > 2", want: []float64{2.5, 3, 10}},
{name: "Result_LessOrEqual", expression: "__result <= 1", want: []float64{-2, 0, 1}},
{name: "DoubleEquals", expression: "F1 == 3", want: []float64{3}},
{name: "AngleNotEquals", expression: "F1 <> 0", want: []float64{-2, 1, 2.5, 3, 10}},
{name: "In_Parentheses", expression: "F1 IN (0, 3, -2)", want: []float64{-2, 0, 3}},
{name: "NotIn_Brackets", expression: "F1 NOT IN [0, 3, -2]", want: []float64{1, 2.5, 10}},
{name: "AndBindsTighterThanOr", expression: "F1 > 0 AND F1 < 3 OR F1 = -2", want: []float64{-2, 1, 2.5}},
{name: "ImplicitAnd", expression: "F1 > 0 F1 < 3", want: []float64{1, 2.5}},
{name: "LowercaseKeywords", expression: "F1 > 2 and not F1 = 10", want: []float64{2.5, 3}},
{name: "NotParenthesized", expression: "NOT (F1 >= 1 AND F1 <= 3)", want: []float64{-2, 0, 10}},
{name: "Arithmetic", expression: "F1 * 2 - 1 > 4", want: []float64{3, 10}},
{name: "Arithmetic_Parentheses", expression: "(F1 + 2) / 2 >= 2", want: []float64{2.5, 3, 10}},
{name: "Modulo", expression: "F1 % 2 = 1", want: []float64{1, 3}},
{name: "UnaryMinus", expression: "-F1 > 1", want: []float64{-2}},
{name: "Number_Exponent", expression: "F1 >= 1e1", want: []float64{10}},
{name: "Number_LeadingDot", expression: "F1 < .5", want: []float64{-2, 0}},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
keep, err := CompileFormulaHaving("F1", testCase.expression)
require.NoError(t, err)
require.NotNil(t, keep)
got := []float64{}
for _, value := range values {
if keep(value) {
got = append(got, value)
}
}
assert.Equal(t, testCase.want, got)
})
}
}
func TestCompileFormulaHaving_Invalid(t *testing.T) {
testCases := []struct {
name string
expression string
wantErrMsg string
wantAdditional []string
}{
{
name: "QueryName_NotAReference",
expression: "A > 0",
wantErrMsg: "Invalid references in `Having` expression: [A]",
wantAdditional: []string{"Valid references are: [F1, __result]"},
},
{
name: "Aggregation_NotAReference",
expression: "count() > 0",
wantErrMsg: "Invalid references in `Having` expression: [count]",
wantAdditional: []string{"Valid references are: [F1, __result]"},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
keep, err := CompileFormulaHaving("F1", testCase.expression)
require.Error(t, err)
assert.Nil(t, keep)
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
assert.ErrorContains(t, err, testCase.wantErrMsg)
assert.Equal(t, testCase.wantAdditional, additionalMessages(err))
})
}
}

View File

@@ -237,7 +237,13 @@ func (v *havingExpressionRewriteVisitor) visitIdentifier(ctx grammar.IIdentifier
return name
}
// rewriteAndValidate is the single-pass implementation used by all RewriteFor* methods.
func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string, error) {
rewritten, _, err := r.parseAndValidate(expression)
return rewritten, err
}
// parseAndValidate is the single-pass implementation used by all RewriteFor* methods.
// It also returns the parse tree, which CompileFormulaHaving evaluates in Go.
//
// Validation layers:
// 1. The visitor runs on the parse tree, rewriting and collecting invalid references.
@@ -248,7 +254,7 @@ func (v *havingExpressionRewriteVisitor) visitIdentifier(ctx grammar.IIdentifier
// 2. String literals in comparison-operand position → descriptive error
// ("aggregator results are numeric").
// 3. ANTLR syntax errors → error with messages referencing the original token names.
func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string, error) {
func (r *HavingExpressionRewriter) parseAndValidate(expression string) (string, grammar.IQueryContext, error) {
original := strings.TrimSpace(expression)
// Parse the expression once.
@@ -281,7 +287,7 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string
// This is checked before invalid references so that "contains string literals" takes
// priority when a bare string literal is also an unresolvable operand.
if v.hasStringLiteral {
return "", errors.NewInvalidInputf(
return "", nil, errors.NewInvalidInputf(
errors.CodeInvalidInput,
"`Having` expression contains string literals",
).WithAdditional("Aggregator results are numeric")
@@ -317,7 +323,7 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string
).WithAdditional(
"Valid references are: [" + strings.Join(validKeys, ", ") + "]",
).WithSuggestions(suggestions...)
return "", havingErr
return "", nil, havingErr
}
// Layer 3 – ANTLR syntax errors. We parse the original expression, so error messages
@@ -343,12 +349,12 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string
return havingSuggestion(allSyntaxErrors[0], original)
})
return "", havingErr.WithSuggestiveAdditional(msgs[0], suggestions...)
return "", nil, havingErr.WithSuggestiveAdditional(msgs[0], suggestions...)
}
return "", havingErr.WithAdditional(msgs...)
return "", nil, havingErr.WithAdditional(msgs...)
}
return result, nil
return result, tree, nil
}
// havingSuggestion returns a corrected expression string to show as a suggestion when

View File

@@ -28,7 +28,7 @@ type QueryBuilderFormula struct {
Offset int `json:"offset,omitempty" description:"The number of ordered series or rows to skip before the page starts. Requires limit."`
Having *Having `json:"having,omitempty" description:"Accepted but currently ignored; the computed values are returned unfiltered."`
Having *Having `json:"having,omitempty" description:"A filter on the formula values, referencing the formula by its name or as __result, for example F1 > 0. A time series keeps only the points that match and drops a series with none left; a scalar result keeps only the rows that match."`
Functions []Function `json:"functions,omitzero" description:"Post-processing functions applied in order to each result series."`
@@ -118,6 +118,10 @@ func (f QueryBuilderFormula) Validate() error {
)
}
if f.Limit < 0 {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "limit must be non-negative, got %d", f.Limit)
}
// Validate functions if present
for i, fn := range f.Functions {
if err := fn.Validate(); err != nil {

View File

@@ -23,7 +23,8 @@ func (r *RequestType) UnmarshalJSON(data []byte) error {
*r = v
return nil
default:
return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown request type %q; allowed values: %s", s, "`scalar`, `time_series`, `raw`, `raw_stream`, `trace`, `distribution`, `heatmap`")
return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown request type %q", s).
WithSuggestions(errors.NewValidReferences(errors.NounRequestTypes, RequestType{}.Enum()...))
}
}

View File

@@ -499,6 +499,18 @@ func (q *QueryBuilderQuery[T]) validateOrderBy(cfg validationConfig) error {
return q.validateOrderByForAggregation()
}
// a raw order key resolves like a select field, so only an empty one is
// invalid before resolution
for i, order := range q.Order {
if order.Key.Name == "" {
orderID := fmt.Sprintf("order by clause #%d", i+1)
if q.Name != "" {
orderID = fmt.Sprintf("order by clause #%d in query '%s'", i+1, q.Name)
}
return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid empty key name for %s", orderID)
}
}
return nil
}
@@ -586,19 +598,10 @@ func (r *QueryRangeRequest) Validate(opts ...ValidationOption) error {
return err
}
// Validate request type
switch r.RequestType {
case RequestTypeRaw, RequestTypeRawStream, RequestTypeTrace, RequestTypeTimeSeries, RequestTypeScalar, RequestTypeHeatmap, RequestTypeDistribution:
opts = append(opts, GetValidationOptions(r.RequestType)...)
default:
return errors.NewInvalidInputf(
errors.CodeInvalidInput,
"invalid request type: %s",
r.RequestType,
).WithAdditional(
"Valid request types are: raw, timeseries, scalar, heatmap, distribution",
)
if err := r.validateRequestType(); err != nil {
return err
}
opts = append(opts, GetValidationOptions(r.RequestType)...)
if err := r.validateBucketCounting(); err != nil {
return err
@@ -639,14 +642,10 @@ func (r *QueryRangeRequest) ValidateRequestScope() ([]ValidationOption, error) {
return nil, err
}
var opts []ValidationOption
switch r.RequestType {
case RequestTypeRaw, RequestTypeRawStream, RequestTypeTrace, RequestTypeTimeSeries, RequestTypeScalar, RequestTypeHeatmap, RequestTypeDistribution:
opts = GetValidationOptions(r.RequestType)
default:
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid request type: %s", r.RequestType).
WithAdditional("Valid request types are: raw, timeseries, scalar, heatmap, distribution")
if err := r.validateRequestType(); err != nil {
return nil, err
}
opts := GetValidationOptions(r.RequestType)
if err := r.validateBucketCounting(); err != nil {
return nil, err
@@ -703,6 +702,20 @@ func (e QueryEnvelope) Validate(opts ...ValidationOption) error {
return validateQueryEnvelope(e, opts...)
}
// Enum is the one list of request types a query can use, so the spec and the
// suggestions agree with what is accepted.
func (r *QueryRangeRequest) validateRequestType() error {
if slices.Contains(RequestType{}.Enum(), any(r.RequestType)) {
return nil
}
if r.RequestType == RequestTypeUnknown {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "requestType is required").
WithSuggestions(errors.NewValidReferences(errors.NounRequestTypes, RequestType{}.Enum()...))
}
return errors.NewInvalidInputf(errors.CodeInvalidInput, "request type %q is not supported", r.RequestType.StringValue()).
WithSuggestions(errors.NewValidReferences(errors.NounRequestTypes, RequestType{}.Enum()...))
}
func (r *QueryRangeRequest) validateTimeRange() error {
if r.RequestType == RequestTypeRawStream {
return nil

View File

@@ -1,9 +1,15 @@
package querybuildertypesv5
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/metrictypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
@@ -521,6 +527,28 @@ func TestQueryRangeRequest_ValidateCompositeQuery(t *testing.T) {
wantErr: true,
errMsg: "expression cannot be blank",
},
{
name: "Formula_NegativeLimit_Rejected",
request: QueryRangeRequest{
Start: 1640995200000,
End: 1640998800000,
RequestType: RequestTypeTimeSeries,
CompositeQuery: CompositeQuery{
Queries: []QueryEnvelope{
{
Type: QueryTypeFormula,
Spec: QueryBuilderFormula{
Name: "F1",
Expression: "A * 2",
Limit: -5,
},
},
},
},
},
wantErr: true,
errMsg: "invalid formula 'F1': limit must be non-negative, got -5",
},
{
name: "promql with empty query should return error",
request: QueryRangeRequest{
@@ -696,6 +724,31 @@ func TestQueryRangeRequest_ValidateCompositeQuery(t *testing.T) {
wantErr: true,
errMsg: "raw request type is not supported for metric queries",
},
{
name: "Raw_EmptyOrderKey_Rejected",
request: QueryRangeRequest{
Start: 1640995200000,
End: 1640998800000,
RequestType: RequestTypeRaw,
CompositeQuery: CompositeQuery{
Queries: []QueryEnvelope{
{
Type: QueryTypeBuilder,
Spec: QueryBuilderQuery[LogAggregation]{
Name: "B",
Signal: telemetrytypes.SignalLogs,
Order: []OrderBy{
{Key: OrderByKey{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "timestamp"}}, Direction: OrderDirectionDesc},
{Key: OrderByKey{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: ""}}, Direction: OrderDirectionAsc},
},
},
},
},
},
},
wantErr: true,
errMsg: "invalid query 'B': invalid empty key name for order by clause #2 in query 'B'",
},
{
name: "timeseries request with group by timestamp should return error",
request: QueryRangeRequest{
@@ -1407,6 +1460,44 @@ func TestRequestType_IsAggregation(t *testing.T) {
}
}
func TestQueryRangeRequest_ValidateRequestType(t *testing.T) {
validRequestTypes := []string{"valid request types are `scalar`, `time_series`, `raw`, `raw_stream`, `trace`, `heatmap`, `distribution`"}
testCases := []struct {
name string
requestType string
message string
}{
{
name: "Missing_Required",
requestType: "",
message: "requestType is required",
},
{
name: "Timeseries_Unknown",
requestType: `"requestType": "timeseries",`,
message: `unknown request type "timeseries"`,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
body := fmt.Sprintf(`{"schemaVersion": "v1", "start": 1640995200000, "end": 1640998800000, %s "compositeQuery": {"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "logs"}}]}}`, testCase.requestType)
var request QueryRangeRequest
err := json.Unmarshal([]byte(body), &request)
if err == nil {
err = request.Validate()
}
require.Error(t, err)
got := errors.AsJSON(err)
assert.Equal(t, testCase.message, got.Message)
assert.Equal(t, validRequestTypes, got.Suggestions)
})
}
}
func TestNonAggregationFieldsSkipped(t *testing.T) {
// Fields that only apply to aggregation queries (groupBy, having, aggregations)
// should be silently skipped for non-aggregation request types.

View File

@@ -363,6 +363,7 @@ def build_formula_query(
order: list[dict] | None = None,
limit: int | None = None,
offset: int | None = None,
having_expression: str | None = None,
) -> dict:
spec: dict[str, Any] = {
"name": name,
@@ -379,6 +380,8 @@ def build_formula_query(
spec["limit"] = limit
if offset is not None:
spec["offset"] = offset
if having_expression:
spec["having"] = {"expression": having_expression}
return {"type": "builder_formula", "spec": spec}

View File

@@ -0,0 +1,86 @@
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
from uuid import uuid4
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.logs import Logs
from fixtures.querier import (
build_aggregation,
build_function,
build_group_by_field,
build_scalar_query,
get_all_series,
index_series_by_label,
make_query_request,
)
MINUTE = timedelta(minutes=1)
def test_time_shift_partial_hit_matches_no_cache(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_logs: Callable[[list[Logs]], None],
) -> None:
"""
The hour before the shifted one holds different counts, so a gap read
one shift too far back returns wrong points instead of nothing.
"""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
# the cache outlives the run, so a fixed filter would serve the previous
# run's points back to this one
run = uuid4().hex[:8]
insert_logs(
[
Logs(
timestamp=now - 120 * MINUTE + minute * MINUTE + timedelta(seconds=1 + i),
resources={"service.name": service},
attributes={"run": run},
body=f"{service} {minute} {i}",
)
for minute in range(60)
for service, count in (("svc-a", 4), ("svc-b", 2))
for i in range(count)
]
+ [
Logs(
timestamp=now - 180 * MINUTE + minute * MINUTE + timedelta(seconds=1 + i),
resources={"service.name": service},
attributes={"run": run},
body=f"{service} earlier {minute} {i}",
)
for minute in range(60)
for service, count in (("svc-a", 9), ("svc-b", 7))
for i in range(count)
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query = build_scalar_query(
name="A",
signal="logs",
aggregations=[build_aggregation("count()")],
group_by=[build_group_by_field("service.name", "string", "resource")],
filter_expression=f"run = '{run}'",
step_interval=60,
functions=[build_function("timeShift", 3600)],
)
start_ms = int((now - 60 * MINUTE).timestamp() * 1000)
first_end_ms = int((now - 30 * MINUTE).timestamp() * 1000)
second_end_ms = int((now - 10 * MINUTE).timestamp() * 1000)
warm = make_query_request(signoz, token, start_ms, first_end_ms, [query], no_cache=False)
assert warm.status_code == HTTPStatus.OK, warm.text
cached = make_query_request(signoz, token, start_ms, second_end_ms, [query], no_cache=False)
assert cached.status_code == HTTPStatus.OK, cached.text
fresh = make_query_request(signoz, token, start_ms, second_end_ms, [query], no_cache=True)
assert fresh.status_code == HTTPStatus.OK, fresh.text
fresh_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(fresh.json(), "A"), "service.name").items()}
assert set(fresh_points) == {"svc-a", "svc-b"}, fresh_points
assert {service: len(points) for service, points in fresh_points.items()} == {"svc-a": 50, "svc-b": 50}
cached_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(cached.json(), "A"), "service.name").items()}
assert cached_points == fresh_points

View File

@@ -0,0 +1,135 @@
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
from uuid import uuid4
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.logs import Logs
from fixtures.querier import (
build_aggregation,
build_group_by_field,
build_order_by,
build_scalar_query,
get_all_series,
index_series_by_label,
make_query_request,
)
MINUTE = timedelta(minutes=1)
def test_limited_group_by_partial_hit_matches_no_cache(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_logs: Callable[[list[Logs]], None],
) -> None:
"""
The two halves have different winners, so a limit applied per cached
piece returns the union of both instead of the window's top two.
"""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
# the cache outlives the run, so a fixed filter would serve the previous
# run's points back to this one
run = uuid4().hex[:8]
head_start = now - 60 * MINUTE
insert_logs(
[
Logs(
timestamp=head_start + minute * MINUTE + timedelta(seconds=1 + i),
resources={"service.name": service},
attributes={"run": run},
body=f"{service} {minute} {i}",
)
for minute in range(40)
for service, count in (("svc-a", 10 if minute < 20 else 1), ("svc-b", 8 if minute < 20 else 1), ("svc-c", 1 if minute < 20 else 10), ("svc-d", 1 if minute < 20 else 8))
for i in range(count)
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query = build_scalar_query(
name="A",
signal="logs",
aggregations=[build_aggregation("count()")],
group_by=[build_group_by_field("service.name", "string", "resource")],
order=[build_order_by("count()", "desc")],
limit=2,
filter_expression=f"run = '{run}'",
step_interval=60,
)
head_start_ms = int(head_start.timestamp() * 1000)
head_end_ms = int((head_start + 20 * MINUTE).timestamp() * 1000)
tail_end_ms = int((head_start + 40 * MINUTE).timestamp() * 1000)
warm = make_query_request(signoz, token, head_start_ms, head_end_ms, [query], no_cache=False)
assert warm.status_code == HTTPStatus.OK, warm.text
cached = make_query_request(signoz, token, head_start_ms, tail_end_ms, [query], no_cache=False)
assert cached.status_code == HTTPStatus.OK, cached.text
fresh = make_query_request(signoz, token, head_start_ms, tail_end_ms, [query], no_cache=True)
assert fresh.status_code == HTTPStatus.OK, fresh.text
fresh_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(fresh.json(), "A"), "service.name").items()}
assert set(fresh_points) == {"svc-a", "svc-c"}, fresh_points
assert {service: len(points) for service, points in fresh_points.items()} == {"svc-a": 40, "svc-c": 40}
cached_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(cached.json(), "A"), "service.name").items()}
assert cached_points == fresh_points
def test_limited_group_by_shrunk_window_matches_no_cache(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_logs: Callable[[list[Logs]], None],
) -> None:
"""
svc-a wins the full window and svc-b wins its second half, so a cache
that keeps the window's winner serves the wrong series for the half.
"""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
# the cache outlives the run, so a fixed filter would serve the previous
# run's points back to this one
run = uuid4().hex[:8]
start = now - 40 * MINUTE
insert_logs(
[
Logs(
timestamp=start + minute * MINUTE + timedelta(seconds=1 + i),
resources={"service.name": service},
attributes={"run": run},
body=f"{service} {minute} {i}",
)
for minute in range(10)
for service, count in (("svc-a", 20 if minute < 5 else 1), ("svc-b", 1 if minute < 5 else 10))
for i in range(count)
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query = build_scalar_query(
name="A",
signal="logs",
aggregations=[build_aggregation("count()")],
group_by=[build_group_by_field("service.name", "string", "resource")],
order=[build_order_by("count()", "desc")],
limit=1,
filter_expression=f"run = '{run}'",
step_interval=60,
)
start_ms = int(start.timestamp() * 1000)
middle_ms = int((start + 5 * MINUTE).timestamp() * 1000)
end_ms = int((start + 10 * MINUTE).timestamp() * 1000)
warm = make_query_request(signoz, token, start_ms, end_ms, [query], no_cache=False)
assert warm.status_code == HTTPStatus.OK, warm.text
cached = make_query_request(signoz, token, middle_ms, end_ms, [query], no_cache=False)
assert cached.status_code == HTTPStatus.OK, cached.text
fresh = make_query_request(signoz, token, middle_ms, end_ms, [query], no_cache=True)
assert fresh.status_code == HTTPStatus.OK, fresh.text
fresh_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(fresh.json(), "A"), "service.name").items()}
assert set(fresh_points) == {"svc-b"}, fresh_points
assert sorted(fresh_points["svc-b"].values()) == [10] * 5, fresh_points
cached_points = {service: {point["timestamp"]: point["value"] for point in series["values"]} for service, series in index_series_by_label(get_all_series(cached.json(), "A"), "service.name").items()}
assert cached_points == fresh_points

View File

@@ -2,6 +2,8 @@ from collections.abc import Callable
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.logs import Logs
@@ -12,6 +14,9 @@ from fixtures.querier import (
build_order_by,
build_scalar_query,
find_named_result,
get_all_series,
get_error_message,
index_series_by_label,
make_query_request,
)
@@ -191,3 +196,138 @@ def test_logs_formula_orderby_and_limit(
assert len(f3_services) == 3, f"F3: expected 3 rows after limit, got {len(f3_services)}"
assert f3_values == f4_values[:3], f"F3 values {f3_values} do not match F4[:3] values {f4_values[:3]}"
assert set(f3_services) == set(f4_services[:3]), f"F3 services {f3_services} do not match F4[:3] services {f4_services[:3]}"
# Logs per service at 5, 4, 3, 2, and 1 minutes before now. Totals: a 15, b 17, c 5, d 15.
FORMULA_HAVING_COUNTS = {
"service-a": [1, 4, 2, 5, 3],
"service-b": [6, 1, 1, 2, 7],
"service-c": [1, 1, 1, 1, 1],
"service-d": [3, 3, 3, 3, 3],
}
@pytest.mark.parametrize(
"query_having,formula_having,expected_services",
[
pytest.param("count() > 4 AND count() < 16", "F1 > 4 AND F1 < 16", {"service-a", "service-b"}, id="and_range"),
pytest.param("count() IN (1, 5, 17) OR count() > 15", "__result IN (1, 5, 17) OR __result > 15", {"service-a", "service-b", "service-c"}, id="in_or"),
pytest.param("NOT (count() * 2 - 1 > 9)", "NOT (F1 * 2 - 1 > 9)", {"service-a", "service-b", "service-c", "service-d"}, id="not_arithmetic"),
],
)
def test_logs_formula_having_time_series_matches_query_having(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_logs: Callable[[list[Logs]], None],
query_having: str,
formula_having: str,
expected_services: set[str],
) -> None:
"""
The querier computes formulas in Go, so a formula having runs in Go. For the
formula `A`, it must keep the same points that SQL HAVING keeps on query A.
"""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
insert_logs([Logs(timestamp=now - timedelta(minutes=5 - minute), resources={"service.name": service}, body=f"{service} log {minute}-{i}") for service, counts in FORMULA_HAVING_COUNTS.items() for minute, count in enumerate(counts) for i in range(count)])
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
group_by = [build_group_by_field("service.name", "string", "resource")]
response = make_query_request(
signoz,
token,
start_ms=int((now - timedelta(minutes=15)).timestamp() * 1000),
end_ms=int(now.timestamp() * 1000),
request_type="time_series",
queries=[
build_scalar_query(name="A", signal="logs", aggregations=[build_aggregation("count()")], group_by=group_by, disabled=True),
build_scalar_query(name="B", signal="logs", aggregations=[build_aggregation("count()")], group_by=group_by, having_expression=query_having),
build_formula_query("F1", "A", having_expression=formula_having),
],
)
assert response.status_code == HTTPStatus.OK, response.text
query_series = index_series_by_label(get_all_series(response.json(), "B"), "service.name")
formula_series = index_series_by_label(get_all_series(response.json(), "F1"), "service.name")
assert set(formula_series) == expected_services
assert set(query_series) == expected_services
for service in expected_services:
query_points = sorted((value["timestamp"], value["value"]) for value in query_series[service]["values"])
formula_points = sorted((value["timestamp"], value["value"]) for value in formula_series[service]["values"])
assert formula_points == query_points, service
@pytest.mark.parametrize(
"query_having,formula_having,expected_services",
[
pytest.param("count() > 4 AND count() < 16", "F1 > 4 AND F1 < 16", {"service-a", "service-c", "service-d"}, id="and_range"),
pytest.param("count() IN (1, 5, 17) OR count() > 15", "__result IN (1, 5, 17) OR __result > 15", {"service-b", "service-c"}, id="in_or"),
pytest.param("NOT (count() * 2 - 1 > 9)", "NOT (F1 * 2 - 1 > 9)", {"service-c"}, id="not_arithmetic"),
],
)
def test_logs_formula_having_scalar_matches_query_having(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_logs: Callable[[list[Logs]], None],
query_having: str,
formula_having: str,
expected_services: set[str],
) -> None:
"""
For the formula `A` in a scalar request, the formula having must keep the
same rows that SQL HAVING keeps on query A.
"""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
insert_logs([Logs(timestamp=now - timedelta(minutes=5 - minute), resources={"service.name": service}, body=f"{service} log {minute}-{i}") for service, counts in FORMULA_HAVING_COUNTS.items() for minute, count in enumerate(counts) for i in range(count)])
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
group_by = [build_group_by_field("service.name", "string", "resource")]
response = make_query_request(
signoz,
token,
start_ms=int((now - timedelta(minutes=15)).timestamp() * 1000),
end_ms=int(now.timestamp() * 1000),
request_type="scalar",
queries=[
build_scalar_query(name="A", signal="logs", aggregations=[build_aggregation("count()")], group_by=group_by, disabled=True),
build_scalar_query(name="B", signal="logs", aggregations=[build_aggregation("count()")], group_by=group_by, having_expression=query_having),
build_formula_query("F1", "A", having_expression=formula_having),
],
)
assert response.status_code == HTTPStatus.OK, response.text
results = response.json()["data"]["data"]["results"]
values_by_query = {}
for name in ("B", "F1"):
result = find_named_result(results, name)
assert result is not None, name
service_column = next(i for i, column in enumerate(result["columns"]) if column["name"] == "service.name")
value_column = next(i for i, column in enumerate(result["columns"]) if column["columnType"] == "aggregation")
values_by_query[name] = {row[service_column]: row[value_column] for row in result["data"]}
assert set(values_by_query["F1"]) == expected_services
assert values_by_query["F1"] == values_by_query["B"]
def test_logs_formula_having_invalid_reference(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
"""A formula having can reference only the formula value, so `count()` is a bad request."""
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = make_query_request(
signoz,
token,
start_ms=int((now - timedelta(minutes=15)).timestamp() * 1000),
end_ms=int(now.timestamp() * 1000),
request_type="time_series",
queries=[
build_scalar_query(name="A", signal="logs", aggregations=[build_aggregation("count()")], disabled=True),
build_formula_query("F1", "A", having_expression="count() > 0"),
],
)
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
assert get_error_message(response.json()) == "Invalid references in `Having` expression: [count]"

View File

@@ -128,6 +128,15 @@ request_types = pytest.mark.parametrize(
"having is not supported for {request_type} requests",
id="having_on_the_query",
),
pytest.param(
[
build_builder_query("A", METRIC_NAME, "max", "max", disabled=True),
build_formula_query("F1", "A", having_expression="F1 > 1"),
],
{},
"having is not supported for {request_type} requests",
id="having_on_the_formula",
),
pytest.param(
[build_builder_query("A", METRIC_NAME, "max", "max", bucket_options={"kind": "quadratic", "spec": {}})],
{},