Compare commits

..

8 Commits

Author SHA1 Message Date
Naman Verma
105f023f32 Merge branch 'main' into nv/exec-stats 2026-11-23 10:11:50 +05:30
Naman Verma
8101a79371 Merge branch 'main' into nv/exec-stats 2026-11-16 10:43:03 +05:30
Naman Verma
62d477e920 Merge branch 'main' into nv/exec-stats 2026-11-09 12:20:27 +05:30
Naman Verma
fe45b9dcae Merge branch 'main' into nv/exec-stats 2026-11-06 00:51:46 +05:30
Naman Verma
63ee60a40c fix(querier): stop cache refreshes from inflating exec stats 2026-11-06 00:51:03 +05:30
Naman Verma
29a393e47e Merge branch 'main' into nv/exec-stats 2026-11-05 10:51:11 +05:30
Naman Verma
c58f76f998 Merge branch 'main' into nv/exec-stats 2026-11-03 11:34:10 +05:30
Naman Verma
e39ad9e221 test: check how exec stats fail 2026-11-02 22:24:22 +05:30
57 changed files with 3770 additions and 1318 deletions

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

@@ -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

@@ -56,7 +56,6 @@
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/ui": "0.4.0-rc.5",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",

View File

@@ -82,9 +82,6 @@ importers:
'@signozhq/icons':
specifier: 0.4.0
version: 0.4.0
'@signozhq/noz-client':
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.0-rc.5
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3251,13 +3248,6 @@ packages:
'@signozhq/icons@0.4.0':
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
react-query: ^3.39.3
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
peerDependencies:
@@ -12383,12 +12373,6 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
dependencies:
axios: 1.21.1
react: 18.2.0
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)

View File

