Compare commits

..

4 Commits

Author SHA1 Message Date
Gaurav Tewari
f3a0fe2acc feat(noz): report caught errors to Sentry
Quota, permission and busy-thread errors are skipped: the UI already explains them.
2026-11-23 22:36:36 +05:30
Nikhil Soni
1e08a94ab8 fix: application support for clickhouse 26.8 (#13371)
#### Description

Part of SigNoz/platform-pod#3428.

- Run every integration suite against ClickHouse `26.8.34` (SQLite only,
non-blocking) to catch upgrade issues early.
- Bump the collector to `v0.144.17` for
SigNoz/signoz-otel-collector#990: 26.8 rejects the migrator's `CREATE`
of AggregatingMergeTree tables with plain columns outside the sorting
key.
- Pin `use_variant_as_common_type=0`: 26.8 turns mismatched types into
`Variant` instead of the no-common-type error. Handling `Variant`
results instead is tracked in SigNoz/events-pod#271.
- Drop `avg(timestamp)` from the pinned unsupported aggregations: 26.8
averages `DateTime64` into an instant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01X3AdVnw3X4N8Knhw8Yghtv
2026-11-23 13:24:36 +00:00
Vinicius Lourenço
cbfbb103af fix(web): correct the CSS modules guide, forbid component overrides, replace undefined tokens (#13697)
## Description

The CSS modules guide told us to write `:local(@keyframes name)`, and
Greptile now flags plain `@keyframes` in review because of it. That form
doesn't compile (Sass fails with `expected selector`), and it isn't
needed: CSS Modules already scope `@keyframes` in a `.module.scss` file.

While checking the rest of the guide against `@signozhq/ui` and the
design tokens, I fixed two more things that don't exist or don't behave
as written. The `--periscope-font-size-*` and `--font-size-*` tokens
aren't defined anywhere, so the checklist now points at the text style
tokens. And a nested `.icon` inside `.button` compiles to `.button
.icon`, so it is scoped under `.button`, contrary to what the comment
said.

The app had the same problem: the AI assistant, the Top List panel and
the Geo Map tooltip used `--periscope-font-size-*`, `--font-size-*` and
`--font-weight-*` tokens that were never defined, so their text fell
back to whatever size and weight it inherited. They now use the
typography tokens, so small labels render at 11px and medium or semibold
text gets its weight back. Expect those surfaces to look slightly
different.

The guide also taught how to override `@signozhq/ui` components through
their CSS variables and `data-*` attributes, and several of the
variables it listed didn't exist. That section now says not to override
them at all: use the component's props, put layout on a wrapper you own,
and when the component can't do what the design needs, file a UI
suggestion in `SigNoz/uforge-pod` instead of restyling it locally.
`frontend/CLAUDE.md` says the same, so agents stop writing overrides.

## Screenshots

AI assistant thread list: group headers and timestamps drop to 11px,
headers get bolder.
![AI assistant thread list, before and
after](https://github.com/user-attachments/assets/97d85d76-95d1-4793-b968-049ba21b11d1)

AI assistant suggested actions: the label drops to 11px, the action
buttons grow to 13px.
![AI assistant suggested actions, before and
after](https://github.com/user-attachments/assets/bc115d6d-2a95-47c5-8aeb-8d8da62cbd7a)

Geo Map tooltip: the place name goes to 13px medium, the code, label and
value to 11px.
![Geo Map tooltip, before and
after](https://github.com/user-attachments/assets/12b54137-2310-4e0b-976b-ac94e7ad364c)

Top List: the value column goes from regular to medium weight.
![Top List values, before and
after](https://github.com/user-attachments/assets/f90222b0-d256-499d-90b7-03065676886d)
2026-11-23 13:17:32 +00:00
Swapnil Nakade
fbca5e7d80 feat(auditor): add tls to the kafka auditor (#13710)
<!--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
- Adds `auditor::kafka::tls` (`enabled`, `ca_file`, `cert_file`,
`key_file`) so the Kafka auditor can connect to brokers that require TLS
or mTLS, such as Redpanda's internal listener in TLS deployments.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
closes https://github.com/SigNoz/keystone-pod/issues/225
2026-11-23 10:57:46 +00:00
40 changed files with 585 additions and 317 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.16-rc.1 \
signoz/signoz-otel-collector:v0.144.17 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,13 +85,18 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.16-rc.1
- v0.144.17
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,6 +474,14 @@ 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

@@ -2,7 +2,10 @@ 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"
@@ -10,6 +13,7 @@ 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"
@@ -39,13 +43,25 @@ 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).
client, err := kgo.NewClient(
opts := []kgo.Opt{
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
}
@@ -130,3 +146,30 @@ 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

@@ -0,0 +1,269 @@
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.
- 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.
- 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.
- 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 `--periscope-font-size-*` or `--font-size-*` tokens
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
- [ ] Global escapes only for third-party overrides
- [ ] 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)
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon (separate class, not scoped under .button)
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
}
// GOOD: Flat structure
@@ -289,88 +289,32 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## Overriding @signozhq/ui Components
## @signozhq/ui Components
Components expose CSS variables for customization.
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.
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:
- 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.
```scss
// 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);
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
}
// 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);
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
}
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
}
```
### 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
@@ -434,24 +378,21 @@ Components use data attributes for variants/states. Target them for state-specif
### Keyframes (Local Scoping)
Without `:local()`, keyframe names are global and can clash across modules:
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`.
```scss
// BAD: Global keyframe - can conflict with other modules
// GOOD: Local to this module
@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

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

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
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(--periscope-font-size-base);
--button-font-size: var(--label-base-400-font-size);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--font-weight-normal);
--button-font-weight: var(--label-base-400-font-weight);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -38,6 +38,7 @@ import logEvent from 'api/common/logEvent';
import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { reportAssistantError } from '../../utils/reportAssistantError';
import { getOpenResourceTarget } from './utils/getOpenResourceTarget';
import {
@@ -464,6 +465,7 @@ export default function ActionsSection({
});
setResult(key, { state: 'success' });
} catch (err) {
reportAssistantError('openSavedView', err);
const message =
err instanceof Error ? err.message : 'Failed to open saved view';
setResult(key, { state: 'error', error: message });
@@ -483,6 +485,7 @@ export default function ActionsSection({
await call(action.actionMetadataId);
setResult(key, { state: 'success' });
} catch (err) {
reportAssistantError('rollbackAction', err);
const message = err instanceof Error ? err.message : 'Failed';
setResult(key, { state: 'error', error: message });
}

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
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(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
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(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--font-size-sm);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
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(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--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(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
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(--font-size-xs);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 15px;
transition:
background-color 0.12s,

View File

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

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
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(--periscope-font-size-small);
font-size: var(--paragraph-small-400-font-size);
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(--periscope-font-size-base);
--input-font-size: var(--label-base-400-font-size);
--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(--font-weight-normal);
--button-font-weight: var(--label-base-400-font-weight);
--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(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
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(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
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(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--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

@@ -6,6 +6,7 @@ import { Check, LoaderCircle, TriangleAlert, X, Zap } from '@signozhq/icons';
import { PageActionRegistry } from '../../../pageActions/PageActionRegistry';
import { AIActionBlock } from '../../../pageActions/types';
import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
import { reportAssistantError } from '../../../utils/reportAssistantError';
import { useMessageContext } from '../../MessageContext';
import blockStyles from '../Block.module.scss';
@@ -85,6 +86,7 @@ export default function ActionBlock({
markBlockAnswered(messageId, `applied:${result.summary}`);
}
} catch (err) {
reportAssistantError('executePageAction', err);
const msg = err instanceof Error ? err.message : 'Unknown error';
setErrorMessage(msg);
setLocalState('error');

View File

@@ -36,6 +36,7 @@ import {
MessageBlock,
MessageRole,
} from '../types';
import { reportAssistantError } from '../utils/reportAssistantError';
import {
resolveAssistantError,
type AssistantErrorResolution,
@@ -590,7 +591,7 @@ async function streamAndFinalize(
conversationId: string,
start: () => Promise<string>,
fallback: string,
logLabel: string,
operation: string,
set: StoreSetter,
get: StoreGetter,
retry: () => Promise<void>,
@@ -605,8 +606,7 @@ async function streamAndFinalize(
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
// eslint-disable-next-line no-console
console.error(logLabel, err);
reportAssistantError(operation, err);
const resolution = resolveAssistantError(err, fallback);
finalizeStreamingError(conversationId, resolution, set, retry);
}
@@ -929,7 +929,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
void get().loadThread(activeThreadIdToLoad);
}
} catch (err) {
console.error('[AIAssistant] fetchThreads failed:', err);
reportAssistantError('fetchThreads', err);
set((s) => {
s.isLoadingThreads = false;
for (const conv of Object.values(s.conversations)) {
@@ -1015,7 +1015,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
console.error('[AIAssistant] loadThread failed:', err);
reportAssistantError('loadThread', err);
set((s) => {
s.isLoadingThread = false;
});
@@ -1068,7 +1068,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
disconnectAndCommit(id, set, get);
if (conv.threadId) {
updateThread(conv.threadId, { archived: true }).catch((err) => {
console.error('[AIAssistant] archiveThread failed:', err);
reportAssistantError('archiveThread', err);
});
set((state) => {
const c = state.conversations[id];
@@ -1112,7 +1112,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
})
.catch((err) => {
console.error('[AIAssistant] restoreThread failed:', err);
reportAssistantError('restoreThread', err);
});
},
@@ -1149,7 +1149,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
}
});
} catch (err) {
console.error('[AIAssistant] renameThread failed:', err);
reportAssistantError('renameThread', err);
set((state) => {
if (state.conversations[id]) {
state.conversations[id].title = previousTitle;
@@ -1189,7 +1189,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
try {
await cancelExecution(existingThreadId);
} catch (err) {
console.error('[AIAssistant] cancelExecution failed:', err);
reportAssistantError('cancelExecution', err);
}
}
}
@@ -1261,7 +1261,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
console.error('[AIAssistant] sendMessage failed:', err);
reportAssistantError('sendMessage', err);
const resolution = resolveAssistantError(
err,
'Something went wrong while fetching the response. Please try again.',
@@ -1296,7 +1296,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
conversationId,
() => approveExecution(approvalId),
'Something went wrong while processing the approval. Please try again.',
'[AIAssistant] approveAction failed:',
'approveAction',
set,
get,
run,
@@ -1311,7 +1311,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
try {
await rejectExecution(approvalId);
} catch (err) {
console.error('[AIAssistant] rejectAction failed:', err);
reportAssistantError('rejectAction', err);
}
set((s) => {
const st = s.streams[conversationId];
@@ -1331,7 +1331,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
const conv = get().conversations[conversationId];
if (conv?.threadId) {
cancelExecution(conv.threadId).catch((err) => {
console.error('[AIAssistant] cancelExecution failed:', err);
reportAssistantError('cancelExecution', err);
});
}
},
@@ -1366,7 +1366,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
conversationId,
() => regenerateMessage(messageId),
'Something went wrong while regenerating the response. Please try again.',
'[AIAssistant] regenerateAssistantMessage failed:',
'regenerateAssistantMessage',
set,
get,
run,
@@ -1398,7 +1398,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
try {
await submitFeedback(messageId, rating, comment);
} catch (err) {
console.error('[AIAssistant] submitMessageFeedback failed:', err);
reportAssistantError('submitMessageFeedback', err);
}
},
@@ -1424,7 +1424,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
conversationId,
() => clarifyExecution(clarificationId, answers),
'Something went wrong while processing your answers. Please try again.',
'[AIAssistant] submitClarification failed:',
'submitClarification',
set,
get,
run,

View File

@@ -0,0 +1,51 @@
import * as Sentry from '@sentry/react';
import { AxiosError } from 'axios';
import { ErrorCodeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { reportAssistantError } from '../reportAssistantError';
jest.mock('@sentry/react', () => ({
captureException: jest.fn(),
}));
const mockCaptureException = jest.mocked(Sentry.captureException);
function restError(status: number, code: string): AxiosError {
const err = new AxiosError('Request failed');
err.response = {
status,
data: { error: { code, message: 'backend message' } },
} as AxiosError['response'];
return err;
}
describe('reportAssistantError', () => {
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
mockCaptureException.mockClear();
});
it('reports an unexpected error tagged with the feature and operation', () => {
const err = restError(500, ErrorCodeDTO.internal_error);
reportAssistantError('sendMessage', err);
expect(mockCaptureException).toHaveBeenCalledWith(err, {
tags: { feature: 'noz', operation: 'sendMessage' },
});
});
it.each([
['a quota limit', restError(429, ErrorCodeDTO.daily_message_limit)],
['a permission error', restError(403, ErrorCodeDTO.permission_denied)],
['a busy thread', restError(409, ErrorCodeDTO.thread_busy)],
])('does not report %s', (_, err) => {
reportAssistantError('sendMessage', err);
expect(mockCaptureException).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,28 @@
import * as Sentry from '@sentry/react';
import { ErrorCodeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolveAssistantError } from './resolveAssistantError';
// Account and thread states the UI already explains. Quota limits are skipped
// too; aborts, 401/403 and network drops are dropped by the global Sentry filter.
const EXPECTED_ERROR_CODES = new Set<ErrorCodeDTO>([
ErrorCodeDTO.permission_denied,
ErrorCodeDTO.user_disabled,
ErrorCodeDTO.org_disabled,
ErrorCodeDTO.thread_busy,
ErrorCodeDTO.thread_has_active_execution,
]);
function isExpectedAssistantError(err: unknown): boolean {
const { code, isRateLimit } = resolveAssistantError(err, '');
return isRateLimit || (code !== undefined && EXPECTED_ERROR_CODES.has(code));
}
export function reportAssistantError(operation: string, err: unknown): void {
// eslint-disable-next-line no-console
console.error(`[AIAssistant] ${operation} failed:`, err);
if (isExpectedAssistantError(err)) {
return;
}
Sentry.captureException(err, { tags: { feature: 'noz', operation } });
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -71,6 +71,20 @@ 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.
@@ -168,6 +182,10 @@ 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

@@ -26,9 +26,8 @@ const bucketCacheCellSteps = 60
type BucketCache interface {
// cached portion + list of gaps to fetch
GetMissRanges(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step) (cached *qbtypes.Result, missing []*qbtypes.TimeRange)
// store fresh buckets for future hits; only the ranges in the map were
// queried for fresh, the rest of it came from the cache
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats)
// store fresh buckets for future hits
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result)
}
// bucketCache implements the BucketCache interface.
@@ -117,7 +116,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Merge buckets into a single result
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings, startMs, endMs)
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings)
// Filter the merged result to only include values within the requested time range
mergedResult = bc.filterResultToTimeRange(mergedResult, q, startMs, endMs, stepMs)
@@ -126,7 +125,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Put stores fresh query results in the cache.
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) {
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result) {
// Get query window
startMs, endMs := q.Window()
@@ -189,7 +188,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
// Convert trimmed result to buckets, one per grid cell it spans
cellWidthMs := bucketCacheCellSteps * stepMs
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs, execStatsForQueriedTimeRanges)
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs)
cellKeys := make([]string, len(freshBuckets))
cellEntries := make([]cachetypes.Cacheable, len(freshBuckets))
@@ -211,7 +210,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
cellEntry = cellEntries[i].(*qbtypes.CachedData)
}
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket, execStatsForQueriedTimeRanges)
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket)
if !changed {
continue
}
@@ -464,7 +463,7 @@ func (bc *bucketCache) filterRelevantBuckets(buckets []*qbtypes.CachedBucket, st
}
// mergeBuckets combines multiple cached buckets into a single result.
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string, startMs, endMs uint64) *qbtypes.Result {
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string) *qbtypes.Result {
if len(buckets) == 0 {
return &qbtypes.Result{}
}
@@ -472,13 +471,12 @@ func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.Cach
// All buckets should have the same type
resultType := buckets[0].Type
// A bucket can reach past the window; only the part inside it is served
// Aggregate stats
var totalStats qbtypes.ExecStats
for _, bucket := range buckets {
servedStats := bucket.ProrateStatsToWindow(startMs, endMs)
totalStats.RowsScanned += servedStats.RowsScanned
totalStats.BytesScanned += servedStats.BytesScanned
totalStats.DurationMS += servedStats.DurationMS
totalStats.RowsScanned += bucket.Stats.RowsScanned
totalStats.BytesScanned += bucket.Stats.BytesScanned
totalStats.DurationMS += bucket.Stats.DurationMS
}
// Merge values based on type
@@ -675,7 +673,7 @@ func (bc *bucketCache) isEmptyResult(result *qbtypes.Result) (isEmpty bool, isFi
}
// resultToBuckets converts a query result into time-based buckets.
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) []*qbtypes.CachedBucket {
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64) []*qbtypes.CachedBucket {
// Check if result is empty
isEmpty, isFiltered := bc.isEmptyResult(result)
@@ -687,7 +685,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
}
// Empty filtered results still become buckets, so the range is not re-queried
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs, execStatsForQueriedTimeRanges)
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs)
if err != nil {
bc.logger.ErrorContext(ctx, "failed to convert result to buckets", errors.Attr(err))
return nil
@@ -699,7 +697,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
// and reports whether the cell changed: a bucket already covering the fresh
// one leaves it as is, buckets inside the fresh one are replaced, buckets
// overlapping or edge to edge with it are unioned, and the rest are kept apart.
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) ([]*qbtypes.CachedBucket, bool) {
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket) ([]*qbtypes.CachedBucket, bool) {
keptBuckets := make([]*qbtypes.CachedBucket, 0, len(cellBuckets)+1)
touchingBuckets := []*qbtypes.CachedBucket{}
for _, cellBucket := range cellBuckets {
@@ -712,7 +710,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
keptBuckets = append(keptBuckets, cellBucket)
}
}
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets, execStatsForQueriedTimeRanges))
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets))
slices.SortFunc(keptBuckets, func(a, b *qbtypes.CachedBucket) int {
return cmp.Compare(a.StartMs, b.StartMs)
@@ -723,16 +721,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
// unionBuckets widens the fresh bucket by the buckets it touches. Buckets
// inside it are replaced outright, so only a genuine partial overlap decodes
// anything.
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) *qbtypes.CachedBucket {
// Data queried again takes the new query's cost, which the fresh bucket
// carries; a touching bucket keeps its cost only for what was not queried again
for _, touchingBucket := range touchingBuckets {
keptStats := touchingBucket.ProrateStatsToUnqueried(execStatsForQueriedTimeRanges)
freshBucket.Stats.RowsScanned += keptStats.RowsScanned
freshBucket.Stats.BytesScanned += keptStats.BytesScanned
freshBucket.Stats.DurationMS += keptStats.DurationMS
}
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket) *qbtypes.CachedBucket {
bucketsToMerge := []*qbtypes.CachedBucket{freshBucket}
for _, touchingBucket := range touchingBuckets {
if !freshBucket.Contains(touchingBucket) {
@@ -753,11 +742,14 @@ func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.Ca
EndMs: freshBucket.EndMs,
Type: freshBucket.Type,
Value: value,
Stats: freshBucket.Stats,
Stats: qbtypes.ExecStats{StepIntervals: freshBucket.Stats.StepIntervals},
}
for _, mergedBucket := range bucketsToMerge {
unionBucket.StartMs = min(unionBucket.StartMs, mergedBucket.StartMs)
unionBucket.EndMs = max(unionBucket.EndMs, mergedBucket.EndMs)
unionBucket.Stats.RowsScanned += mergedBucket.Stats.RowsScanned
unionBucket.Stats.BytesScanned += mergedBucket.Stats.BytesScanned
unionBucket.Stats.DurationMS += mergedBucket.Stats.DurationMS
}
return unionBucket
}

View File

@@ -30,7 +30,7 @@ func BenchmarkBucketCache_GetMissRanges(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
}
// Create test queries with varying cache hit patterns
@@ -121,7 +121,7 @@ func BenchmarkBucketCache_Put(b *testing.B) {
for i := 0; i < b.N; i++ {
for j := 0; j < tc.numQueries; j++ {
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j], map[qbtypes.TimeRange]qbtypes.ExecStats{{From: queries[j].startMs, To: queries[j].endMs}: results[j].Stats})
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j])
}
}
})
@@ -259,7 +259,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
}
b.ResetTimer()
@@ -284,7 +284,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
case 2: // Partial read
query := &mockQuery{
fingerprint: fmt.Sprintf("concurrent-query-%d", i%100),

View File

@@ -59,7 +59,7 @@ func TestBucketCacheStepAlignment(t *testing.T) {
}
// Put result in cache
bc.Put(ctx, orgID, query, step, result, nil)
bc.Put(ctx, orgID, query, step, result)
// Get cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
@@ -109,7 +109,7 @@ func TestBucketCacheNoStepInterval(t *testing.T) {
}
// Should cache the entire range when step is 0
bc.Put(ctx, orgID, query, step, result, nil)
bc.Put(ctx, orgID, query, step, result)
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
assert.NotNil(t, cached)

View File

@@ -156,7 +156,7 @@ func TestBucketCache_Put_And_Get(t *testing.T) {
}
// Store in cache
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Wait a bit for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -189,7 +189,7 @@ func TestBucketCache_PartialHit(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 3000, 1000),
}
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
// Wait for cache write
time.Sleep(10 * time.Millisecond)
@@ -225,7 +225,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 2000, 100),
}, nil)
})
query2 := &mockQuery{
fingerprint: "test-query",
@@ -235,7 +235,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
bc.Put(context.Background(), valuer.UUID{}, query2, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 3000, 4000, 100),
}, nil)
})
// Wait for cache writes
time.Sleep(10 * time.Millisecond)
@@ -280,7 +280,7 @@ func TestBucketCache_FluxInterval(t *testing.T) {
}
// This should not be cached due to flux interval
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Wait a bit
time.Sleep(10 * time.Millisecond)
@@ -358,7 +358,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
{Series: []*qbtypes.TimeSeries{series1}},
},
},
}, nil)
})
// Cache second part
query2 := &mockQuery{
@@ -374,7 +374,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
{Series: []*qbtypes.TimeSeries{series2}},
},
},
}, nil)
})
// Wait for cache writes
time.Sleep(10 * time.Millisecond)
@@ -441,7 +441,7 @@ func TestBucketCache_RawData(t *testing.T) {
Value: rawData,
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -481,7 +481,7 @@ func TestBucketCache_ScalarData(t *testing.T) {
Value: scalarData,
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -509,7 +509,7 @@ func TestBucketCache_EmptyFingerprint(t *testing.T) {
Value: createTestTimeSeries("A", 1000, 5000, 1000),
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
// Should still be able to retrieve
@@ -564,7 +564,7 @@ func TestBucketCache_ConcurrentAccess(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries(fmt.Sprintf("Q%d", id), query.startMs, query.endMs, 100),
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result, nil)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result)
done <- true
}(i)
}
@@ -624,7 +624,7 @@ func TestBucketCache_GetMissRanges_FluxInterval(t *testing.T) {
},
}
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult)
// Get miss ranges
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -686,7 +686,7 @@ func TestBucketCache_Put_FluxIntervalTrimming(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Retrieve cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -756,7 +756,7 @@ func TestBucketCache_Put_EntireRangeInFluxInterval(t *testing.T) {
}
// Put the result - should not cache anything
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Try to get cached data - should have no cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -862,7 +862,7 @@ func TestBucketCache_EmptyDataHandling(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result)
// Wait a bit for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -927,7 +927,7 @@ func TestBucketCache_PartialValues(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Wait for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -997,7 +997,7 @@ func TestBucketCache_AllPartialValues(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
// Wait for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -1058,7 +1058,7 @@ func TestBucketCache_FilteredCachedResults(t *testing.T) {
}
// Cache the wide range
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
time.Sleep(10 * time.Millisecond)
// Now query for a smaller range (2000-3500ms)
@@ -1125,7 +1125,7 @@ func TestBucketCache_PromQLKeepsTheValueAtTheWindowEnd(t *testing.T) {
}},
}},
},
}, nil)
})
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
@@ -1291,7 +1291,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1345,7 +1345,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1397,7 +1397,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1454,7 +1454,7 @@ func TestBucketCache_NoCache(t *testing.T) {
}
// Put the result in cache
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
time.Sleep(10 * time.Millisecond)
// Verify data is cached
@@ -1475,12 +1475,11 @@ func TestBucketCachePutSlicesAtCellBoundaries(t *testing.T) {
// a 1s step gives 60s cells, so 30s to 150s spans three of them
query := &mockQuery{fingerprint: "sliced-query", startMs: 30000, endMs: 150000}
result := &qbtypes.Result{
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 30000, 150000, 1000),
Stats: qbtypes.ExecStats{RowsScanned: 120, BytesScanned: 1200, DurationMS: 12},
}
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: 30000, To: 150000}: result.Stats})
})
type bucketShape struct {
cell, startMs, endMs, rowsScanned uint64
@@ -1540,7 +1539,7 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
name: "OverlappingWrites_BecomeOne",
firstWindow: qbtypes.TimeRange{From: 1000, To: 4000},
secondWindow: qbtypes.TimeRange{From: 3000, To: 6000},
expectedBuckets: []bucketShape{{1000, 6000, 5}},
expectedBuckets: []bucketShape{{1000, 6000, 6}},
expectedMissingRanges: []*qbtypes.TimeRange{},
expectedValueCount: 5,
},
@@ -1571,13 +1570,12 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
for _, window := range []qbtypes.TimeRange{testCase.firstWindow, testCase.secondWindow} {
query := &mockQuery{fingerprint: "absorb-query", startMs: window.From, endMs: window.To}
result := &qbtypes.Result{
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", window.From, window.To, 1000),
// one row per second, so a bucket's stats read as the seconds of data it holds
// one row per second, so a bucket's stats read as the seconds it was scanned for
Stats: qbtypes.ExecStats{RowsScanned: (window.To - window.From) / 1000},
}
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{window: result.Stats})
})
}
query := &mockQuery{
@@ -1611,7 +1609,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 10000, 1000),
Warnings: []string{"from the wide write"},
}, nil)
})
// a write already covered by the cell's bucket must not rewrite the entry,
// which shows as its warnings never arriving
@@ -1620,7 +1618,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 3000, 5000, 1000),
Warnings: []string{"from the inside write"},
}, nil)
})
var cellEntry qbtypes.CachedData
require.NoError(t, bc.cache.Get(ctx, orgID, bc.generateCacheKey(wide, 0), &cellEntry))

