Compare commits

..

2 Commits

Author SHA1 Message Date
Naman Verma
cd694e61c4 chore: no need for an extra interface 2026-11-23 14:44:08 +05:30
Naman Verma
08bc95df8e feat: add support for scalar queries in rules 2026-11-23 14:19:43 +05:30
49 changed files with 1010 additions and 602 deletions

View File

@@ -94,7 +94,7 @@ jobs:
postgres:15 \
clickhouse/clickhouse-server:25.12.5 \
clickhouse/clickhouse-keeper:25.12.5 \
signoz/signoz-otel-collector:v0.144.17 \
signoz/signoz-otel-collector:v0.144.16-rc.1 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,18 +85,13 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.17
- v0.144.16-rc.1
postgres-version:
- 15
exclude:
- sqlstore-provider: postgres
clickhouse-version: 26.8.34
if: |
((github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))) && contains(github.event.pull_request.labels.*.name, 'safe-to-integrate')
continue-on-error: ${{ matrix.clickhouse-version == '26.8.34' }}
runs-on: ubuntu-latest
steps:
- name: checkout

View File

@@ -474,14 +474,6 @@ auditor:
compression: lz4
# The maximum time to drain buffered events on shutdown. Undelivered events are dropped after it.
shutdown_timeout: 30s
tls:
# Whether to connect to the brokers over TLS.
enabled: false
# The PEM CA bundle that verifies broker certificates. Empty uses the system roots.
ca_file: ""
# The client certificate and key, for brokers that require client auth. Set both or neither.
cert_file: ""
key_file: ""
##################### Cloud Integration #####################
cloudintegration:

View File

@@ -11651,8 +11651,11 @@ components:
panelType:
allOf:
- $ref: '#/components/schemas/RuletypesPanelType'
description: 'The panel the UI renders the queries with: graph, table or
value. Use graph for alerts.'
description: 'How the queries are evaluated. graph runs them as time series
and matchType decides which points must satisfy op. table and value run
them as scalar: one value per group over the whole evaluation window,
compared directly, so matchType has no effect and metric aggregations
need reduceTo. promql queries and anomaly_rule support graph only.'
queries:
description: 'The queries to evaluate, at least one. Every envelope type
must match queryType: builder_query and builder_formula for builder, promql

View File

@@ -2,10 +2,7 @@ package kafkaauditor
import (
"context"
"crypto/tls"
"crypto/x509"
"log/slog"
"os"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/plugin/kslog"
@@ -13,7 +10,6 @@ import (
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/auditor/auditorserver"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/types/audittypes"
@@ -43,25 +39,13 @@ func newProvider(_ context.Context, providerSettings factory.ProviderSettings, c
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
opts := []kgo.Opt{
client, err := kgo.NewClient(
kgo.SeedBrokers(config.Kafka.Brokers...),
kgo.ClientID(config.Kafka.ClientID),
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
kgo.ProducerLinger(0),
kgo.WithLogger(kslog.New(settings.Logger())),
}
if config.Kafka.TLS.Enabled {
tlsConfig, err := newTLSConfig(config.Kafka.TLS)
if err != nil {
return nil, err
}
// franz-go sets ServerName per broker from the dialed address.
opts = append(opts, kgo.DialTLSConfig(tlsConfig))
}
client, err := kgo.NewClient(opts...)
)
if err != nil {
return nil, err
}
@@ -146,30 +130,3 @@ func compressionCodec(name string) kgo.CompressionCodec {
return kgo.NoCompression()
}
}
func newTLSConfig(config auditor.TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{}
if config.CAFile != "" {
caPEM, err := os.ReadFile(config.CAFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot read auditor::kafka::tls::ca_file")
}
tlsConfig.RootCAs = x509.NewCertPool()
if !tlsConfig.RootCAs.AppendCertsFromPEM(caPEM) {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "auditor::kafka::tls::ca_file %q holds no PEM certificate", config.CAFile)
}
}
if config.CertFile != "" {
cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot load auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return tlsConfig, nil
}

View File

@@ -1,269 +0,0 @@
package kafkaauditor
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/twmb/franz-go/pkg/kfake"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/types/audittypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/version"
)
func TestExport_MutualTLS(t *testing.T) {
certificates := newTestCertificates(t)
cluster, err := kfake.NewCluster(
kfake.NumBrokers(1),
kfake.SeedTopics(1, "tls_audit"),
kfake.TLS(&tls.Config{
Certificates: []tls.Certificate{certificates.server},
ClientCAs: certificates.caPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}),
)
require.NoError(t, err)
t.Cleanup(cluster.Close)
testCases := []struct {
name string
tls auditor.TLSConfig
err bool
}{
{
name: "CAAndClientCertificate_Delivers",
tls: certificates.client,
},
{
name: "TLSDisabled_Fails",
tls: auditor.TLSConfig{},
err: true,
},
{
name: "WithoutClientCertificate_Fails",
tls: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
err: true,
},
{
name: "WithoutCA_Fails",
tls: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
config := auditor.Config{
Provider: "kafka",
BufferSize: 10,
BatchSize: 5,
FlushInterval: 50 * time.Millisecond,
Kafka: auditor.KafkaConfig{
Brokers: cluster.ListenAddrs(),
Topic: "tls_audit",
ClientID: "signoz-tls-test",
Compression: "lz4",
ShutdownTimeout: 30 * time.Second,
TLS: testCase.tls,
},
}
auditor, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, version.Info)
require.NoError(t, err)
provider := auditor.(*provider)
defer provider.client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = provider.export(ctx, []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, testCase.name)})
if testCase.err {
assert.True(t, errors.Is(err, context.DeadlineExceeded))
return
}
require.NoError(t, err)
})
}
consumerTLS, err := newTLSConfig(certificates.client)
require.NoError(t, err)
consumer, err := kgo.NewClient(
kgo.SeedBrokers(cluster.ListenAddrs()...),
kgo.DialTLSConfig(consumerTLS),
kgo.ConsumeTopics("tls_audit"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
require.NoError(t, err)
defer consumer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fetches := consumer.PollFetches(ctx)
require.Empty(t, fetches.Errors())
assert.Len(t, fetches.Records(), 1)
}
func TestNewTLSConfig(t *testing.T) {
certificates := newTestCertificates(t)
notPEMFile := filepath.Join(t.TempDir(), "not-pem.crt")
require.NoError(t, os.WriteFile(notPEMFile, []byte("not a pem"), 0o600))
testCases := []struct {
name string
config auditor.TLSConfig
err bool
wantRootCAs bool
wantCertificates int
}{
{
name: "NoFiles_UsesSystemRoots",
config: auditor.TLSConfig{Enabled: true},
},
{
name: "CAOnly",
config: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
wantRootCAs: true,
},
{
name: "CAAndClientCertificate",
config: certificates.client,
wantRootCAs: true,
wantCertificates: 1,
},
{
name: "CAFileMissing",
config: auditor.TLSConfig{Enabled: true, CAFile: filepath.Join(t.TempDir(), "missing-ca.crt")},
err: true,
},
{
name: "CAFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CAFile: notPEMFile},
err: true,
},
{
name: "KeyFileMissing",
config: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: filepath.Join(t.TempDir(), "missing.key")},
err: true,
},
{
name: "CertFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CertFile: notPEMFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tlsConfig, err := newTLSConfig(testCase.config)
if testCase.err {
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
return
}
require.NoError(t, err)
assert.Equal(t, testCase.wantRootCAs, tlsConfig.RootCAs != nil)
assert.Len(t, tlsConfig.Certificates, testCase.wantCertificates)
})
}
}
type testCertificates struct {
caPool *x509.CertPool
server tls.Certificate
client auditor.TLSConfig
}
// Issues a CA, a broker certificate for 127.0.0.1 and a client certificate, writing the client side as ca.crt, tls.crt and tls.key.
func newTestCertificates(t *testing.T) testCertificates {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
caTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "test-ca"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCertSign,
}
caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
require.NoError(t, err)
ca, err := x509.ParseCertificate(caDER)
require.NoError(t, err)
serverCertPEM, serverKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "broker"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
})
server, err := tls.X509KeyPair(serverCertPEM, serverKeyPEM)
require.NoError(t, err)
clientCertPEM, clientKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(3),
Subject: pkix.Name{CommonName: "signoz"},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
})
dir := t.TempDir()
client := auditor.TLSConfig{
Enabled: true,
CAFile: filepath.Join(dir, "ca.crt"),
CertFile: filepath.Join(dir, "tls.crt"),
KeyFile: filepath.Join(dir, "tls.key"),
}
require.NoError(t, os.WriteFile(client.CAFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o600))
require.NoError(t, os.WriteFile(client.CertFile, clientCertPEM, 0o600))
require.NoError(t, os.WriteFile(client.KeyFile, clientKeyPEM, 0o600))
caPool := x509.NewCertPool()
caPool.AddCert(ca)
return testCertificates{caPool: caPool, server: server, client: client}
}
func issueTestCertificate(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, template *x509.Certificate) ([]byte, []byte) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template.NotBefore = time.Now().Add(-time.Hour)
template.NotAfter = time.Now().Add(time.Hour)
template.KeyUsage = x509.KeyUsageDigitalSignature
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
require.NoError(t, err)
keyDER, err := x509.MarshalECPrivateKey(key)
require.NoError(t, err)
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
}