@@ -11,7 +11,7 @@
* to resume, which each return a new executionId to open a fresh SSE stream.
*
* Types in this file re-use the OpenAPI-generated DTOs in
* `@signozhq/noz-client`.
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
* Local types are defined only when the UI needs a different shape — for
* example, the SSE event union adds a literal `type` discriminator that the
* generated event DTOs leave loose.
@@ -30,11 +30,16 @@ import rotateSession from 'api/v2/sessions/rotate/post';
import afterLogin from 'AppRoutes/utils';
import type {
ActionResultResponseDTO,
ApprovalEventDTO,
ApproveResponseDTO,
CancelResponseDTO,
ClarificationEventDTO,
ClarifyResponseDTO,
ConversationEventDTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
DoneEventDTO,
ErrorEventDTO,
ExecutionStateDTO,
FeedbackRatingDTO,
ListThreadsApiV1AssistantThreadsGetArchived,
@@ -42,15 +47,20 @@ import type {
MessageContextDTO,
MessageContextDTOSource,
MessageContextDTOType,
MessageEventDTO,
MessageSummaryDTO,
RegenerateResponseDTO,
StatusEventDTO,
ThinkingEventDTO,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
ThreadSummaryDTO,
ChipDTO,
ChipsResponseDTO,
PageTypeDTO,
} from '@signozhq/noz-client';
ToolCallEventDTO,
ToolResultEventDTO,
} from './sigNozAIAssistantAPI.schemas';
import { LOCALSTORAGE } from 'constants/localStorage';
import {
@@ -60,10 +70,6 @@ import {
} from '../AIAPIInstance';
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
import type { SSEEvent } from './sseEvent';
export type { SSEEvent };
// ---------------------------------------------------------------------------
// SSE-only auth wrapper.
//
@@ -177,6 +183,26 @@ async function fetchSSEWithAuth(
return res;
}
// ---------------------------------------------------------------------------
// SSE event types
//
// The generated event DTOs each declare `type?: string` (loose). The UI needs
// a discriminated union, so we intersect each variant with a string-literal
// `type` to enable narrowing via `event.type === 'status'`.
// ---------------------------------------------------------------------------
export type SSEEvent =
| (StatusEventDTO & { type: 'status' })
| (MessageEventDTO & { type: 'message' })
| (ThinkingEventDTO & { type: 'thinking' })
| (ToolCallEventDTO & { type: 'tool_call' })
| (ToolResultEventDTO & { type: 'tool_result' })
| (ApprovalEventDTO & { type: 'approval' })
| (ClarificationEventDTO & { type: 'clarification' })
| (ErrorEventDTO & { type: 'error' })
| (ConversationEventDTO & { type: 'conversation' })
| (DoneEventDTO & { type: 'done' });
/** String-literal view of `ExecutionStateDTO` for ergonomic comparisons. */
export type ExecutionState = `${ExecutionStateDTO}`;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,32 +0,0 @@
import type {
ApprovalEventDTO,
ClarificationEventDTO,
ConversationEventDTO,
DoneEventDTO,
ErrorEventDTO,
MessageEventDTO,
StatusEventDTO,
ThinkingEventDTO,
ToolCallEventDTO,
ToolResultEventDTO,
} from '@signozhq/noz-client';
// ---------------------------------------------------------------------------
// SSE event types
//
// The generated event DTOs each declare `type?: string` (loose). The UI needs
// a discriminated union, so we intersect each variant with a string-literal
// `type` to enable narrowing via `event.type === 'status'`.
// ---------------------------------------------------------------------------
export type SSEEvent =
| (StatusEventDTO & { type: 'status' })
| (MessageEventDTO & { type: 'message' })
| (ThinkingEventDTO & { type: 'thinking' })
| (ToolCallEventDTO & { type: 'tool_call' })
| (ToolResultEventDTO & { type: 'tool_result' })
| (ApprovalEventDTO & { type: 'approval' })
| (ClarificationEventDTO & { type: 'clarification' })
| (ErrorEventDTO & { type: 'error' })
| (ConversationEventDTO & { type: 'conversation' })
| (DoneEventDTO & { type: 'done' });

View File

@@ -12,5 +12,4 @@
import '@signozhq/design-tokens';
import '@signozhq/icons';
import '@signozhq/noz-client';
import '@signozhq/ui';

View File

@@ -194,7 +194,7 @@ export default function ConversationView({
}
return (
<div className={conversationClass} data-testid="conversation-view">
<div className={conversationClass}>
<VirtualizedMessages
key={conversationId}
conversationId={conversationId}

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';

View File

@@ -16,11 +16,11 @@ import {
import { v4 as uuidv4 } from 'uuid';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import type { MessageActionDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
restoreExecution,
revertExecution,

View File

@@ -1,4 +1,7 @@
import { MessageActionDTO, MessageActionKindDTO } from '@signozhq/noz-client';
import {
MessageActionDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import logEvent from 'api/common/logEvent';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';

View File

@@ -1,9 +1,9 @@
import { undoExecution } from 'api/ai-assistant/chat';
import type { MessageActionDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import { ApplyFilterSignalDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -2,7 +2,7 @@ import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
SavedViewEntityDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
getSavedView,
listSavedViews,

View File

@@ -1,7 +1,7 @@
import {
type MessageActionDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
isSavedViewOpenAction,

View File

@@ -1,7 +1,7 @@
import {
ApplyFilterSignalDTO,
type MessageActionDTOQuery,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import type { MessageActionDTOQuery } from '@signozhq/noz-client';
import type { MessageActionDTOQuery } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { normalizeTimeToMs } from 'utils/timeUtils';
export interface ActionTimeRange {

View File

@@ -1,5 +1,8 @@
import type { MessageActionDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO, SavedViewEntityDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
SavedViewEntityDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { DataSource } from 'types/common/queryBuilder';
import { ResourceType } from './resourceRoute';

View File

@@ -8,7 +8,7 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import type {
ApprovalEventDTO,
ApprovalEventDTODiff,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
Check,
Columns2,

View File

@@ -6,11 +6,11 @@ import { Input } from '@signozhq/ui/input';
import { Select } from '@signozhq/ui/select';
import type { SelectItemType } from '@signozhq/ui/select';
import logEvent from 'api/common/logEvent';
import { ClarificationFieldTypeDTO } from '@signozhq/noz-client';
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
ClarificationEventDTO,
ClarificationFieldEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { CircleHelp, Send, X } from '@signozhq/icons';
import { AIAssistantEvents } from '../../events';

View File

@@ -167,7 +167,6 @@ export default function ConversationItem({
return (
<div
className={itemClass}
data-testid={`ai-conversation-item-${conversation.id}`}
onClick={(): void => onSelect(conversation.id)}
role="button"
tabIndex={0}

View File

@@ -5,7 +5,7 @@ import remarkGfm from 'remark-gfm';
import { Button } from '@signozhq/ui/button';
import { RotateCw, TriangleAlert } from '@signozhq/icons';
import { RetryActionDTO } from '@signozhq/noz-client';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
// Side-effect: registers all built-in block types into the BlockRegistry
import '../blocks';

View File

@@ -1,6 +1,9 @@
import React from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Message } from '../../../types';

View File

@@ -10,7 +10,7 @@ import { useTimezone } from 'providers/Timezone';
import logEvent from 'api/common/logEvent';
import { FeedbackRatingDTO } from '@signozhq/noz-client';
import { FeedbackRatingDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { AIAssistantEvents } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';

View File

@@ -6,7 +6,7 @@ import remarkGfm from 'remark-gfm';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { useVariant } from '../../VariantContext';
import { StreamingEventItem } from '../../types';

View File

@@ -7,7 +7,7 @@ import { ArrowDown } from '@signozhq/icons';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';

View File

@@ -1,4 +1,4 @@
import type { ChipDTO } from '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
/** Static empty-state chips used when the contextual chips API is unavailable. */
export const EMPTY_STATE_CHIPS_FALLBACK: ChipDTO[] = [

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { getEmptyStateChips } from 'api/ai-assistant/chat';
import type { ChipDTO } from '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { matchRoute } from 'lib/router/matchRoute';

View File

@@ -4,7 +4,7 @@ import {
MessageContextDTOType,
MessageRoleDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
MessageContext,
SSEEvent,

View File

@@ -7,8 +7,8 @@ import { immer } from 'zustand/middleware/immer';
import type {
MessageActionDTO,
MessageSummaryDTOBlocksAnyOfItem,
} from '@signozhq/noz-client';
import { RetryActionDTO } from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
approveExecution,

View File

@@ -1,7 +1,8 @@
/**
* UI types for the AI Assistant.
*
* Wherever the OpenAPI-generated DTOs in `@signozhq/noz-client`
* Wherever the OpenAPI-generated DTOs in
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`
* already capture the right shape, this module re-exports them.
*
* A type is defined locally only when the UI needs a different shape than
@@ -19,7 +20,7 @@ import type {
MessageActionDTO,
MessageActionKindDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageContext } from 'api/ai-assistant/chat';
/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */

View File

@@ -1,5 +1,8 @@
import { AxiosError } from 'axios';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolveAssistantError } from '../resolveAssistantError';

View File

@@ -4,7 +4,7 @@ import {
RetryActionDTO,
type ErrorBodyDTO,
type ErrorResponseDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
export interface AssistantErrorResolution {
/** User-facing copy: code-specific FE copy → backend message → caller fallback. */

View File

@@ -1,5 +1,5 @@
import { renderHook } from '@testing-library/react';
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { AIAssistantVariant } from 'container/AIAssistant/VariantContext';
import ROUTES from 'constants/routes';
import { mockAppLocation } from 'tests/router-mocks';

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useAppLocation } from 'lib/router/useAppLocation';
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolvePageType } from 'container/AIAssistant/resolvePageType';
import { useVariant } from 'container/AIAssistant/VariantContext';

View File

@@ -11,7 +11,7 @@ import type {
MessageSummaryDTO,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
ApprovalActionTypeDTO,
@@ -22,7 +22,7 @@ import {
MessageActionKindDTO,
MessageContentTypeDTO,
MessageRoleDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
Conversation,
ConversationStreamState,

View File

@@ -3,11 +3,11 @@
* Do not hand-edit: regenerate instead.
*/
import type { MessageSummaryDTO } from '@signozhq/noz-client';
import type { MessageSummaryDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
MessageContextDTOSource,
MessageContextDTOType,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageBlock } from 'container/AIAssistant/types';
/** The opening question's contexts: the thread shows the @-picked ones, not the page it was asked from. */

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

@@ -26,8 +26,9 @@ 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
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result)
// 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)
}
// bucketCache implements the BucketCache interface.
@@ -116,7 +117,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Merge buckets into a single result
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings)
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings, startMs, endMs)
// Filter the merged result to only include values within the requested time range
mergedResult = bc.filterResultToTimeRange(mergedResult, q, startMs, endMs, stepMs)
@@ -125,7 +126,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) {
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) {
// Get query window
startMs, endMs := q.Window()
@@ -188,7 +189,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)
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs, execStatsForQueriedTimeRanges)
cellKeys := make([]string, len(freshBuckets))
cellEntries := make([]cachetypes.Cacheable, len(freshBuckets))
@@ -210,7 +211,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)
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket, execStatsForQueriedTimeRanges)
if !changed {
continue
}
@@ -463,7 +464,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) *qbtypes.Result {
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string, startMs, endMs uint64) *qbtypes.Result {
if len(buckets) == 0 {
return &qbtypes.Result{}
}
@@ -471,12 +472,13 @@ func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.Cach
// All buckets should have the same type
resultType := buckets[0].Type
// Aggregate stats
// A bucket can reach past the window; only the part inside it is served
var totalStats qbtypes.ExecStats
for _, bucket := range buckets {
totalStats.RowsScanned += bucket.Stats.RowsScanned
totalStats.BytesScanned += bucket.Stats.BytesScanned
totalStats.DurationMS += bucket.Stats.DurationMS
servedStats := bucket.ProrateStatsToWindow(startMs, endMs)
totalStats.RowsScanned += servedStats.RowsScanned
totalStats.BytesScanned += servedStats.BytesScanned
totalStats.DurationMS += servedStats.DurationMS
}
// Merge values based on type
@@ -673,7 +675,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) []*qbtypes.CachedBucket {
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) []*qbtypes.CachedBucket {
// Check if result is empty
isEmpty, isFiltered := bc.isEmptyResult(result)
@@ -685,7 +687,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)
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs, execStatsForQueriedTimeRanges)
if err != nil {
bc.logger.ErrorContext(ctx, "failed to convert result to buckets", errors.Attr(err))
return nil
@@ -697,7 +699,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) ([]*qbtypes.CachedBucket, bool) {
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) ([]*qbtypes.CachedBucket, bool) {
keptBuckets := make([]*qbtypes.CachedBucket, 0, len(cellBuckets)+1)
touchingBuckets := []*qbtypes.CachedBucket{}
for _, cellBucket := range cellBuckets {
@@ -710,7 +712,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
keptBuckets = append(keptBuckets, cellBucket)
}
}
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets))
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets, execStatsForQueriedTimeRanges))
slices.SortFunc(keptBuckets, func(a, b *qbtypes.CachedBucket) int {
return cmp.Compare(a.StartMs, b.StartMs)
@@ -721,7 +723,16 @@ 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) *qbtypes.CachedBucket {
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
}
bucketsToMerge := []*qbtypes.CachedBucket{freshBucket}
for _, touchingBucket := range touchingBuckets {
if !freshBucket.Contains(touchingBucket) {
@@ -742,14 +753,11 @@ func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.Ca
EndMs: freshBucket.EndMs,
Type: freshBucket.Type,
Value: value,
Stats: qbtypes.ExecStats{StepIntervals: freshBucket.Stats.StepIntervals},
Stats: freshBucket.Stats,
}
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)
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})
}
// 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])
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})
}
}
})
@@ -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)
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})
}
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)
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})
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)
bc.Put(ctx, orgID, query, step, result, nil)
// 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)
bc.Put(ctx, orgID, query, step, result, nil)
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)
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})
// 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)
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
// 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)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// 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)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result, nil)
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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult, nil)
// 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)
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})
// 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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// 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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result, nil)
// 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)
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})
// 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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// 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)
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
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)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Verify data is cached
@@ -1475,11 +1475,12 @@ 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}
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
result := &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
@@ -1539,7 +1540,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, 6}},
expectedBuckets: []bucketShape{{1000, 6000, 5}},
expectedMissingRanges: []*qbtypes.TimeRange{},
expectedValueCount: 5,
},
@@ -1570,12 +1571,13 @@ 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}
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
result := &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 it was scanned for
// one row per second, so a bucket's stats read as the seconds of data it holds
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{
@@ -1609,7 +1611,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
@@ -1618,7 +1620,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)
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
return result, nil
}
}
@@ -884,16 +884,19 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
if err != nil {
return nil, err
}
q.bucketCache.Put(ctx, orgID, query, step, result)
startMs, endMs := query.Window()
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
return result, nil
}
}
// Calculate total stats and filter out nil results
validResults := make([]*qbtypes.Result, 0, len(freshResults))
for _, result := range freshResults {
execStatsForQueriedTimeRanges := make(map[qbtypes.TimeRange]qbtypes.ExecStats, len(freshResults))
for i, 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
@@ -908,7 +911,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)
q.bucketCache.Put(ctx, orgID, query, step, mergedResult, execStatsForQueriedTimeRanges)
return mergedResult, nil
}

