Compare commits

...

3 Commits

Author SHA1 Message Date
Ashu Ghildiyal
677ee4502d fix(alerts): let the empty rules page scroll to the sample alerts 2026-11-17 17:20:59 +05:30
Naman Verma
2a96645af6 fix(rules): keep rule labels from overriding engine labels (#13612)
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
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

A rule label named threshold.name or severity replaced the value the
evaluator stamped. Rule Labels aren't supposed to be treated in a
special way like this.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

Part of https://github.com/SigNoz/pulse-pod/issues/653
2026-11-17 10:33:44 +00:00
hardik-signoz
900796a573 test(e2e): cover users FGA on the members page (#13615)
#### Description

- Adds `members.spec.ts` TC-04 to TC-07, each running as a member
holding only a custom role:
  - TC-04: `list:user` without `create:user`, invite button denied
- TC-05: no `list:user`, list shows "not authorized" and search is
denied
- TC-06: invited member without `factor-password:list`, "Invite Link
Unavailable"
- TC-07: self edit, adds then removes a role (needs `attach` and
`detach` on user and role)
- Drivers: `guestSettings` fixture (settings pages on the signed-in
guest page), `createGrantedUser` seed, members locators, `addRole` and
`removeRole`.
- Unit, story and integration tests already cover the rest of Users FGA,
see the plan on the issue.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#212

#### Additional Information

- Each spec was checked by granting the missing permission and
confirming it fails.
- Run locally against hosted staging backend with the local frontend
(`--no-deps`). Not run on the pytest bootstrap stack.
2026-11-17 06:54:50 +00:00
15 changed files with 390 additions and 27 deletions

View File

@@ -11992,8 +11992,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:
@@ -12110,8 +12111,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:

View File

@@ -267,9 +267,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.Labels().Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -13156,7 +13156,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13273,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13306,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13365,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

@@ -1,12 +1,14 @@
.alertListContainer {
margin-top: auto;
margin-bottom: auto;
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
justify-content: center;
width: 100%;
}
.alertListViewContent {
margin: auto;
padding: 24px 0;
width: calc(100% - 30px);
max-width: 836px;
}

View File

@@ -201,9 +201,7 @@ func (r *PromRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel)
resultLabels := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel).Labels()
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.labels.Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -278,9 +278,7 @@ func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.labels.Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -71,7 +71,7 @@ type PostableRule struct {
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
RuleCondition *RuleCondition `json:"condition" required:"true" description:"The query to evaluate and the thresholds applied to its result."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored."`
Annotations map[string]string `json:"annotations,omitempty" description:"Free text attached to every alert, conventionally summary and description. Values may use Go templates with $value, $threshold and $labels."`
Disabled bool `json:"disabled" description:"Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false."`

View File

@@ -31,6 +31,23 @@ const (
AlertDescriptionLabel = "description"
)
// reservedLabelNames are written by the rule engine; a rule label with one of
// these names never reaches the alert.
var reservedLabelNames = map[string]struct{}{
MetricNameLabel: {},
TemporalityLabel: {},
AlertNameLabel: {},
AlertRuleIDLabel: {},
RuleSourceLabel: {},
NoDataLabel: {},
LabelThresholdName: {},
LabelSeverityName: {},
LabelLastSeen: {},
// TODO: the template layer reads is_recovering but nothing writes it;
// set it from Alert.IsRecovering.
LabelIsRecovering: {},
}
// Label is a key/value pair of strings.
// TODO(srikanthccv): https://github.com/SigNoz/signoz/issues/9232?
type Label struct {
@@ -285,6 +302,20 @@ func (b *Builder) Set(n, v string) *Builder {
return b
}
// SetRuleLabels adds the rule's labels, each expanded, skipping the names the
// engine writes.
// TODO: a rule label still overwrites a query result label of the same name;
// decide whether those are locked too.
func (b *Builder) SetRuleLabels(ruleLabels map[string]string, expand func(string) string) *Builder {
for name, value := range ruleLabels {
if _, reserved := reservedLabelNames[name]; reserved {
continue
}
b.Set(name, expand(value))
}
return b
}
// Labels returns the labels from the builder. If no modifications
// were made, the original labels are returned.
func (b *Builder) Labels() Labels {

View File

@@ -131,14 +131,23 @@ export interface Settings {
/** The member's table row. Search for the email first: the list pages at 20. */
row(email: string): Locator;
inviteButton(): Locator;
searchInput(): Locator;
resetLinkButton(): Locator;
/** The "is not authorized" message a denied list or drawer renders. */
deniedMessage(): Locator;
openInvite(): Promise<void>;
inviteDialog(): Locator;
invite(rows: { email: string; role: string }[]): Promise<void>;
openMember(email: string): Promise<void>;
drawer(): Locator;
nameInput(): Locator;
roleSelect(): Locator;
deleteButton(): Locator;
setRoles(roles: string[]): Promise<void>;
/** Add a role to the open member without clearing the others. */
addRole(role: string): Promise<void>;
/** Remove one role from the open member, leaving the others. */
removeRole(role: string): Promise<void>;
saveMember(): Promise<void>;
/** Mint a reset or invite link from the drawer and return it. */
generateLink(): Promise<string>;
@@ -414,6 +423,9 @@ export function settingsDriver(page: Page): Settings {
// antd keys each row by the member id; the email is what callers hold.
row: (email) => page.locator('tr[data-row-key]').filter({ hasText: email }),
inviteButton: () => page.getByTestId('invite-member-btn'),
searchInput: () => page.getByTestId('members-search-input'),
resetLinkButton: () => page.getByTestId('member-reset-link-btn'),
deniedMessage: () => page.getByText(/is not authorized/).first(),
openInvite: async () => {
await settings.members.inviteButton().click();
await expect(settings.members.inviteDialog()).toBeVisible();
@@ -449,6 +461,7 @@ export function settingsDriver(page: Page): Settings {
await expect(settings.members.drawer().getByText(email)).toBeVisible();
},
drawer: () => page.getByRole('dialog', { name: 'Member Details' }),
nameInput: () => page.getByPlaceholder('Enter name'),
roleSelect: () => selectById('member-role'),
deleteButton: () => page.getByTestId('member-delete-btn'),
setRoles: async (roles) => {
@@ -458,6 +471,21 @@ export function settingsDriver(page: Page): Settings {
await pickInDialog(settings.members.drawer(), select, role);
}
},
addRole: async (role) => {
await pickInDialog(
settings.members.drawer(),
settings.members.roleSelect(),
role,
);
},
removeRole: async (role) => {
await settings.members
.roleSelect()
.locator('.ant-select-selection-item')
.filter({ hasText: role })
.locator('.ant-select-selection-item-remove')
.click();
},
saveMember: async () => {
await page.getByTestId('member-save-btn').click();
await expect(

View File

@@ -1,7 +1,7 @@
import { withAuthFlows } from '../auth-flows';
import { kit } from '../kit';
import { guestDriver, kit, type Layer } from '../kit';
import { withSettings } from './driver';
import { settingsDriver, withSettings, type Settings } from './driver';
import {
withActiveEditor,
withCustomRoleSeed,
@@ -9,6 +9,12 @@ import {
withServiceAccountSeed,
} from './seeds';
/** The settings pages bound to the logged-out `guestPage`, for a signed-in member. */
const withGuestSettings: Layer<{ guestSettings: Settings }> = guestDriver(
'guestSettings',
({ page }) => settingsDriver(page),
);
/**
* The settings `test`. Seeds are test-scoped and lazy: a spec pays only for the
* ones it destructures. `authFlows` drives a guest context, for the flows that
@@ -16,8 +22,10 @@ import {
*/
export const test = withAuthFlows(
withSettings(
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
withGuestSettings(
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
),
),
),
);

View File

@@ -1,9 +1,11 @@
import type { Browser, TestType } from '@playwright/test';
import type { User } from '../auth';
import type { AuthtypesTransactionGroupDTO } from '../schemas';
import { onAdminPage, type Layer } from '../kit';
import { usersApi, type CreatedUser } from '../users';
import { grantAll, roleName, settingsDriver } from './driver';
import { grantAll, roleName, settingsDriver, type Settings } from './driver';
/**
* Test-scoped seeds. Each test that asks for one gets its own copy, created on
@@ -123,3 +125,40 @@ export const withActiveEditor = perTest(
({ browser, value }) =>
onAdminPage(browser, (page) => usersApi(page).remove(value.id)),
);
export interface GrantedUser {
user: User;
role: string;
remove(): Promise<void>;
}
/**
* An active member whose only role is a fresh custom role holding
* `transactionGroups`. Call `remove` in a `finally`.
*/
export async function createGrantedUser(
settings: Settings,
workerIndex: number,
kind: string,
transactionGroups: AuthtypesTransactionGroupDTO[],
): Promise<GrantedUser> {
const name = roleName(kind, workerIndex);
const roleId = await settings.roles.createApi({ name, transactionGroups });
const label = `${kind}-w${workerIndex}-${Date.now()}`;
let member: CreatedUser;
try {
member = await settings.users.createActive(name, label);
} catch (error) {
await settings.users.removeByEmail(`e2e-${label}@signoz.test`);
await settings.roles.removeApi(roleId);
throw error;
}
return {
user: member.user,
role: name,
remove: async () => {
await settings.users.remove(member.id);
await settings.roles.removeApi(roleId);
},
};
}

View File

@@ -1,4 +1,9 @@
import { expect, test } from '../../drivers/settings';
import {
createGrantedUser,
expect,
grantAll,
test,
} from '../../drivers/settings';
test.describe('settings — members', () => {
test('TC-01 an invite of two rows creates two pending members', async ({
@@ -62,4 +67,163 @@ test.describe('settings — members', () => {
await settings.members.search(email);
await expect(settings.members.row(email)).toContainText('DELETED');
});
test('TC-04 a user without create:user cannot invite members', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'list-users',
[grantAll('list', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await expect(guestSettings.members.inviteButton()).toHaveAttribute(
'data-denied-permissions',
/create/,
);
} finally {
await member.remove();
}
});
test('TC-05 a user without list:user cannot list members', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-list',
[grantAll('read', 'dashboard')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await expect(guestSettings.members.deniedMessage()).toBeVisible();
await expect(guestSettings.members.searchInput()).toHaveAttribute(
'data-denied-permissions',
/list/,
);
} finally {
await member.remove();
}
});
test('TC-06 an invite link is unavailable without factor-password:list', async ({
settings,
authFlows,
guestSettings,
pendingMember,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-pwd',
[grantAll('list', 'user', 'user'), grantAll('read', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(pendingMember.email);
await expect(guestSettings.members.resetLinkButton()).toHaveAttribute(
'data-denied-permissions',
/factor-password/,
);
await expect(guestSettings.members.resetLinkButton()).toContainText(
'Invite Link Unavailable',
);
} finally {
await member.remove();
}
});
test('TC-07 a member can add and remove a role on themselves', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'self-edit',
[
grantAll('list', 'user', 'user'),
grantAll('read', 'user', 'user'),
grantAll('attach', 'user', 'user'),
grantAll('detach', 'user', 'user'),
grantAll('list', 'role', 'role'),
grantAll('read', 'role', 'role'),
grantAll('attach', 'role', 'role'),
grantAll('detach', 'role', 'role'),
],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(member.user.email);
await guestSettings.members.addRole('signoz-viewer');
await guestSettings.members.saveMember();
await guestSettings.reload();
await guestSettings.members.openMember(member.user.email);
await expect(guestSettings.members.roleSelect()).toContainText(
'signoz-viewer',
);
const added = await settings.users.byEmail(member.user.email);
expect(
(added?.userRoles ?? []).map((entry) => entry.role.name).sort(),
).toEqual([member.role, 'signoz-viewer'].sort());
await guestSettings.members.removeRole('signoz-viewer');
await guestSettings.members.saveMember();
await guestSettings.reload();
await guestSettings.members.openMember(member.user.email);
await expect(guestSettings.members.roleSelect()).not.toContainText(
'signoz-viewer',
);
const removed = await settings.users.byEmail(member.user.email);
expect((removed?.userRoles ?? []).map((entry) => entry.role.name)).toEqual([
member.role,
]);
} finally {
await member.remove();
}
});
test('TC-08 a user without update:user cannot rename another member', async ({
settings,
authFlows,
guestSettings,
activeEditor,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-update',
[grantAll('list', 'user', 'user'), grantAll('read', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(activeEditor.user.email);
await expect(guestSettings.members.nameInput()).toHaveAttribute(
'data-denied-permissions',
/update/,
);
} finally {
await member.remove();
}
});
});

View File

@@ -0,0 +1,12 @@
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:01:00+00:00","value":1,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:02:00+00:00","value":2,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:03:00+00:00","value":4,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:04:00+00:00","value":4,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:05:00+00:00","value":15,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:06:00+00:00","value":10,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:07:00+00:00","value":36,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:08:00+00:00","value":25,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:09:00+00:00","value":37,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:10:00+00:00","value":35,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:11:00+00:00","value":39,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:12:00+00:00","value":25,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}

View File

@@ -0,0 +1,57 @@
{
"alert": "reserved_labels_from_engine",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "clickhouse_sql",
"panelType": "graph",
"queries": [
{
"type": "clickhouse_sql",
"spec": {
"name": "A",
"query": "WITH __temporal_aggregation_cte AS (\n SELECT \n fingerprint, \n toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(60)) AS ts, \n avg(value) AS per_series_value \n FROM signoz_metrics.distributed_samples_v4 AS points \n INNER JOIN (\n SELECT fingerprint \n FROM signoz_metrics.time_series_v4 \n WHERE metric_name IN ('request_total_reserved_labels_from_engine') \n AND LOWER(temporality) LIKE LOWER('cumulative') \n GROUP BY fingerprint\n ) AS filtered_time_series ON points.fingerprint = filtered_time_series.fingerprint \n WHERE metric_name IN ('request_total_reserved_labels_from_engine') \n AND unix_milli >= $start_timestamp_ms \n AND unix_milli < $end_timestamp_ms \n GROUP BY fingerprint, ts \n ORDER BY fingerprint, ts\n), \n__spatial_aggregation_cte AS (\n SELECT \n ts, \n sum(per_series_value) AS value \n FROM __temporal_aggregation_cte \n WHERE isNaN(per_series_value) = 0 \n GROUP BY ts\n) \nSELECT * FROM __spatial_aggregation_cte \nORDER BY ts"
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {"threshold.name": "spoofed", "severity": "spoofed", "team": "payments"},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -543,6 +543,32 @@ TEST_RULES_MISCELLANEOUS = [
],
),
),
# the rule carries threshold.name and severity labels of its own; the alert
# keeps the values the engine wrote and only the plain label comes through
types.AlertTestCase(
name="test_rule_labels_do_not_override_engine_labels",
rule_path="ruler/test_scenarios/reserved_labels_from_engine/rule.json",
alert_data=[
types.AlertData(
type="metrics",
data_path="ruler/test_scenarios/reserved_labels_from_engine/alert_data.jsonl",
),
],
alert_expectation=types.AlertExpectation(
should_alert=True,
wait_time_seconds=30,
expected_alerts=[
types.FiringAlert(
labels={
"alertname": "reserved_labels_from_engine",
"threshold.name": "critical",
"severity": "critical",
"team": "payments",
}
),
],
),
),
# TODO: @abhishekhugetech enable the test for multi threshold rule, pylint: disable=W0511
# after the [issue](https://github.com/SigNoz/engineering-pod/issues/3934) with alertManager is resolved
# types.AlertTestCase(