View File

@@ -28,7 +28,7 @@ You are operating within a constrained context window and strict system prompts.
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
- Never override a `@signozhq/ui` component's styles: no `--<component>-*` CSS variables, no `:global` class or `data-*` selectors, no restyling through `className`/`style`. Use its props, and put layout on a wrapper you own. When it can't do what the design needs, file a UI suggestion in `SigNoz/uforge-pod` (`ui-suggestion.yml` template) and link it in the PR.
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.

View File

@@ -9,12 +9,12 @@
- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)
- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)
- [ ] No magic numbers - use `--spacing-*` tokens
- [ ] Typography uses `--{variant}-{size}-{weight}-*` text style tokens (see Typography)
- [ ] No overrides of `@signozhq/ui` components (see below)
- [ ] Global escapes only for third-party overrides (`@signozhq/ui` is not third-party)
- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
- [ ] Global escapes only for third-party overrides
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
.icon { } // -> styles.icon (separate class, not scoped under .button)
}
// GOOD: Flat structure
@@ -289,32 +289,88 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## @signozhq/ui Components
## Overriding @signozhq/ui Components
Don't override them. That covers setting a component's `--<component>-*` CSS variables, targeting its classes or `data-*` attributes through `:global(...)`, and restyling it with `className` or `style`. An override keeps working until the component changes, then breaks with no type error or lint warning, and the screen drifts from every other one using that component.
Components expose CSS variables for customization.
- Use the component's props (`variant`, `color`, `size`, ...) for how it looks.
- Put layout (position, margin, width inside a flex or grid parent) on a wrapper element you own.
- If the component can't do what the design needs, file a [UI suggestion](https://github.com/SigNoz/uforge-pod/issues/new?template=ui-suggestion.yml) in `SigNoz/uforge-pod` and ship with the component as it renders until the suggestion is decided. Link the issue in the PR.
You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.
Never write a override without confirm it exists.
Override via:
### Method 1: CSS Variables (Preferred)
Each component exposes `--<component>-<property>` variables:
```scss
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
// Override Button
.customButton {
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--label-base-400-font-size);
}
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
// Override Input
.customInput {
--input-height: 2.5rem;
--input-border-color: var(--l2-border);
--input-padding: var(--spacing-2) var(--spacing-6);
--input-placeholder-color: var(--l3-foreground);
}
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
}
```
### Method 2: Data Attributes
Components use data attributes for variants/states. Target them for state-specific overrides:
```scss
// Target variant
.wrapper :global([data-variant="outlined"]) {
--button-border-color: var(--accent-primary);
}
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
}
// Target color
.wrapper :global([data-color="destructive"]) {
--button-background: var(--danger-background);
}
// Target state (Radix patterns)
.popover :global([data-state="open"]) {
opacity: 1;
}
.tooltip :global([data-side="top"]) {
margin-bottom: var(--spacing-2);
}
```
### Common Component CSS Variables
**Button:**
- `--button-background`, `--button-border-radius`, `--button-padding`
- `--button-font-size`, `--button-height`, `--button-gap`
- `--button-hover-background`, `--button-disabled-opacity`
**Input:**
- `--input-height`, `--input-border-color`, `--input-background`
- `--input-padding`, `--input-font-size`, `--input-placeholder-color`
- `--input-focus-outline-color`, `--input-hover-border-color`
- `--input-prefix-*`, `--input-suffix-*` for adornments
**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`
## Good Patterns
### Structure
@@ -378,21 +434,24 @@ Don't override them. That covers setting a component's `--<component>-*` CSS var
### Keyframes (Local Scoping)
CSS Modules scope `@keyframes` like classes: the build renames `fadeIn` to `_fadeIn_<hash>` and rewrites every `animation` in the same module that names it. Don't wrap it in `:local(...)`; Sass rejects `:local(@keyframes fadeIn)` with `expected selector`.
Without `:local()`, keyframe names are global and can clash across modules:
```scss
// GOOD: Local to this module
// BAD: Global keyframe - can conflict with other modules
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
// GOOD: Locally scoped keyframe
:local(@keyframes fadeIn) {
from { opacity: 0; }
to { opacity: 1; }
}
.modal {
animation: fadeIn 200ms ease;
}
// BAD: Doesn't compile
:local(@keyframes fadeIn) { }
```
## JS Import Patterns

View File

@@ -12787,7 +12787,7 @@ export enum RuletypesQueryTypeDTO {
}
export interface RuletypesAlertCompositeQueryDTO {
/**
* @description The panel the UI renders the queries with: graph, table or value. Use graph for alerts.
* @description How the queries are evaluated. graph runs them as time series and matchType decides which points must satisfy op. table and value run them as scalar: one value per group over the whole evaluation window, compared directly, so matchType has no effect and metric aggregations need reduceTo. promql queries and anomaly_rule support graph only.
*/
panelType: RuletypesPanelTypeDTO;
/**

View File

@@ -8,7 +8,7 @@
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
@@ -34,9 +34,9 @@
--button-height: auto;
--button-padding: var(--spacing-4) var(--spacing-6);
--button-border-radius: var(--radius-3);
--button-font-size: var(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
@@ -64,8 +64,8 @@
// While Noz works, the row names the step it's on.
.live .activitySummary {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
}

View File

@@ -59,7 +59,7 @@
border: none;
background: none;
font: inherit;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -134,8 +134,8 @@
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
--button-variant-ghost-hover-background-color: var(--l3-background);
@@ -180,8 +180,8 @@
height: 44px;
padding: 0 var(--spacing-7);
border-bottom: 1px solid var(--l2-border);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -8,8 +8,8 @@
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: 20px;
letter-spacing: -0.005em;
color: var(--text-vanilla-400);
@@ -73,7 +73,7 @@
// Wide enough to hold the action buttons that replace it.
min-width: 16px;
text-align: right;
font-size: var(--paragraph-small-400-font-size);
font-size: var(--periscope-font-size-small);
line-height: 18px;
color: var(--l3-foreground);
opacity: calc(1 - var(--actions-opacity, 0));
@@ -87,7 +87,7 @@
width: 100%;
border-bottom: 1px solid var(--accent-primary);
--input-padding: 1px 0;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-hover-border-color: transparent;
}

View File

@@ -56,7 +56,7 @@
--button-border-radius: 3px;
--button-justify-content: flex-start;
--button-gap: var(--spacing-4);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l2-background);
--button-variant-outlined-border: 1px solid var(--l1-border);
--button-variant-outlined-color: var(--l2-foreground);
@@ -144,8 +144,8 @@
.groupLabel {
display: block;
padding: 0 0 7px;
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
font-feature-settings:
'tnum' on,

View File

@@ -71,7 +71,7 @@
align-items: flex-start;
background: var(--l2-background);
color: var(--l1-foreground);
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -44,8 +44,8 @@
--button-height: 32px;
--button-padding: 0 var(--spacing-6);
--button-border-radius: var(--radius-round);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-secondary-background-color: var(--l3-background);
--button-secondary-hover-background-color: var(--l3-background-hover);
--button-secondary-solid-foreground: var(--l1-foreground);

View File

@@ -1,42 +1,13 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import {
act,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import {
AUTHZ_CHECK_URL,
authzMockResponse,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
jest.mock('@monaco-editor/react', () => ({
__esModule: true,
default: ({
value,
onChange,
}: {
value: string;
onChange: (next?: string) => void;
}): JSX.Element => (
<textarea
data-testid="monaco-editor"
value={value}
onChange={(e): void => onChange(e.target.value)}
/>
),
}));
const CUSTOM_ROLE_ID = '019c24aa-3333-0001-aaaa-111111111111';
const rolesApiBase = '*/api/v1/roles';
const VIEW_ROLE_URL = `${ROUTES.ROLE_DETAILS.replace(
@@ -437,125 +408,4 @@ describe('EditRolePage', () => {
);
});
});
describe('JSON view opened from the URL', () => {
const roleGrants = roleWithTransactionGroups.data.transactionGroups;
function renderJsonView(client?: QueryClient): ReturnType<typeof render> {
const page = <CreateEditRolePage />;
return render(
client ? (
<QueryClientProvider client={client}>{page}</QueryClientProvider>
) : (
page
),
undefined,
{
initialRoute: `/settings/roles/${CUSTOM_ROLE_ID}/edit?name=Custom%20Role&viewMode=json`,
},
);
}
function readBuffer(editor: HTMLElement): unknown {
return JSON.parse((editor as HTMLTextAreaElement).value);
}
it('shows the role grants when the role loads after the authz check', async () => {
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) =>
res(ctx.delay(300), ctx.status(200), ctx.json(roleWithTransactionGroups)),
),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('shows the role grants when the role loads before the authz check', async () => {
server.use(
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
const payload = await req.json();
return res(
ctx.delay(300),
ctx.status(200),
ctx.json(
authzMockResponse(
payload,
payload.map(() => true),
),
),
);
}),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('saves what was typed in the buffer even when the role refetches afterwards', async () => {
const updatedBodies: unknown[] = [];
let roleReads = 0;
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) => {
roleReads += 1;
return res(
ctx.status(200),
ctx.json(
roleReads === 1
? roleWithTransactionGroups
: {
...roleWithTransactionGroups,
data: {
...roleWithTransactionGroups.data,
transactionGroups: [
{
objectGroup: {
resource: { kind: 'role', type: 'role' },
selectors: ['*'],
},
relation: 'update',
},
],
},
},
),
);
}),
rest.put(`${rolesApiBase}/:id`, async (req, res, ctx) => {
updatedBodies.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
const user = userEvent.setup();
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
renderJsonView(client);
const editor = await screen.findByTestId('monaco-editor');
await user.type(editor, '[[]', {
initialSelectionStart: 0,
initialSelectionEnd: (editor as HTMLTextAreaElement).value.length,
});
await act(async () => {
await client.invalidateQueries();
});
await waitFor(() => {
expect(roleReads).toBeGreaterThan(1);
});
await user.click(screen.getByTestId('save-button'));
await waitFor(() => {
expect(updatedBodies).toHaveLength(1);
});
expect(updatedBodies[0]).toMatchObject({ transactionGroups: [] });
});
});
});