View File

@@ -43,6 +43,23 @@ 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"`
@@ -88,7 +105,7 @@ func (c *CachedData) Cost() int64 {
return size
}
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) ([]*CachedBucket, error) {
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ([]*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())
@@ -111,18 +128,39 @@ func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) (
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: r.Stats.prorate(to-from, endMs-startMs),
Stats: sliceStats,
})
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

@@ -1,65 +0,0 @@
import type { Locator, Page } from '@playwright/test';
import { LOGS_EXPLORER_PATH } from '../logs/explorer';
import { installFakeAssistant, type FakeAssistant } from './fake';
export const NOZ_NEW_PATH = '/ai-assistant/new';
const THREAD_PATH = /^\/ai-assistant\/([^/]+)$/;
export interface Noz {
/** Turns Noz on for this page against a fake AI service; call before the first navigation. */
enable(): Promise<FakeAssistant>;
gotoHome(): Promise<void>;
gotoNew(): Promise<void>;
gotoLogsExplorer(): Promise<void>;
reload(): Promise<void>;
navItem(): Locator;
/** "Ask Noz" in the bottom strip; opens the Noz drawer over the current page. */
askNozButton(): Locator;
newChatButton(): Locator;
/** A thread's row in the history list. */
historyItem(threadId: string): Locator;
input(): Locator;
/** Text in the open conversation, from either side. */
message(text: string): Locator;
/** Types `text` and presses Enter, as a user sends. */
send(text: string): Promise<void>;
/** The id in `/ai-assistant/:id`, `null` off the page. */
conversationId(): string | null;
}
export function nozDriver(page: Page): Noz {
const conversation = (): Locator => page.getByTestId('conversation-view');
const input = (): Locator => page.getByTestId('ai-chat-input-textarea');
return {
enable: () => installFakeAssistant(page),
gotoHome: async () => {
await page.goto('/home');
},
gotoNew: async () => {
await page.goto(NOZ_NEW_PATH);
},
gotoLogsExplorer: async () => {
await page.goto(LOGS_EXPLORER_PATH);
},
reload: async () => {
await page.reload();
},
navItem: () => page.getByTestId('nav-item-ai-assistant'),
askNozButton: () => page.getByTestId('bottom-strip-ask-noz-button'),
newChatButton: () => page.getByTestId('ai-assistant-new-conversation'),
historyItem: (threadId) =>
page.getByTestId(`ai-conversation-item-${threadId}`),
input,
message: (text) => conversation().getByText(text, { exact: true }),
send: async (text) => {
await input().fill(text);
await input().press('Enter');
},
conversationId: () =>
new URL(page.url()).pathname.match(THREAD_PATH)?.[1] ?? null,
};
}