View File

@@ -828,7 +828,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
return nil, err
}
// Store in cache for future use
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
q.bucketCache.Put(ctx, orgID, query, step, result)
return result, nil
}
}
@@ -884,19 +884,16 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
if err != nil {
return nil, err
}
startMs, endMs := query.Window()
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
q.bucketCache.Put(ctx, orgID, query, step, result)
return result, nil
}
}
// Calculate total stats and filter out nil results
validResults := make([]*qbtypes.Result, 0, len(freshResults))
execStatsForQueriedTimeRanges := make(map[qbtypes.TimeRange]qbtypes.ExecStats, len(freshResults))
for i, result := range freshResults {
for _, result := range freshResults {
if result != nil {
validResults = append(validResults, result)
execStatsForQueriedTimeRanges[*missingRanges[i]] = result.Stats
totalStats.RowsScanned += result.Stats.RowsScanned
totalStats.BytesScanned += result.Stats.BytesScanned
totalStats.DurationMS += result.Stats.DurationMS
@@ -911,7 +908,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
mergedResult.Stats.DurationMS += totalStats.DurationMS
// Store merged result in cache
q.bucketCache.Put(ctx, orgID, query, step, mergedResult, execStatsForQueriedTimeRanges)
q.bucketCache.Put(ctx, orgID, query, step, mergedResult)
return mergedResult, nil
}

View File

@@ -30,6 +30,10 @@ 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

@@ -43,23 +43,6 @@ func (c *CachedBucket) Touches(other *CachedBucket) bool {
return c.StartMs <= other.EndMs && other.StartMs <= c.EndMs
}
// ProrateStatsToWindow returns the share of the stats for the part of the
// bucket inside [startMs, endMs).
func (c *CachedBucket) ProrateStatsToWindow(startMs, endMs uint64) ExecStats {
return c.Stats.prorate(overlapMs(c.StartMs, c.EndMs, startMs, endMs), c.EndMs-c.StartMs)
}
// ProrateStatsToUnqueried returns the share of the stats for the part of the
// bucket no queried range covers.
func (c *CachedBucket) ProrateStatsToUnqueried(execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ExecStats {
widthMs := c.EndMs - c.StartMs
queriedMs := uint64(0)
for queried := range execStatsForQueriedTimeRanges {
queriedMs += overlapMs(c.StartMs, c.EndMs, queried.From, queried.To)
}
return c.Stats.prorate(widthMs-min(queriedMs, widthMs), widthMs)
}
// CachedData represents the full cached data for a query.
type CachedData struct {
Buckets []*CachedBucket `json:"buckets"`
@@ -105,7 +88,7 @@ func (c *CachedData) Cost() int64 {
return size
}
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ([]*CachedBucket, error) {
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) ([]*CachedBucket, error) {
tsData, ok := r.Value.(*TimeSeriesData)
if !ok || tsData == nil {
return nil, errors.NewInternalf(errors.CodeInternal, "result of type %s cannot be bucketed", r.Type.StringValue())
@@ -128,39 +111,18 @@ func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, e
if err != nil {
return nil, err
}
// A slice costs what was queried inside it; the rest of the result came
// out of the cache and is costed there already
sliceStats := ExecStats{StepIntervals: maps.Clone(r.Stats.StepIntervals)}
for queried, stats := range execStatsForQueriedTimeRanges {
queriedMs := overlapMs(from, to, queried.From, queried.To)
if queriedMs == 0 {
continue
}
share := stats.prorate(queriedMs, queried.To-queried.From)
sliceStats.RowsScanned += share.RowsScanned
sliceStats.BytesScanned += share.BytesScanned
sliceStats.DurationMS += share.DurationMS
}
cellBuckets = append(cellBuckets, &CachedBucket{
StartMs: from,
EndMs: to,
Type: r.Type,
Value: value,
Stats: sliceStats,
Stats: r.Stats.prorate(to-from, endMs-startMs),
})
from = to
}
return cellBuckets, nil
}
// overlapMs is the length of [aFromMs, aToMs) ∩ [bFromMs, bToMs).
func overlapMs(aFromMs, aToMs, bFromMs, bToMs uint64) uint64 {
if fromMs, toMs := max(aFromMs, bFromMs), min(aToMs, bToMs); fromMs < toMs {
return toMs - fromMs
}
return 0
}
// prorate returns the share of the stats that partMs out of wholeMs of the
// scanned window accounts for.
func (e ExecStats) prorate(partMs, wholeMs uint64) ExecStats {

View File

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

View File

@@ -442,55 +442,3 @@ def test_builder_refreshing_a_sliding_time_range(
assert uncached.status_code == HTTPStatus.OK, uncached.text
assert_results_equal(from_cache.json(), uncached.json(), "A", "the twentieth refresh")
def test_builder_refreshing_does_not_inflate_rows_scanned(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_metrics: Callable[[list[Metrics]], None],
) -> None:
metric_name = f"cache_rows_scanned_{uuid4().hex[:8]}"
# 90 minutes back so even the last refresh closes clear of the flux
# interval, which holds recent data out of the cache
start_time = datetime.fromtimestamp(int((datetime.now(tz=UTC) - timedelta(minutes=90)).timestamp()) // 60 * 60, tz=UTC)
start_time_ms = int(start_time.timestamp() * 1000)
query = [build_builder_query("A", metric_name, "max", "max")]
insert_metrics(
[
Metrics(
metric_name=metric_name,
labels={"service": "api"},
timestamp=start_time + timedelta(minutes=minute),
value=minute,
type_="Gauge",
is_monotonic=False,
)
for minute in range(70)
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
# a dashboard left open on a thirty minute range, re-running a minute later
# each time. rowsScanned is a cost indicator, so a refresh served mostly out
# of the cache cannot claim more than every read made so far: the first
# full read and then one new minute per refresh, measured with the cache off
uncached_rows_scanned_so_far = 0
for refresh in range(10):
refresh_start_ms = start_time_ms + refresh * MINUTE_MS
refresh_end_ms = refresh_start_ms + 30 * MINUTE_MS
uncached_start_ms = refresh_start_ms if refresh == 0 else refresh_end_ms - MINUTE_MS
uncached_response = make_query_request(signoz, token, uncached_start_ms, refresh_end_ms, query, no_cache=True)
assert uncached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: uncached read failed: {uncached_response.text}"
uncached_rows_scanned_so_far += uncached_response.json()["data"]["meta"]["rowsScanned"]
assert uncached_rows_scanned_so_far > 0, f"refresh {refresh}: uncached read reported no rows scanned"
cached_response = make_query_request(signoz, token, refresh_start_ms, refresh_end_ms, query, no_cache=False)
assert cached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: cached read failed: {cached_response.text}"
cached_rows_scanned = cached_response.json()["data"]["meta"]["rowsScanned"]
assert cached_rows_scanned <= uncached_rows_scanned_so_far, f"refresh {refresh}: cached read reported {cached_rows_scanned} rows scanned, more than the {uncached_rows_scanned_so_far} rows all uncached reads scanned so far"

View File

@@ -144,14 +144,13 @@ 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/avg over DateTime64, and rate_*
# KNOWN GAP, pinned deliberately: ClickHouse rejects sum 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)",