View File

@@ -86,9 +86,6 @@ export function useCreateEditRolePageActions(
const { mutateAsync: updateRole, isLoading: isUpdating } =
useUpdateRolePermissions();
const isSaving = isCreating || isUpdating;
// Editors read their initial value once, so stay loading until the fetched
// role has been copied into local state.
const isSeedingFromRole = !!rolePermissionsData && !isInitialized;
useEffect(() => {
if (rolePermissionsData && !isInitialized) {
@@ -232,7 +229,7 @@ export function useCreateEditRolePageActions(
setEditorMode: handleModeChange,
resources: localResources,
setResources: handleResourcesChange,
isLoading: isLoadingPermissions || isSeedingFromRole,
isLoading: isLoadingPermissions,
isSaving,
hasUnsavedChanges,
handleSave,

View File

@@ -29,7 +29,7 @@
align-items: center;
justify-content: space-between;
gap: var(--spacing-6);
font-size: var(--label-base-500-font-size);
font-size: var(--font-size-sm);
font-weight: 500;
}
@@ -37,7 +37,7 @@
.subtitle {
padding-left: calc(12px + var(--spacing-3));
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -58,7 +58,7 @@
.code {
flex-shrink: 0;
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -100,7 +100,7 @@
align-items: center;
gap: var(--spacing-2);
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
letter-spacing: -0.01em;
font-variant-numeric: tabular-nums;
}

View File

@@ -36,7 +36,7 @@
.sizerValue {
font-size: 12px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}

View File

@@ -46,7 +46,7 @@
}
.tooltipName {
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
word-break: break-word;
}

View File

@@ -37,7 +37,7 @@
.value {
font-size: 12px;
line-height: 16px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
color: var(--l1-foreground);
text-align: right;
white-space: nowrap;

View File

@@ -71,20 +71,6 @@ type KafkaConfig struct {
// ShutdownTimeout bounds draining buffered events on stop; events still undelivered when it expires are dropped.
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
TLS TLSConfig `mapstructure:"tls"`
}
type TLSConfig struct {
Enabled bool `mapstructure:"enabled"`
// CAFile is the PEM bundle that verifies the server certificate. Empty uses the system roots.
CAFile string `mapstructure:"ca_file"`
// CertFile and KeyFile are the client certificate, presented when the server requires client auth.
CertFile string `mapstructure:"cert_file"`
KeyFile string `mapstructure:"key_file"`
}
// RetryConfig configures exponential backoff for the OTLP HTTP exporter.
@@ -182,10 +168,6 @@ func (c Config) Validate() error {
if c.Kafka.ShutdownTimeout <= 0 {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "auditor::kafka::shutdown_timeout must be greater than 0")
}
if c.Kafka.TLS.Enabled && (c.Kafka.TLS.CertFile == "") != (c.Kafka.TLS.KeyFile == "") {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file must be set together")
}
}
return nil

View File

@@ -492,6 +492,14 @@ func (r *BaseRule) extractMetricAndGroupBys(ctx context.Context) (map[string][]s
// FilterNewSeries filters out items that are too new based on metadata first_seen timestamps.
// Returns the filtered series (old ones) excluding new series that are still within the grace period.
func (r *BaseRule) FilterNewSeries(ctx context.Context, ts time.Time, series []*qbtypes.TimeSeries) ([]*qbtypes.TimeSeries, error) {
return filterNewByLabels(ctx, r, ts, series, func(s *qbtypes.TimeSeries) []*qbtypes.Label { return s.Labels })
}
func (r *BaseRule) FilterNewScalarGroups(ctx context.Context, ts time.Time, groups []qbtypes.ScalarGroup) ([]qbtypes.ScalarGroup, error) {
return filterNewByLabels(ctx, r, ts, groups, func(group qbtypes.ScalarGroup) []*qbtypes.Label { return group.Labels })
}
func filterNewByLabels[T any](ctx context.Context, r *BaseRule, ts time.Time, series []T, labelsOf func(T) []*qbtypes.Label) ([]T, error) {
// Extract metric names and groupBy keys
metricToGroupedFields, err := r.extractMetricAndGroupBys(ctx)
if err != nil {
@@ -510,7 +518,7 @@ func (r *BaseRule) FilterNewSeries(ctx context.Context, ts time.Time, series []*
for i := 0; i < len(series); i++ {
valueForKey := func(key string) (string, bool) {
for _, item := range series[i].Labels {
for _, item := range labelsOf(series[i]) {
if item.Key.Name == key {
return fmt.Sprint(item.Value), true
}
@@ -563,7 +571,7 @@ func (r *BaseRule) FilterNewSeries(ctx context.Context, ts time.Time, series []*
}
// Filter series based on first_seen + delay
filteredSeries := make([]*qbtypes.TimeSeries, 0, len(series))
filteredSeries := make([]T, 0, len(series))
evalTimeMs := ts.UnixMilli()
newGroupEvalDelayMs := r.newGroupEvalDelay.Milliseconds()
@@ -605,7 +613,7 @@ func (r *BaseRule) FilterNewSeries(ctx context.Context, ts time.Time, series []*
ctx, "skipping new series",
slog.Int("series.index", i), slog.Int64("series.max_first_seen", maxFirstSeen),
slog.Int64("eval.time_ms", evalTimeMs), slog.Int64("eval.delay_ms", newGroupEvalDelayMs),
slog.Any("series.labels", series[i].Labels),
slog.Any("series.labels", labelsOf(series[i])),
)
continue
}

View File

@@ -75,7 +75,7 @@ func (r *ThresholdRule) prepareQueryRange(ctx context.Context, ts time.Time) (*q
req := &qbtypes.QueryRangeRequest{
Start: uint64(start),
End: uint64(end),
RequestType: qbtypes.RequestTypeTimeSeries,
RequestType: r.Condition().CompositeQuery.PanelType.GetQueryRangeRequestType(),
CompositeQuery: qbtypes.CompositeQuery{
Queries: make([]qbtypes.QueryEnvelope, 0),
},
@@ -132,8 +132,6 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return nil, err
}
var results []*qbtypes.TimeSeriesData
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.CodeNamespace: "rules",
instrumentationtypes.CodeFunctionName: "buildAndRunQuery",
@@ -144,22 +142,22 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return nil, err
}
for _, item := range v5Result.Data.Results {
if tsData, ok := item.(*qbtypes.TimeSeriesData); ok {
results = append(results, tsData)
} else {
// NOTE: should not happen but just to ensure we don't miss it if it happens for some reason
r.logger.WarnContext(ctx, "expected qbtypes.TimeSeriesData but got unexpected type", slog.String("item.type", reflect.TypeOf(item).String()))
}
}
selectedQuery := r.SelectedQuery(ctx)
var queryResult *qbtypes.TimeSeriesData
for _, res := range results {
if res.QueryName == selectedQuery {
queryResult = res
break
for _, item := range v5Result.Data.Results {
switch data := item.(type) {
case *qbtypes.TimeSeriesData:
if data.QueryName == selectedQuery {
queryResult = data
}
case *qbtypes.ScalarData:
if data.QueryName == selectedQuery {
return r.evalScalarResult(ctx, ts, data)
}
default:
// NOTE: should not happen but just to ensure we don't miss it if it happens for some reason
r.logger.WarnContext(ctx, "expected qbtypes.TimeSeriesData or qbtypes.ScalarData but got unexpected type", slog.String("item.type", reflect.TypeOf(item).String()))
}
}
@@ -213,6 +211,44 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return resultVector, nil
}
func (r *ThresholdRule) evalScalarResult(ctx context.Context, ts time.Time, queryResult *qbtypes.ScalarData) (ruletypes.Vector, error) {
groups := queryResult.ExtractGroups()
hasData := len(groups) > 0
if missingDataAlert := r.HandleMissingDataAlert(ctx, ts, hasData); missingDataAlert != nil {
return ruletypes.Vector{*missingDataAlert}, nil
}
var resultVector ruletypes.Vector
// Filter out new groups if newGroupEvalDelay is configured
groupsToProcess := groups
if r.ShouldSkipNewGroups() {
filteredGroups, filterErr := r.BaseRule.FilterNewScalarGroups(ctx, ts, groupsToProcess)
// In case of error we log the error and continue with the original groups
if filterErr != nil {
r.logger.ErrorContext(ctx, "error filtering new groups", errors.Attr(filterErr))
} else {
groupsToProcess = filteredGroups
}
}
for _, group := range groupsToProcess {
// the first aggregation, as the series path reads Aggregations[0]
resultSeries, err := r.Threshold.EvalScalar(group.Labels, group.Values[0], r.Unit(), ruletypes.EvalData{
ActiveAlerts: r.ActiveAlertsLabelFP(),
SendUnmatched: r.ShouldSendUnmatched(),
})
if err != nil {
return nil, err
}
resultVector = append(resultVector, resultSeries...)
}
return resultVector, nil
}
func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
prevState := r.State()

View File

@@ -0,0 +1,204 @@
package rules
import (
"context"
"testing"
"time"
cmock "github.com/SigNoz/clickhouse-go-mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
"github.com/SigNoz/signoz/pkg/types/metrictypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
func scalarPanelRule(alertType ruletypes.AlertType, panelType ruletypes.PanelType, query qbtypes.QueryEnvelope, target float64, matchType ruletypes.MatchType) ruletypes.PostableRule {
return ruletypes.PostableRule{
AlertName: valuer.NewDisplayName("Scalar panel test"),
AlertType: alertType,
RuleType: ruletypes.RuleTypeThreshold,
Evaluation: &ruletypes.EvaluationEnvelope{Kind: ruletypes.RollingEvaluation, Spec: ruletypes.RollingWindow{
EvalWindow: valuer.MustParseTextDuration("5m"),
Frequency: valuer.MustParseTextDuration("1m"),
}},
RuleCondition: &ruletypes.RuleCondition{
CompositeQuery: &ruletypes.AlertCompositeQuery{
QueryType: ruletypes.QueryTypeBuilder,
PanelType: panelType,
Queries: []qbtypes.QueryEnvelope{query},
},
SelectedQuery: "A",
Thresholds: &ruletypes.RuleThresholdData{
Kind: ruletypes.BasicThresholdKind,
Spec: ruletypes.BasicRuleThresholds{{
Name: "critical",
TargetValue: &target,
MatchType: matchType,
CompareOperator: ruletypes.ValueIsAbove,
}},
},
},
}
}
// A value panel reduces the window to one number (reduceTo), so a target no
// single step crosses fires on the reduced value and matchType, which is
// about steps, no longer matters. The same rows on a graph panel keep the
// step semantics.
func TestThresholdRuleEvalScalarPanelTypeMetricsReducedOverWindow(t *testing.T) {
ts := time.Now().Truncate(time.Minute)
query := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{
Name: "A",
Signal: telemetrytypes.SignalMetrics,
StepInterval: qbtypes.Step{Duration: time.Minute},
Aggregations: []qbtypes.MetricAggregation{{
MetricName: "signoz_calls_total",
Temporality: metrictypes.Delta,
TimeAggregation: metrictypes.TimeAggregationRate,
SpaceAggregation: metrictypes.SpaceAggregationSum,
ReduceTo: qbtypes.ReduceToSum,
}},
},
}
cols := []cmock.ColumnType{
{Name: "ts", Type: "DateTime"},
{Name: "value", Type: "Float64"},
}
values := [][]any{
{ts.Add(-4 * time.Minute), float64(100)},
{ts.Add(-3 * time.Minute), float64(150)},
{ts.Add(-2 * time.Minute), float64(250)},
}
testCases := []struct {
name string
panelType ruletypes.PanelType
matchType ruletypes.MatchType
target float64
expectedAlertCount int
}{
{name: "ValuePanel_SumAboveTarget_AllTheTimes_Fires", panelType: ruletypes.PanelTypeValue, matchType: ruletypes.AllTheTimes, target: 400, expectedAlertCount: 1},
{name: "ValuePanel_SumBelowTarget_AtleastOnce_Silent", panelType: ruletypes.PanelTypeValue, matchType: ruletypes.AtleastOnce, target: 600, expectedAlertCount: 0},
{name: "GraphPanel_NoStepAboveTarget_AllTheTimes_Silent", panelType: ruletypes.PanelTypeGraph, matchType: ruletypes.AllTheTimes, target: 400, expectedAlertCount: 0},
{name: "GraphPanel_OneStepAboveTarget_AtleastOnce_Fires", panelType: ruletypes.PanelTypeGraph, matchType: ruletypes.AtleastOnce, target: 200, expectedAlertCount: 1},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, &queryMatcherAny{})
telemetryStore.Mock().
ExpectQuery("SELECT any").
WithArgs(nil, nil, nil, nil, nil, nil, nil).
WillReturnRows(cmock.NewRows(cols, values))
querier, mockMetadataStore := prepareQuerierForMetrics(t, telemetryStore)
mockMetadataStore.TypeMap["signoz_calls_total"] = metrictypes.SumType
postableRule := scalarPanelRule(ruletypes.AlertTypeMetric, testCase.panelType, query, testCase.target, testCase.matchType)
rule, err := NewThresholdRule("scalar", valuer.GenerateUUID(), &postableRule, querier, instrumentationtest.New().Logger(), mustParseURL(t, "http://localhost:8080"))
require.NoError(t, err)
alertsFound, err := rule.Eval(context.Background(), ts)
require.NoError(t, err)
assert.Equal(t, testCase.expectedAlertCount, alertsFound)
})
}
}
// A table panel over logs yields one row per group for the whole window, and
// the engine raises one alert per row that crosses the target, labelled with
// the group values.
func TestThresholdRuleEvalScalarPanelTypeLogsOneAlertPerRow(t *testing.T) {
ts := time.Now().Truncate(time.Minute)
serviceKey := telemetrytypes.TelemetryFieldKey{
Name: "service.name",
FieldContext: telemetrytypes.FieldContextResource,
FieldDataType: telemetrytypes.FieldDataTypeString,
}
query := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
Name: "A",
Signal: telemetrytypes.SignalLogs,
StepInterval: qbtypes.Step{Duration: time.Minute},
Aggregations: []qbtypes.LogAggregation{{Expression: "count()"}},
GroupBy: []qbtypes.GroupByKey{{TelemetryFieldKey: serviceKey}},
},
}
keysMap := map[string][]*telemetrytypes.TelemetryFieldKey{"service.name": {&serviceKey}}
cols := []cmock.ColumnType{
{Name: "__GROUP_BY_KEY_0_service.name", Type: "String"},
{Name: "__result_0", Type: "UInt64"},
}
testCases := []struct {
name string
rows [][]any
alertOnAbsent bool
expectedAlertCount int
expectedServices []string
expectedMissing bool
}{
{
name: "TwoGroups_OneAboveTarget_FiresForThatGroup",
rows: [][]any{{"checkout", uint64(120)}, {"cart", uint64(30)}},
expectedAlertCount: 1,
expectedServices: []string{"checkout"},
},
{
name: "TwoGroups_BothAboveTarget_FiresForEach",
rows: [][]any{{"checkout", uint64(120)}, {"cart", uint64(130)}},
expectedAlertCount: 2,
expectedServices: []string{"cart", "checkout"},
},
{
name: "NoRows_AlertOnAbsent_FiresNoData",
rows: [][]any{},
alertOnAbsent: true,
expectedAlertCount: 1,
expectedMissing: true,
},
{
name: "NoRows_WithoutAlertOnAbsent_Silent",
rows: [][]any{},
expectedAlertCount: 0,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, &queryMatcherAny{})
telemetryStore.Mock().
ExpectQuery("SELECT any").
WithArgs(nil, nil, nil, nil).
WillReturnRows(cmock.NewRows(cols, testCase.rows))
querier := prepareQuerierForLogs(t, telemetryStore, keysMap)
postableRule := scalarPanelRule(ruletypes.AlertTypeLogs, ruletypes.PanelTypeTable, query, 100, ruletypes.OnAverage)
postableRule.RuleCondition.AlertOnAbsent = testCase.alertOnAbsent
rule, err := NewThresholdRule("scalar", valuer.GenerateUUID(), &postableRule, querier, instrumentationtest.New().Logger(), mustParseURL(t, "http://localhost:8080"))
require.NoError(t, err)
alertsFound, err := rule.Eval(context.Background(), ts)
require.NoError(t, err)
assert.Equal(t, testCase.expectedAlertCount, alertsFound)
services := make([]string, 0, len(rule.Active))
for _, alert := range rule.Active {
assert.Equal(t, testCase.expectedMissing, alert.Missing)
if service := alert.QueryResultLabels.Get("service.name"); service != "" {
services = append(services, service)
}
}
assert.ElementsMatch(t, testCase.expectedServices, services)
})
}
}

View File

@@ -30,10 +30,6 @@ func (h *provider) BeforeQuery(ctx context.Context, _ *telemetrystore.QueryEvent
settings["log_comment"] = ctxtypes.CommentFromContext(ctx).String()
// The result model has no Variant type: mismatched types must fail with the
// no-common-type error rather than become a Variant (the 26.8 default).
settings["use_variant_as_common_type"] = 0
if ctx.Value("enforce_max_result_rows") != nil {
settings["max_result_rows"] = h.settings.MaxResultRows
}

View File

@@ -444,6 +444,39 @@ type ScalarData struct {
Data [][]any `json:"data" description:"The rows, each a list of values aligned with columns."`
}
// ScalarGroup is one entry of a ScalarData, the scalar counterpart of a
// TimeSeries: the group-by cells as labels and one value per aggregation, in
// column order. A cell that is not numeric reads as NaN.
type ScalarGroup struct {
Labels []*Label
Values []float64
}
func (sd *ScalarData) ExtractGroups() []ScalarGroup {
if !slices.ContainsFunc(sd.Columns, func(col *ColumnDescriptor) bool { return col.Type == ColumnTypeAggregation }) {
return nil
}
groups := make([]ScalarGroup, 0, len(sd.Data))
for _, row := range sd.Data {
group := ScalarGroup{Labels: make([]*Label, 0), Values: make([]float64, 0)}
for i, col := range sd.Columns {
var cell any
if i < len(row) {
cell = row[i]
}
switch col.Type {
case ColumnTypeGroup:
group.Labels = append(group.Labels, &Label{Key: col.TelemetryFieldKey, Value: cell})
case ColumnTypeAggregation:
group.Values = append(group.Values, numericAsFloat(cell))
}
}
groups = append(groups, group)
}
return groups
}
type RawData struct {
QueryName string `json:"queryName" description:"The name of the query that produced these rows."`
NextCursor string `json:"nextCursor" description:"The cursor to pass in the next request to continue from the last row; empty when there are no more rows."`
@@ -649,3 +682,17 @@ func (r RawData) MarshalJSON() ([]byte, error) {
type Alias RawData
return json.Marshal((*Alias)(&r))
}
func numericAsFloat(v any) float64 {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Float32, reflect.Float64:
return rv.Float()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(rv.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(rv.Uint())
default:
return math.NaN()
}
}

View File

@@ -530,3 +530,52 @@ func TestTimeSeriesDataFilterToTimeRange(t *testing.T) {
})
}
}
func TestScalarDataExtractGroups(t *testing.T) {
serviceKey := telemetrytypes.TelemetryFieldKey{Name: "service"}
groupCol := &ColumnDescriptor{TelemetryFieldKey: serviceKey, QueryName: "A", Type: ColumnTypeGroup}
countCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "__result_0"}, QueryName: "A", AggregationIndex: 0, Type: ColumnTypeAggregation}
latencyCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "p99"}, QueryName: "A", AggregationIndex: 1, Type: ColumnTypeAggregation}
testCases := []struct {
name string
scalarData *ScalarData
expectedGroups []ScalarGroup
}{
{
name: "GroupByColumn_LabelsAndOneValuePerAggregation_InResultOrder",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{groupCol, countCol, latencyCol}, Data: [][]any{
{"cart", int64(2), 20.0},
{"auth", uint64(1), float32(10)},
}},
expectedGroups: []ScalarGroup{
{Labels: []*Label{{Key: serviceKey, Value: "cart"}}, Values: []float64{2, 20}},
{Labels: []*Label{{Key: serviceKey, Value: "auth"}}, Values: []float64{1, 10}},
},
},
{
name: "NoGroupByColumn_SingleUnlabeledGroup",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{countCol}, Data: [][]any{{3.5}}},
expectedGroups: []ScalarGroup{{Labels: []*Label{}, Values: []float64{3.5}}},
},
{
name: "NoAggregationColumn_NoGroups",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{groupCol}, Data: [][]any{{"cart"}}},
expectedGroups: nil,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.expectedGroups, testCase.scalarData.ExtractGroups())
})
}
}
func TestScalarDataExtractGroupsNonNumericCell(t *testing.T) {
countCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "__result_0"}, QueryName: "A", Type: ColumnTypeAggregation}
groups := (&ScalarData{Columns: []*ColumnDescriptor{countCol}, Data: [][]any{{"n/a"}}}).ExtractGroups()
assert.Len(t, groups, 1)
assert.True(t, math.IsNaN(groups[0].Values[0]))
}