View File

@@ -1,203 +0,0 @@
import { randomUUID } from 'node:crypto';
import type { Page, Route } from '@playwright/test';
import type { GetGlobalConfig200 } from '../schemas';
import type {
ChipsResponseDTO,
CreateMessageRequestDTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
ExecutionStateDTO,
MessageRoleDTO,
MessageSummaryDTO,
SSEEvent,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
} from './schemas';
export interface SentMessage {
threadId: string;
body: CreateMessageRequestDTO;
}
export interface FakeAssistant {
/** Queue the text of the next reply; a send with nothing queued gets a 500. */
replyWith(text: string): void;
/** Bodies the app POSTed to `/threads/:id/messages`, oldest first. */
sentMessages(): SentMessage[];
}
const ASSISTANT_PATH = '/api/v1/assistant';
// Calls made before the global config loads go out with an empty base URL.
const UNPREFIXED = /^\/(threads|executions|empty-state)(\/|$)/;
/** The path under the assistant API, or `null` for any other request. */
function assistantPath(url: URL): string | null {
const at = url.pathname.indexOf(`${ASSISTANT_PATH}/`);
if (at >= 0) {
return url.pathname.slice(at + ASSISTANT_PATH.length);
}
return UNPREFIXED.test(url.pathname) ? url.pathname : null;
}
const json = (route: Route, body: unknown, status = 200): Promise<void> =>
route.fulfill({ status, json: body });
// The generated enums are TS enums; a literal typed by their values can't drift.
const role = (value: `${MessageRoleDTO}`): MessageRoleDTO =>
value as MessageRoleDTO;
const state = (value: `${ExecutionStateDTO}`): ExecutionStateDTO =>
value as ExecutionStateDTO;
function replyEvents(
executionId: string,
messageId: string,
text: string,
): SSEEvent[] {
return [
{ type: 'status', executionId, state: state('running') },
{ type: 'message', executionId, messageId, delta: text, done: false },
{ type: 'message', executionId, messageId, delta: '', done: true },
{ type: 'done', executionId, tokenInput: 0, tokenOutput: 0, latencyMs: 0 },
];
}
const sse = (events: SSEEvent[]): string =>
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('');
/** Fakes the AI service the stack doesn't run, and enables Noz for this page only. */
export async function installFakeAssistant(page: Page): Promise<FakeAssistant> {
const threads = new Map<string, ThreadDetailResponseDTO>();
const executions = new Map<string, SSEEvent[]>();
const replies: string[] = [];
const sent: SentMessage[] = [];
const now = (): string => new Date().toISOString();
const message = (
messageRole: `${MessageRoleDTO}`,
content: string,
extra: Partial<MessageSummaryDTO> = {},
): MessageSummaryDTO => ({
messageId: randomUUID(),
role: role(messageRole),
content,
complete: true,
createdAt: now(),
updatedAt: now(),
...extra,
});
const createThread = (): CreateThreadResponseDTO => {
const threadId = randomUUID();
threads.set(threadId, {
threadId,
title: null,
state: null,
activeExecutionId: null,
archived: false,
createdAt: now(),
updatedAt: now(),
messages: [],
});
return { threadId };
};
const listThreads = (url: URL): ThreadListResponseDTO => {
const archived = url.searchParams.get('archived') === 'true';
return {
threads: [...threads.values()]
.filter((thread) => Boolean(thread.archived) === archived)
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
.map((thread) => ({
threadId: thread.threadId,
title: thread.title,
state: thread.state,
archived: thread.archived,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
})),
hasMore: false,
nextCursor: null,
};
};
const postMessage = async (
route: Route,
thread: ThreadDetailResponseDTO,
): Promise<void> => {
const body = route.request().postDataJSON() as CreateMessageRequestDTO;
sent.push({ threadId: thread.threadId, body });
const text = replies.shift();
if (text === undefined) {
await json(route, { error: 'no scripted reply' }, 500);
return;
}
const executionId = randomUUID();
const reply = message('assistant', text, { executionId });
executions.set(executionId, replyEvents(executionId, reply.messageId, text));
thread.messages?.push(
message('user', body.content, { contexts: body.contexts }),
reply,
);
thread.title ??= body.content;
thread.state = state('completed');
thread.updatedAt = now();
const response: CreateMessageResponseDTO = { executionId };
await json(route, response);
};
const handle = async (route: Route): Promise<void> => {
const url = new URL(route.request().url());
const method = route.request().method();
const path = assistantPath(url) ?? '';
const [, resource, id, sub] = path.split('/');
const thread = id ? threads.get(id) : undefined;
if (resource === 'threads' && !id && method === 'POST') {
return json(route, createThread());
}
if (resource === 'threads' && !id && method === 'GET') {
return json(route, listThreads(url));
}
if (resource === 'threads' && thread && !sub && method === 'GET') {
return json(route, thread);
}
if (resource === 'threads' && thread && sub === 'messages') {
return postMessage(route, thread);
}
if (resource === 'executions' && id && executions.has(id)) {
return route.fulfill({
status: 200,
contentType: 'text/event-stream',
body: sse(executions.get(id) ?? []),
});
}
if (resource === 'empty-state') {
const chips: ChipsResponseDTO = { chips: [] };
return json(route, chips);
}
return json(route, { error: `fake assistant: ${method} ${path}` }, 404);
};
await page.route((url) => assistantPath(url) !== null, handle);
await page.route(
(url) => url.pathname.endsWith('/api/v1/global/config'),
async (route) => {
const response = await route.fetch();
const body = (await response.json()) as GetGlobalConfig200;
body.data.ai_assistant_url = new URL(route.request().url()).origin;
await route.fulfill({ response, json: body });
},
);
return {
replyWith: (text) => {
replies.push(text);
},
sentMessages: () => [...sent],
};
}

View File

@@ -1,12 +0,0 @@
import { driver, kit, type Layer } from '../kit';
import { nozDriver, type Noz } from './driver';
export type { FakeAssistant, SentMessage } from './fake';
export const withNoz: Layer<{ noz: Noz }> = driver('noz', ({ page }) =>
nozDriver(page),
);
export const test = withNoz(kit);
export { expect } from '../kit';

View File

@@ -1,3 +0,0 @@
/** The AI service contract; `SSEEvent` adds the `type` discriminator the package's event DTOs leave loose. */
export type * from '@signozhq/noz-client';
export type { SSEEvent } from '../../../../frontend/src/api/ai-assistant/sseEvent';

View File

@@ -39,7 +39,6 @@
"license": "MIT",
"devDependencies": {
"@playwright/test": "1.57.0",
"@signozhq/noz-client": "1.13.0",
"@types/node": "^20.0.0",
"dotenv": "^16.0.0",
"eslint-plugin-playwright": "^2.10.2",

425
tests/e2e/pnpm-lock.yaml generated
View File

@@ -14,9 +14,6 @@ importers:
'@playwright/test':
specifier: 1.57.0
version: 1.57.0
'@signozhq/noz-client':
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react@18.3.1))(react@18.3.1)
'@types/node':
specifier: ^20.0.0
version: 20.19.20
@@ -41,10 +38,6 @@ importers:
packages:
'@babel/runtime@7.29.7':
resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==}
engines: {node: '>=6.9.0'}
'@eslint-community/eslint-utils@4.9.1':
resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
@@ -374,13 +367,6 @@ packages:
engines: {node: '>=18'}
hasBin: true
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
react-query: ^3.39.3
'@types/esrecurse@4.3.1':
resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}
@@ -403,51 +389,17 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
agent-base@6.0.2:
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
ajv@6.15.0:
resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
axios@1.21.1:
resolution: {integrity: sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==}
balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
balanced-match@4.0.4:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
big-integer@1.6.52:
resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==}
engines: {node: '>=0.6'}
brace-expansion@1.1.22:
resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==}
brace-expansion@5.0.12:
resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}
engines: {node: 20 || >=22}
broadcast-channel@3.7.0:
resolution: {integrity: sha512-cIAKJXAxGJceNZGTZSBzMxzyOn72cVgPnKx4dc6LRjQgbaJUQqhy5rzL3zbMxkMWsGKkv2hSFkPRMEXfoMZ2Mg==}
call-bind-apply-helpers@1.0.2:
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
engines: {node: '>= 0.4'}
combined-stream@1.0.8:
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
concat-map@0.0.1:
resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
cross-spawn@7.0.6:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -464,37 +416,10 @@ packages:
deep-is@0.1.4:
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
delayed-stream@1.0.0:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
detect-node@2.1.0:
resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}
dotenv@16.6.1:
resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}
engines: {node: '>=12'}
dunder-proto@1.0.1:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
es-define-property@1.0.1:
resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}
engines: {node: '>= 0.4'}
es-errors@1.3.0:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
es-object-atoms@1.1.2:
resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
engines: {node: '>= 0.4'}
es-set-tostringtag@2.1.0:
resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}
engines: {node: '>= 0.4'}
escape-string-regexp@4.0.0:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
@@ -571,70 +496,19 @@ packages:
flatted@3.4.2:
resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==}
follow-redirects@1.16.3:
resolution: {integrity: sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
form-data@4.0.6:
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
engines: {node: '>= 6'}
fs.realpath@1.0.0:
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
function-bind@1.1.2:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
get-intrinsic@1.3.0:
resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
engines: {node: '>= 0.4'}
get-proto@1.0.1:
resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}
engines: {node: '>= 0.4'}
glob-parent@6.0.2:
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
engines: {node: '>=10.13.0'}
glob@7.2.3:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
globals@17.5.0:
resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==}
engines: {node: '>=18'}
gopd@1.2.0:
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
has-symbols@1.1.0:
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
engines: {node: '>= 0.4'}
has-tostringtag@1.0.2:
resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}
engines: {node: '>= 0.4'}
hasown@2.0.4:
resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}
engines: {node: '>= 0.4'}
https-proxy-agent@5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
ignore@5.3.2:
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
engines: {node: '>= 4'}
@@ -643,13 +517,6 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
inflight@1.0.6:
resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
is-extglob@2.1.1:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
@@ -661,12 +528,6 @@ packages:
isexe@2.0.0:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
js-sha3@0.8.0:
resolution: {integrity: sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==}
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
json-buffer@3.0.1:
resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}
@@ -687,50 +548,16 @@ packages:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
loose-envify@1.4.0:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
match-sorter@6.3.4:
resolution: {integrity: sha512-jfZW7cWS5y/1xswZo8VBOdudUiSd9nifYRWphc9M5D/ee4w4AoXLgBEdRbgVaxbMuagBPeUC5y2Hi8DO6o9aDg==}
math-intrinsics@1.1.0:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
microseconds@0.2.0:
resolution: {integrity: sha512-n7DHHMjR1avBbSpsTBj6fmMGh2AGrifVV4e+WYc3Q9lO+xnSZ3NyhcBND3vzzatt05LFhoKFRxrIyklmLlUtyA==}
mime-db@1.52.0:
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
engines: {node: '>= 0.6'}
mime-types@2.1.35:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
minimatch@10.2.5:
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
minimatch@3.1.5:
resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
nano-time@1.0.0:
resolution: {integrity: sha512-flnngywOoQ0lLQOTRNexn2gGSNuM9bKj9RZAWSzhQ+UJYaAFG9bac4DW9VHjUAzrOaIcajHybCTHe/bkvozQqA==}
natural-compare@1.4.0:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
oblivious-set@1.0.0:
resolution: {integrity: sha512-z+pI07qxo4c2CulUHCDf9lcqDlMSo72N/4rLUpRXf6fu+q8vjt8y0xS+Tlf8NTJDdTXHbdeO1n3MlbctwEoXZw==}
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
optionator@0.9.4:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@@ -780,10 +607,6 @@ packages:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
path-is-absolute@1.0.1:
resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}
engines: {node: '>=0.10.0'}
path-key@3.1.1:
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
@@ -802,38 +625,10 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
proxy-from-env@2.1.0:
resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}
engines: {node: '>=10'}
punycode@2.3.1:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
react-query@3.39.3:
resolution: {integrity: sha512-nLfLz7GiohKTJDuT4us4X3h/8unOh+00MLb2yJoGTPjxKs2bc1iDhkNx2bd5MKklXnOD3NrVZ+J2UXujA5In4g==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
react-dom: '*'
react-native: '*'
peerDependenciesMeta:
react-dom:
optional: true
react-native:
optional: true
react@18.3.1:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
remove-accents@0.5.0:
resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}
rimraf@3.0.2:
resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==}
deprecated: Rimraf versions prior to v4 are no longer supported
hasBin: true
shebang-command@2.0.0:
resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
engines: {node: '>=8'}
@@ -858,9 +653,6 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
unload@2.2.0:
resolution: {integrity: sha512-B60uB5TNBLtN6/LsgAf3udH9saB5p7gqJwcFfbOEZ8BcBHnGwCf6G/TGiEqkRAxX7zAFIUtzdrXQSdL3Q/wqNA==}
uri-js@4.4.1:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
@@ -873,17 +665,12 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
wrappy@1.0.2:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
yocto-queue@0.1.0:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
snapshots:
'@babel/runtime@7.29.7': {}
'@eslint-community/eslint-utils@4.9.1(eslint@10.2.1)':
dependencies:
eslint: 10.2.1
@@ -1066,12 +853,6 @@ snapshots:
dependencies:
playwright: 1.57.0
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react@18.3.1))(react@18.3.1)':
dependencies:
axios: 1.21.1
react: 18.3.1
react-query: 3.39.3(react@18.3.1)
'@types/esrecurse@4.3.1': {}
'@types/estree@1.0.8': {}
@@ -1088,12 +869,6 @@ snapshots:
acorn@8.16.0: {}
agent-base@6.0.2:
dependencies:
debug: 4.4.3
transitivePeerDependencies:
- supports-color
ajv@6.15.0:
dependencies:
fast-deep-equal: 3.1.3
@@ -1101,55 +876,12 @@ snapshots:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
asynckit@0.4.0: {}
axios@1.21.1:
dependencies:
follow-redirects: 1.16.3
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
transitivePeerDependencies:
- debug
- supports-color
balanced-match@1.0.2: {}
balanced-match@4.0.4: {}
big-integer@1.6.52: {}
brace-expansion@1.1.22:
dependencies:
balanced-match: 1.0.2
concat-map: 0.0.1
brace-expansion@5.0.12:
dependencies:
balanced-match: 4.0.4
broadcast-channel@3.7.0:
dependencies:
'@babel/runtime': 7.29.7
detect-node: 2.1.0
js-sha3: 0.8.0
microseconds: 0.2.0
nano-time: 1.0.0
oblivious-set: 1.0.0
rimraf: 3.0.2
unload: 2.2.0
call-bind-apply-helpers@1.0.2:
dependencies:
es-errors: 1.3.0
function-bind: 1.1.2
combined-stream@1.0.8:
dependencies:
delayed-stream: 1.0.0
concat-map@0.0.1: {}
cross-spawn@7.0.6:
dependencies:
path-key: 3.1.1
@@ -1162,33 +894,8 @@ snapshots:
deep-is@0.1.4: {}
delayed-stream@1.0.0: {}
detect-node@2.1.0: {}
dotenv@16.6.1: {}
dunder-proto@1.0.1:
dependencies:
call-bind-apply-helpers: 1.0.2
es-errors: 1.3.0
gopd: 1.2.0
es-define-property@1.0.1: {}
es-errors@1.3.0: {}
es-object-atoms@1.1.2:
dependencies:
es-errors: 1.3.0
es-set-tostringtag@2.1.0:
dependencies:
es-errors: 1.3.0
get-intrinsic: 1.3.0
has-tostringtag: 1.0.2
hasown: 2.0.4
escape-string-regexp@4.0.0: {}
eslint-plugin-playwright@2.10.2(eslint@10.2.1):
@@ -1282,86 +989,19 @@ snapshots:
flatted@3.4.2: {}
follow-redirects@1.16.3: {}
form-data@4.0.6:
dependencies:
asynckit: 0.4.0
combined-stream: 1.0.8
es-set-tostringtag: 2.1.0
hasown: 2.0.4
mime-types: 2.1.35
fs.realpath@1.0.0: {}
fsevents@2.3.2:
optional: true
function-bind@1.1.2: {}
get-intrinsic@1.3.0:
dependencies:
call-bind-apply-helpers: 1.0.2
es-define-property: 1.0.1
es-errors: 1.3.0
es-object-atoms: 1.1.2
function-bind: 1.1.2
get-proto: 1.0.1
gopd: 1.2.0
has-symbols: 1.1.0
hasown: 2.0.4
math-intrinsics: 1.1.0
get-proto@1.0.1:
dependencies:
dunder-proto: 1.0.1
es-object-atoms: 1.1.2
glob-parent@6.0.2:
dependencies:
is-glob: 4.0.3
glob@7.2.3:
dependencies:
fs.realpath: 1.0.0
inflight: 1.0.6
inherits: 2.0.4
minimatch: 3.1.5
once: 1.4.0
path-is-absolute: 1.0.1
globals@17.5.0: {}
gopd@1.2.0: {}
has-symbols@1.1.0: {}
has-tostringtag@1.0.2:
dependencies:
has-symbols: 1.1.0
hasown@2.0.4:
dependencies:
function-bind: 1.1.2
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.4.3
transitivePeerDependencies:
- supports-color
ignore@5.3.2: {}
imurmurhash@0.1.4: {}
inflight@1.0.6:
dependencies:
once: 1.4.0
wrappy: 1.0.2
inherits@2.0.4: {}
is-extglob@2.1.1: {}
is-glob@4.0.3:
@@ -1370,10 +1010,6 @@ snapshots:
isexe@2.0.0: {}
js-sha3@0.8.0: {}
js-tokens@4.0.0: {}
json-buffer@3.0.1: {}
json-schema-traverse@0.4.1: {}
@@ -1393,47 +1029,14 @@ snapshots:
dependencies:
p-locate: 5.0.0
loose-envify@1.4.0:
dependencies:
js-tokens: 4.0.0
match-sorter@6.3.4:
dependencies:
'@babel/runtime': 7.29.7
remove-accents: 0.5.0
math-intrinsics@1.1.0: {}
microseconds@0.2.0: {}
mime-db@1.52.0: {}
mime-types@2.1.35:
dependencies:
mime-db: 1.52.0
minimatch@10.2.5:
dependencies:
brace-expansion: 5.0.12
minimatch@3.1.5:
dependencies:
brace-expansion: 1.1.22
ms@2.1.3: {}
nano-time@1.0.0:
dependencies:
big-integer: 1.6.52
natural-compare@1.4.0: {}
oblivious-set@1.0.0: {}
once@1.4.0:
dependencies:
wrappy: 1.0.2
optionator@0.9.4:
dependencies:
deep-is: 0.1.4
@@ -1509,8 +1112,6 @@ snapshots:
path-exists@4.0.0: {}
path-is-absolute@1.0.1: {}
path-key@3.1.1: {}
playwright-core@1.57.0: {}
@@ -1523,27 +1124,8 @@ snapshots:
prelude-ls@1.2.1: {}
proxy-from-env@2.1.0: {}
punycode@2.3.1: {}
react-query@3.39.3(react@18.3.1):
dependencies:
'@babel/runtime': 7.29.7
broadcast-channel: 3.7.0
match-sorter: 6.3.4
react: 18.3.1
react@18.3.1:
dependencies:
loose-envify: 1.4.0
remove-accents@0.5.0: {}
rimraf@3.0.2:
dependencies:
glob: 7.2.3
shebang-command@2.0.0:
dependencies:
shebang-regex: 3.0.0
@@ -1560,11 +1142,6 @@ snapshots:
undici-types@6.21.0: {}
unload@2.2.0:
dependencies:
'@babel/runtime': 7.29.7
detect-node: 2.1.0
uri-js@4.4.1:
dependencies:
punycode: 2.3.1
@@ -1575,6 +1152,4 @@ snapshots:
word-wrap@1.2.5: {}
wrappy@1.0.2: {}
yocto-queue@0.1.0: {}