View File

@@ -87,6 +87,17 @@ func (p PanelType) Validate() error {
}
}
func (p PanelType) GetQueryRangeRequestType() qbtypes.RequestType {
switch p {
case PanelTypeTable, PanelTypeValue:
return qbtypes.RequestTypeScalar
default:
// Only the write path validates the panel, so a stored unset or
// unknown one runs as graph.
return qbtypes.RequestTypeTimeSeries
}
}
// Note: this is used to represent the state of the alert query
// i.e the active tab which should be used to represent the selection
@@ -121,7 +132,7 @@ func (q QueryType) Validate() error {
type AlertCompositeQuery struct {
Queries []qbtypes.QueryEnvelope `json:"queries" required:"true" description:"The queries to evaluate, at least one. Every envelope type must match queryType: builder_query and builder_formula for builder, promql for promql, clickhouse_sql for clickhouse_sql."`
PanelType PanelType `json:"panelType" required:"true" description:"The panel the UI renders the queries with: graph, table or value. Use graph for alerts."`
PanelType PanelType `json:"panelType" required:"true" description:"How the queries are evaluated. graph runs them as time series and matchType decides which points must satisfy op. table and value run them as scalar: one value per group over the whole evaluation window, compared directly, so matchType has no effect and metric aggregations need reduceTo. promql queries and anomaly_rule support graph only."`
QueryType QueryType `json:"queryType" required:"true" description:"The query language of every query: builder, promql or clickhouse_sql."`
Unit string `json:"unit,omitempty" description:"The unit of the query result, such as percent, ms or bytes. Used to format values in notifications and to convert thresholds given in a different targetUnit."`
}

View File

@@ -0,0 +1,29 @@
package ruletypes
import (
"testing"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/stretchr/testify/assert"
)
func TestPanelTypeGetQueryRangeRequestType(t *testing.T) {
testCases := []struct {
name string
panelType PanelType
expectedRequestType qbtypes.RequestType
}{
{name: "Graph_TimeSeries", panelType: PanelTypeGraph, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Unset_TimeSeries", panelType: PanelType{}, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Unknown_TimeSeries", panelType: PanelType{valuer.NewString("pie")}, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Table_Scalar", panelType: PanelTypeTable, expectedRequestType: qbtypes.RequestTypeScalar},
{name: "Value_Scalar", panelType: PanelTypeValue, expectedRequestType: qbtypes.RequestTypeScalar},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.expectedRequestType, testCase.panelType.GetQueryRangeRequestType())
})
}
}