View File

@@ -1,108 +0,0 @@
import { expect, test } from '../../drivers/noz';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const QUESTION = 'Why is checkout slow?';
const REPLY = 'Checkout waits on the payment quota.';
const FOLLOW_UP = 'Since when?';
const FOLLOW_UP_REPLY = 'Since the 14:05 deploy.';
test.describe('Noz — chat', () => {
test('TC-01 with an assistant URL the side nav opens a new chat', async ({
noz,
}) => {
await noz.enable();
await noz.gotoHome();
await noz.navItem().click();
await expect.poll(() => noz.conversationId()).toMatch(UUID);
await expect(noz.input()).toBeVisible();
});
test('TC-02 a sent message reaches the assistant and its reply renders', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await expect(noz.message(QUESTION)).toBeVisible();
const [sent] = assistant.sentMessages();
expect(sent.body.content).toBe(QUESTION);
await expect.poll(() => noz.conversationId()).toBe(sent.threadId);
});
test('TC-03 a reload reopens the thread from the assistant', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await noz.reload();
await expect(noz.message(QUESTION)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
});
test('TC-04 a follow-up stays in the same thread', async ({ noz }) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
assistant.replyWith(FOLLOW_UP_REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await noz.send(FOLLOW_UP);
await expect(noz.message(FOLLOW_UP_REPLY)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
const [first, second] = assistant.sentMessages();
expect(second.body.content).toBe(FOLLOW_UP);
expect(second.threadId).toBe(first.threadId);
expect(noz.conversationId()).toBe(first.threadId);
});
test('TC-05 a new chat starts empty and the history list reopens the last one', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
const [{ threadId }] = assistant.sentMessages();
await noz.newChatButton().click();
await expect.poll(() => noz.conversationId()).not.toBe(threadId);
await expect(noz.message(QUESTION)).toHaveCount(0);
await noz.historyItem(threadId).click();
await expect.poll(() => noz.conversationId()).toBe(threadId);
await expect(noz.message(QUESTION)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
});
test('TC-06 asking from the Logs Explorer sends that page as context', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoLogsExplorer();
await noz.askNozButton().click();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
const [sent] = assistant.sentMessages();
expect(sent.body.contexts).toContainEqual(
expect.objectContaining({ source: 'auto', type: 'logs_explorer' }),
);
});
});

View File

@@ -16,9 +16,7 @@
"types": ["node", "@playwright/test"],
"paths": {
"@tests/*": ["./tests/*"],
"@specs/*": ["./specs/*"],
// `drivers/noz/schemas.ts` reaches into `frontend/`, which CI never installs.
"@signozhq/noz-client": ["./node_modules/@signozhq/noz-client"]
"@specs/*": ["./specs/*"]
}
},
"include": ["tests/**/*.ts", "drivers/**/*.ts", "bootstrap/**/*.ts", "playwright.config.ts"],

View File

@@ -442,3 +442,55 @@ 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"