View File

@@ -391,14 +391,18 @@ func (r *PostableRule) Validate() error {
if err := r.RuleCondition.CompositeQuery.PanelType.Validate(); err != nil {
errs = append(errs, err)
}
queryRangeRequestType := r.RuleCondition.CompositeQuery.PanelType.GetQueryRangeRequestType()
if len(r.RuleCondition.CompositeQuery.Queries) == 0 {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.compositeQuery.queries: must have at least one query"))
} else {
cq := &qbtypes.CompositeQuery{Queries: r.RuleCondition.CompositeQuery.Queries}
if err := cq.Validate(qbtypes.GetValidationOptions(qbtypes.RequestTypeTimeSeries)...); err != nil {
if err := cq.Validate(qbtypes.GetValidationOptions(queryRangeRequestType)...); err != nil {
errs = append(errs, err)
}
}
if queryRangeRequestType == qbtypes.RequestTypeScalar {
errs = append(errs, r.validateScalarPanelType()...)
}
}
if r.RuleCondition.SelectedQuery == "" {
@@ -453,6 +457,26 @@ func (r *PostableRule) Validate() error {
return nil
}
func (r *PostableRule) validateScalarPanelType() []error {
var errs []error
panelType := r.RuleCondition.CompositeQuery.PanelType.StringValue()
if r.RuleType == RuleTypeAnomaly {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.compositeQuery.panelType: anomaly_rule supports %q only, got %q", PanelTypeGraph.StringValue(), panelType))
}
if r.RuleType == RuleTypeProm || r.RuleCondition.CompositeQuery.QueryType == QueryTypePromQL {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.compositeQuery.panelType: promql queries support %q only, got %q", PanelTypeGraph.StringValue(), panelType))
}
if r.RuleCondition.RequireMinPoints {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.requireMinPoints: not supported with panelType %q, which evaluates one value per group", panelType))
}
return errs
}
func (r *PostableRule) validateSchemaVersion() []error {
switch r.SchemaVersion {
case SchemaVersionV2Alpha1:

View File

@@ -126,6 +126,9 @@ type RuleThreshold interface {
// Eval runs the given series through the threshold rules
// using the given EvalData and returns the matching series
Eval(series *qbtypes.TimeSeries, unit string, evalData EvalData) (Vector, error)
// EvalScalar runs one value per group through the threshold rules; the
// value is compared directly, matchType plays no part.
EvalScalar(labels []*qbtypes.Label, value float64, unit string, evalData EvalData) (Vector, error)
GetRuleReceivers() []RuleReceivers
// Validate runs on the write path and before a task is built; a stored
// rule may hold a threshold that fails it and still decode.
@@ -268,6 +271,37 @@ func (r BasicRuleThresholds) Eval(s *qbtypes.TimeSeries, unit string, evalData E
return resultVector, nil
}
func (r BasicRuleThresholds) EvalScalar(labels []*qbtypes.Label, value float64, unit string, evalData EvalData) (Vector, error) {
var resultVector Vector
if math.IsNaN(value) || math.IsInf(value, 0) {
return resultVector, nil
}
thresholds := []BasicRuleThreshold(r)
sortThresholds(thresholds)
for _, threshold := range thresholds {
op := threshold.CompareOperator.Normalize()
smpl := Sample{
Point: Point{V: value},
Metric: PrepareSampleLabelsForRule(labels, threshold.Name),
Target: *threshold.TargetValue,
RecoveryTarget: threshold.RecoveryTarget,
TargetUnit: threshold.TargetUnit,
CompareOperator: threshold.CompareOperator,
MatchType: threshold.MatchType,
}
if matchesCompareOp(op, value, threshold.target(unit)) || evalData.SendUnmatched {
resultVector = append(resultVector, smpl)
continue
}
if threshold.RecoveryTarget != nil && evalData.HasActiveAlert(smpl.Metric.Hash()) && matchesCompareOp(op, value, threshold.recoveryTarget(unit)) {
smpl.IsRecovering = true
resultVector = append(resultVector, smpl)
}
}
return resultVector, nil
}
func sortThresholds(thresholds []BasicRuleThreshold) {
sort.Slice(thresholds, func(i, j int) bool {

View File

@@ -1,10 +1,12 @@
package ruletypes
import (
"math"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -448,6 +450,45 @@ func TestBasicRuleThresholdEval_UnitConversion(t *testing.T) {
}
}
func TestBasicRuleThresholdsEvalScalar(t *testing.T) {
target := 100.0
recoveryTarget := 80.0
labels := []*qbtypes.Label{{Key: telemetrytypes.TelemetryFieldKey{Name: "service"}, Value: "cart"}}
thresholds := BasicRuleThresholds{{Name: "critical", TargetValue: &target, RecoveryTarget: &recoveryTarget, CompareOperator: ValueIsAbove, MatchType: AllTheTimes}}
activeAlerts := map[uint64]struct{}{PrepareSampleLabelsForRule(labels, "critical").Hash(): {}}
testCases := []struct {
name string
value float64
evalData EvalData
expectedSampleCount int
expectedValue float64
expectedRecovering bool
}{
{name: "AboveTarget_Fires", value: 150, expectedSampleCount: 1, expectedValue: 150},
{name: "BelowTarget_Silent", value: 50},
{name: "BelowTarget_SendUnmatched_ReportsValue", value: 50, evalData: EvalData{SendUnmatched: true}, expectedSampleCount: 1, expectedValue: 50},
{name: "ActiveAlertAboveRecoveryTarget_Recovering", value: 90, evalData: EvalData{ActiveAlerts: activeAlerts}, expectedSampleCount: 1, expectedValue: 90, expectedRecovering: true},
{name: "NoActiveAlertAboveRecoveryTarget_Silent", value: 90},
{name: "NaN_Silent", value: math.NaN()},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
vector, err := thresholds.EvalScalar(labels, testCase.value, "", testCase.evalData)
require.NoError(t, err)
require.Len(t, vector, testCase.expectedSampleCount)
if testCase.expectedSampleCount == 0 {
return
}
assert.Equal(t, testCase.expectedValue, vector[0].V)
assert.Equal(t, testCase.expectedRecovering, vector[0].IsRecovering)
assert.Equal(t, "cart", vector[0].Metric.Get("service"))
assert.Equal(t, "critical", vector[0].Metric.Get(LabelThresholdName))
})
}
}
func TestPrepareSampleLabelsForRule(t *testing.T) {
alertAllHashes := make(map[uint64]struct{})
thresholdName := "test"

View File

@@ -116,6 +116,6 @@ def pytest_addoption(parser: pytest.Parser):
parser.addoption(
"--signoz-otel-collector-version",
action="store",
default="v0.144.17",
default="v0.144.16-rc.1",
help="signoz-otel-collector version, used to run clickhouse migrations",
)

View File

@@ -0,0 +1,8 @@
{ "timestamp": "2026-01-29T10:00:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:00:15.000000Z", "resources": { "service.name": "cart" }, "attributes": {}, "body": "scalar panel probe: cart", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:00:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:15.000000Z", "resources": { "service.name": "cart" }, "attributes": {}, "body": "scalar panel probe: cart", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }

View File

@@ -0,0 +1,72 @@
{
"alert": "scalar_table_panel_logs",
"ruleType": "threshold_rule",
"alertType": "LOGS_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 4,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "table",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "logs",
"filter": {
"expression": "body CONTAINS 'scalar panel probe'"
},
"groupBy": [
{
"name": "service.name",
"fieldContext": "resource",
"fieldDataType": "string"
}
],
"aggregations": [
{
"expression": "count()"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"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

@@ -0,0 +1,3 @@
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:00:00+00:00","value":100,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:01:00+00:00","value":150,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:02:00+00:00","value":250,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}

View File

@@ -0,0 +1,66 @@
{
"alert": "scalar_value_panel_metrics",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 400,
"matchType": "all_the_times",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "metrics",
"stepInterval": "1m",
"aggregations": [
{
"metricName": "active_requests_scalar_value_panel",
"timeAggregation": "avg",
"spaceAggregation": "sum",
"reduceTo": "sum"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"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

@@ -0,0 +1,66 @@
{
"alert": "scalar_value_panel_metrics_as_graph",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 400,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "graph",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "metrics",
"stepInterval": "1m",
"aggregations": [
{
"metricName": "active_requests_scalar_value_panel",
"timeAggregation": "avg",
"spaceAggregation": "sum",
"reduceTo": "sum"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"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

@@ -144,13 +144,14 @@ def test_timestamp_counting_aggregations_are_numeric(
assert raw > 0, f"{expression} returned {raw!r}, expected a positive rate"
# KNOWN GAP, pinned deliberately: ClickHouse rejects sum over DateTime64, and rate_*
# KNOWN GAP, pinned deliberately: ClickHouse rejects sum/avg over DateTime64, and rate_*
# additionally divides a time by an interval; both surface as the generic 500. They returned
# a meaningless seconds number before #5824. Flip to BAD_REQUEST once validated up front.
@pytest.mark.parametrize(
"expression",
[
"sum(timestamp)",
"avg(timestamp)",
"rate_sum(timestamp)",
"rate_avg(timestamp)",
"rate_min(timestamp)",

View File

@@ -2,6 +2,7 @@ import time
from collections.abc import Callable
from http import HTTPStatus
import pytest
import requests
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
@@ -463,3 +464,84 @@ def test_create_rejects_channel_by_name(
"suggestions": [],
},
}
@pytest.mark.parametrize(
("rule", "expected_message"),
[
(
{**VALID_RULE, "condition": {**VALID_RULE["condition"], "compositeQuery": {**VALID_RULE["condition"]["compositeQuery"], "panelType": "value"}}},
"invalid query 'A': reduceTo is required for aggregation #1 in query 'A' for the scalar request type",
),
(
{
**VALID_RULE,
"ruleType": "anomaly_rule",
"condition": {
**VALID_RULE["condition"],
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "validation_probe_cpu", "timeAggregation": "avg", "spaceAggregation": "max", "reduceTo": "avg"}]}}],
},
},
},
'condition.compositeQuery.panelType: anomaly_rule supports "graph" only, got "value"',
),
(
{
**VALID_RULE,
"ruleType": "promql_rule",
"condition": {
**VALID_RULE["condition"],
"compositeQuery": {"queryType": "promql", "panelType": "table", "queries": [{"type": "promql", "spec": {"name": "A", "query": "up == 0", "disabled": False}}]},
},
},
'condition.compositeQuery.panelType: promql queries support "graph" only, got "table"',
),
(
{
**VALID_RULE,
"condition": {
**VALID_RULE["condition"],
"requireMinPoints": True,
"requiredNumPoints": 2,
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "validation_probe_cpu", "timeAggregation": "avg", "spaceAggregation": "max", "reduceTo": "avg"}]}}],
},
},
},
'condition.requireMinPoints: not supported with panelType "value", which evaluates one value per group',
),
],
ids=["metrics_without_reduce_to", "anomaly_rule", "promql_query", "require_min_points"],
)
def test_create_rejects_rules_a_scalar_panel_cannot_evaluate(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
rule: dict,
expected_message: str,
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = requests.post(
signoz.self.host_configs["8080"].get(BASE_URL),
json=rule,
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
assert response.json() == {
"status": "error",
"error": {
"type": "invalid-input",
"code": "invalid_input",
"message": "alert rule is not valid",
"errors": [{"message": expected_message, "suggestions": []}],
"suggestions": [],
},
}

View File

@@ -0,0 +1,65 @@
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
import pytest
from fixtures import types
from fixtures.alerts import (
get_rule_history_top_contributors,
labels_to_map,
wait_for_firing_timeline_entry,
)
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
def test_value_panel_fires_on_the_window_sum(
signoz: types.SigNoz,
create_alert_rule_with_channel: Callable[[str], str],
insert_alert_data: Callable[[list[types.AlertData], datetime], None],
get_token: Callable[[str, str], str],
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)
# one-minute samples of 100, 150 and 250: no step reaches the 400 target,
# their sum over the window does
insert_alert_data(
[types.AlertData(type="metrics", data_path="ruler/test_scenarios/scalar_value_panel_metrics/alert_data.jsonl")],
base_time=datetime.now(tz=UTC) - timedelta(minutes=4),
)
value_rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_value_panel_metrics/rule.json")
graph_rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_value_panel_metrics_as_graph/rule.json")
(item, _) = wait_for_firing_timeline_entry(signoz, token, value_rule_id, query_start_ms)
assert item["value"] == 500
# the same query on a graph panel compares each step, even at_least_once
# never sees 400
with pytest.raises(AssertionError, match="No firing entry recorded"):
wait_for_firing_timeline_entry(signoz, token, graph_rule_id, query_start_ms, wait_seconds=30)
def test_table_panel_fires_per_group_on_the_window_count(
signoz: types.SigNoz,
create_alert_rule_with_channel: Callable[[str], str],
insert_alert_data: Callable[[list[types.AlertData], datetime], None],
get_token: Callable[[str, str], str],
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)
# checkout logs two lines a minute for three minutes, cart one line a
# minute for two: only checkout's whole-window count passes the 4 target,
# and no single minute of either does
insert_alert_data(
[types.AlertData(type="logs", data_path="ruler/test_scenarios/scalar_table_panel_logs/alert_data.jsonl")],
base_time=datetime.now(tz=UTC) - timedelta(minutes=4),
)
rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_table_panel_logs/rule.json")
(item, end_ms) = wait_for_firing_timeline_entry(signoz, token, rule_id, query_start_ms)
assert labels_to_map(item["labels"]).get("service.name") == "checkout"
assert item["value"] == 6
contributors = get_rule_history_top_contributors(signoz, token, rule_id, query_start_ms, end_ms)
assert {labels_to_map(contributor["labels"]).get("service.name") for contributor in contributors} == {"checkout"}