Compare commits

...

4 Commits

Author SHA1 Message Date
Tushar Vats
3556aaa366 fix: removed scores 2026-06-25 12:27:15 +05:30
Tushar Vats
1b53ec94c4 fix: reduce comments 2026-06-23 16:31:42 +05:30
Tushar Vats
a0125492b8 fix: remove code duplication 2026-06-23 00:39:12 +05:30
Tushar Vats
35bde78bbe fix: draft 2026-06-22 17:16:01 +05:30
22 changed files with 1520 additions and 5 deletions

View File

@@ -5597,6 +5597,33 @@ components:
nullable: true
type: array
type: object
Querybuildertypesv5EstimateEntry:
properties:
database:
nullable: true
type: string
marks:
format: int64
nullable: true
type: integer
parts:
format: int64
nullable: true
type: integer
rows:
format: int64
nullable: true
type: integer
table:
nullable: true
type: string
required:
- database
- table
- parts
- rows
- marks
type: object
Querybuildertypesv5ExecStats:
description: Execution statistics for the query, including rows scanned, bytes
scanned, and duration.
@@ -5664,6 +5691,32 @@ components:
- anomaly
- fillzero
type: string
Querybuildertypesv5Granules:
nullable: true
properties:
initial:
format: int64
nullable: true
type: integer
reads:
items:
$ref: '#/components/schemas/Querybuildertypesv5MergeTreeRead'
nullable: true
type: array
selected:
format: int64
nullable: true
type: integer
skipped:
format: int64
nullable: true
type: integer
required:
- initial
- selected
- skipped
- reads
type: object
Querybuildertypesv5GroupByKey:
properties:
description:
@@ -5686,6 +5739,48 @@ components:
expression:
type: string
type: object
Querybuildertypesv5IndexStep:
properties:
condition:
nullable: true
type: string
initialGranules:
format: int64
nullable: true
type: integer
initialParts:
format: int64
nullable: true
type: integer
keys:
items:
type: string
nullable: true
type: array
name:
nullable: true
type: string
selectedGranules:
format: int64
nullable: true
type: integer
selectedParts:
format: int64
nullable: true
type: integer
type:
nullable: true
type: string
required:
- type
- name
- keys
- condition
- initialParts
- selectedParts
- initialGranules
- selectedGranules
type: object
Querybuildertypesv5Label:
properties:
key:
@@ -5709,6 +5804,20 @@ components:
expression:
type: string
type: object
Querybuildertypesv5MergeTreeRead:
properties:
steps:
items:
$ref: '#/components/schemas/Querybuildertypesv5IndexStep'
nullable: true
type: array
table:
nullable: true
type: string
required:
- table
- steps
type: object
Querybuildertypesv5MetricAggregation:
properties:
comparisonSpaceAggregationParam:
@@ -5753,6 +5862,28 @@ components:
- asc
- desc
type: string
Querybuildertypesv5PreviewStatement:
properties:
db.statement.args:
items: {}
nullable: true
type: array
db.statement.query:
nullable: true
type: string
estimate:
items:
$ref: '#/components/schemas/Querybuildertypesv5EstimateEntry'
nullable: true
type: array
granules:
$ref: '#/components/schemas/Querybuildertypesv5Granules'
required:
- db.statement.query
- db.statement.args
- estimate
- granules
type: object
Querybuildertypesv5PromQuery:
properties:
disabled:
@@ -6075,6 +6206,43 @@ components:
type:
$ref: '#/components/schemas/Querybuildertypesv5QueryType'
type: object
Querybuildertypesv5QueryPreview:
properties:
error: {}
statements:
items:
$ref: '#/components/schemas/Querybuildertypesv5PreviewStatement'
nullable: true
type: array
valid:
nullable: true
type: boolean
warnings:
items:
type: string
nullable: true
type: array
required:
- valid
- error
- warnings
- statements
type: object
Querybuildertypesv5QueryRangePreviewResponse:
description: Response from the v5 query range preview (dry-run) endpoint. For
each query in the composite query, returns the underlying ClickHouse statement(s)
it renders to without executing them (one per PromQL metric selector; exactly
one for builder/ClickHouse/trace-operator queries), with the optional EXPLAIN
ESTIMATE and granule analysis attached per statement when requested.
properties:
compositeQuery:
additionalProperties:
$ref: '#/components/schemas/Querybuildertypesv5QueryPreview'
nullable: true
type: object
required:
- compositeQuery
type: object
Querybuildertypesv5QueryRangeRequest:
description: Request body for the v5 query range endpoint. Supports builder
queries (traces, logs, metrics), formulas, joins, trace operators, PromQL,
@@ -22141,6 +22309,75 @@ paths:
summary: Query range
tags:
- querier
/api/v5/query_range/preview:
post:
deprecated: false
description: 'Validate a composite query without executing it. Accepts the same
payload as the query range endpoint. By default (verbose=true) returns, for
each query, the rendered underlying ClickHouse statement(s) with each statement''s
EXPLAIN ESTIMATE (per-table parts/rows/marks) and granule index analysis (candidate/surviving
granules and the per-index pruning funnel). Pass ?verbose=false for the lightweight
per-query verdict (valid/error/warnings) with no rendered SQL and no ClickHouse
round trips. Intended for agentic/dry-run consumption: per-query errors are
reported in the response rather than failing the whole request.'
operationId: QueryRangePreviewV5
parameters:
- in: query
name: verbose
schema:
type: string
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Querybuildertypesv5QueryRangeRequest'
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/Querybuildertypesv5QueryRangePreviewResponse'
status:
type: string
required:
- status
- data
type: object
description: OK
"400":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Bad Request
"401":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Unauthorized
"403":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
security:
- api_key:
- VIEWER
- tokenizer:
- VIEWER
summary: Query range preview
tags:
- querier
/api/v5/substitute_vars:
post:
deprecated: false

View File

@@ -101,6 +101,10 @@ func (h *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {
h.community.QueryRange(rw, req)
}
func (h *handler) QueryRangePreview(rw http.ResponseWriter, req *http.Request) {
h.community.QueryRangePreview(rw, req)
}
func (h *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request) {
h.community.QueryRawStream(rw, req)
}

View File

@@ -12,6 +12,8 @@ import type {
} from 'react-query';
import type {
QueryRangePreviewV5200,
QueryRangePreviewV5Params,
QueryRangeV5200,
Querybuildertypesv5QueryRangeRequestDTO,
RenderErrorResponseDTO,
@@ -104,6 +106,107 @@ export const useQueryRangeV5 = <
> => {
return useMutation(getQueryRangeV5MutationOptions(options));
};
/**
* Validate a composite query without executing it. Accepts the same payload as the query range endpoint. By default (verbose=true) returns, for each query, the rendered underlying ClickHouse statement(s) with each statement's EXPLAIN ESTIMATE (per-table parts/rows/marks) and granule index analysis (candidate/surviving granules and the per-index pruning funnel). Pass ?verbose=false for the lightweight per-query verdict (valid/error/warnings) with no rendered SQL and no ClickHouse round trips. Intended for agentic/dry-run consumption: per-query errors are reported in the response rather than failing the whole request.
* @summary Query range preview
*/
export const queryRangePreviewV5 = (
querybuildertypesv5QueryRangeRequestDTO?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
params?: QueryRangePreviewV5Params,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<QueryRangePreviewV5200>({
url: `/api/v5/query_range/preview`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: querybuildertypesv5QueryRangeRequestDTO,
params,
signal,
});
};
export const getQueryRangePreviewV5MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangePreviewV5>>,
TError,
{
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: QueryRangePreviewV5Params;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof queryRangePreviewV5>>,
TError,
{
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: QueryRangePreviewV5Params;
},
TContext
> => {
const mutationKey = ['queryRangePreviewV5'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof queryRangePreviewV5>>,
{
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: QueryRangePreviewV5Params;
}
> = (props) => {
const { data, params } = props ?? {};
return queryRangePreviewV5(data, params);
};
return { mutationFn, ...mutationOptions };
};
export type QueryRangePreviewV5MutationResult = NonNullable<
Awaited<ReturnType<typeof queryRangePreviewV5>>
>;
export type QueryRangePreviewV5MutationBody =
| BodyType<Querybuildertypesv5QueryRangeRequestDTO>
| undefined;
export type QueryRangePreviewV5MutationError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary Query range preview
*/
export const useQueryRangePreviewV5 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangePreviewV5>>,
TError,
{
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: QueryRangePreviewV5Params;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof queryRangePreviewV5>>,
TError,
{
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: QueryRangePreviewV5Params;
},
TContext
> => {
return useMutation(getQueryRangePreviewV5MutationOptions(options));
};
/**
* Replace variables in a query
* @summary Replace variables

View File

@@ -7130,6 +7130,32 @@ export interface Querybuildertypesv5ColumnDescriptorDTO {
unit?: string;
}
export interface Querybuildertypesv5EstimateEntryDTO {
/**
* @type string,null
*/
database: string | null;
/**
* @type integer,null
* @format int64
*/
marks: number | null;
/**
* @type integer,null
* @format int64
*/
parts: number | null;
/**
* @type integer,null
* @format int64
*/
rows: number | null;
/**
* @type string,null
*/
table: string | null;
}
export type Querybuildertypesv5ExecStatsDTOStepIntervals = {
[key: string]: number;
};
@@ -7170,6 +7196,100 @@ export interface Querybuildertypesv5FormatOptionsDTO {
formatTableResultForUI?: boolean;
}
export interface Querybuildertypesv5IndexStepDTO {
/**
* @type string,null
*/
condition: string | null;
/**
* @type integer,null
* @format int64
*/
initialGranules: number | null;
/**
* @type integer,null
* @format int64
*/
initialParts: number | null;
/**
* @type array,null
*/
keys: string[] | null;
/**
* @type string,null
*/
name: string | null;
/**
* @type integer,null
* @format int64
*/
selectedGranules: number | null;
/**
* @type integer,null
* @format int64
*/
selectedParts: number | null;
/**
* @type string,null
*/
type: string | null;
}
export interface Querybuildertypesv5MergeTreeReadDTO {
/**
* @type array,null
*/
steps: Querybuildertypesv5IndexStepDTO[] | null;
/**
* @type string,null
*/
table: string | null;
}
export type Querybuildertypesv5GranulesDTOAnyOf = {
/**
* @type integer,null
* @format int64
*/
initial: number | null;
/**
* @type array,null
*/
reads: Querybuildertypesv5MergeTreeReadDTO[] | null;
/**
* @type integer,null
* @format int64
*/
selected: number | null;
/**
* @type integer,null
* @format int64
*/
skipped: number | null;
};
/**
* @nullable
*/
export type Querybuildertypesv5GranulesDTO =
Querybuildertypesv5GranulesDTOAnyOf | null;
export interface Querybuildertypesv5PreviewStatementDTO {
/**
* @type array,null
*/
'db.statement.args': unknown[] | null;
/**
* @type string,null
*/
'db.statement.query': string | null;
/**
* @type array,null
*/
estimate: Querybuildertypesv5EstimateEntryDTO[] | null;
granules: Querybuildertypesv5GranulesDTO | null;
}
export interface Querybuildertypesv5TimeSeriesDataDTO {
/**
* @type array,null
@@ -7251,6 +7371,41 @@ export type Querybuildertypesv5QueryDataDTO =
results?: unknown[] | null;
});
export interface Querybuildertypesv5QueryPreviewDTO {
error: unknown;
/**
* @type array,null
*/
statements: Querybuildertypesv5PreviewStatementDTO[] | null;
/**
* @type boolean,null
*/
valid: boolean | null;
/**
* @type array,null
*/
warnings: string[] | null;
}
export type Querybuildertypesv5QueryRangePreviewResponseDTOCompositeQueryAnyOf =
{ [key: string]: Querybuildertypesv5QueryPreviewDTO };
/**
* @nullable
*/
export type Querybuildertypesv5QueryRangePreviewResponseDTOCompositeQuery =
Querybuildertypesv5QueryRangePreviewResponseDTOCompositeQueryAnyOf | null;
/**
* Response from the v5 query range preview (dry-run) endpoint. For each query in the composite query, returns the underlying ClickHouse statement(s) it renders to without executing them (one per PromQL metric selector; exactly one for builder/ClickHouse/trace-operator queries), with the optional EXPLAIN ESTIMATE and granule analysis attached per statement when requested.
*/
export interface Querybuildertypesv5QueryRangePreviewResponseDTO {
/**
* @type object,null
*/
compositeQuery: Querybuildertypesv5QueryRangePreviewResponseDTOCompositeQuery;
}
export enum Querybuildertypesv5VariableTypeDTO {
query = 'query',
dynamic = 'dynamic',
@@ -10950,6 +11105,22 @@ export type QueryRangeV5200 = {
status: string;
};
export type QueryRangePreviewV5Params = {
/**
* @type string
* @description undefined
*/
verbose?: string;
};
export type QueryRangePreviewV5200 = {
data: Querybuildertypesv5QueryRangePreviewResponseDTO;
/**
* @type string
*/
status: string;
};
export type ReplaceVariables200 = {
data: Querybuildertypesv5QueryRangeRequestDTO;
/**

2
go.mod
View File

@@ -180,7 +180,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/ClickHouse/ch-go v0.71.0 // indirect
github.com/ClickHouse/ch-go v0.71.0
github.com/Masterminds/squirrel v1.5.4 // indirect
github.com/Yiling-J/theine-go v0.6.2 // indirect
github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b

View File

@@ -451,6 +451,23 @@ func (provider *provider) addQuerierRoutes(router *mux.Router) error {
return err
}
if err := router.Handle("/api/v5/query_range/preview", handler.New(provider.authzMiddleware.ViewAccess(provider.querierHandler.QueryRangePreview), handler.OpenAPIDef{
ID: "QueryRangePreviewV5",
Tags: []string{"querier"},
Summary: "Query range preview",
Description: "Validate a composite query without executing it. Accepts the same payload as the query range endpoint. By default (verbose=true) returns, for each query, the rendered underlying ClickHouse statement(s) with each statement's EXPLAIN ESTIMATE (per-table parts/rows/marks) and granule index analysis (candidate/surviving granules and the per-index pruning funnel). Pass ?verbose=false for the lightweight per-query verdict (valid/error/warnings) with no rendered SQL and no ClickHouse round trips. Intended for agentic/dry-run consumption: per-query errors are reported in the response rather than failing the whole request.",
Request: new(qbtypes.QueryRangeRequest),
RequestQuery: new(qbtypes.QueryRangePreviewParams),
RequestContentType: "application/json",
Response: new(qbtypes.QueryRangePreviewResponse),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest},
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
})).Methods(http.MethodPost).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v5/substitute_vars", handler.New(provider.authzMiddleware.ViewAccess(provider.querierHandler.ReplaceVariables), handler.OpenAPIDef{
ID: "ReplaceVariables",
Tags: []string{"querier"},

View File

@@ -0,0 +1,88 @@
package clickhouseprometheus
import (
"context"
"sync"
"github.com/SigNoz/signoz/pkg/prometheus"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/storage"
)
// statementRecorder collects the statements a PromQL evaluation would run. Safe
// for concurrent use: the engine may Select multiple selectors concurrently.
type statementRecorder struct {
mu sync.Mutex
statements []prometheus.CapturedStatement
}
func (r *statementRecorder) record(query string, args []any) {
r.mu.Lock()
defer r.mu.Unlock()
r.statements = append(r.statements, prometheus.CapturedStatement{Query: query, Args: args})
}
func (r *statementRecorder) Statements() []prometheus.CapturedStatement {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]prometheus.CapturedStatement, len(r.statements))
copy(out, r.statements)
return out
}
// captureClient is a remote.ReadClient that builds the same SQL as the real
// client but records it and returns an empty result instead of executing.
type captureClient struct {
*client
recorder *statementRecorder
}
func (c *captureClient) Read(ctx context.Context, query *prompb.Query, _ bool) (storage.SeriesSet, error) {
// Raw-SQL passthrough ({job="rawsql", query="..."}): record the raw query.
if len(query.Matchers) == 2 {
var hasJob bool
var queryString string
for _, m := range query.Matchers {
if m.Type == prompb.LabelMatcher_EQ && m.Name == "job" && m.Value == "rawsql" {
hasJob = true
}
if m.Type == prompb.LabelMatcher_EQ && m.Name == "query" {
queryString = m.Value
}
}
if hasJob && queryString != "" {
c.recorder.record(queryString, nil)
return storage.EmptySeriesSet(), nil
}
}
var metricName string
for _, matcher := range query.Matchers {
if matcher.Name == "__name__" {
metricName = matcher.Value
}
}
// Build the same queries as the executing path, but only record them.
subQuery, args, err := c.queryToClickhouseQuery(ctx, query, metricName, true)
if err != nil {
return nil, err
}
samplesQuery, samplesArgs := buildSamplesQuery(int64(query.StartTimestampMs), int64(query.EndTimestampMs), metricName, subQuery, args)
c.recorder.record(samplesQuery, samplesArgs)
return storage.EmptySeriesSet(), nil
}
// captureQueryable adapts the capturing read client to storage.Queryable.
type captureQueryable struct {
inner storage.SampleAndChunkQueryable
}
func (c captureQueryable) Querier(mint, maxt int64) (storage.Querier, error) {
querier, err := c.inner.Querier(mint, maxt)
if err != nil {
return nil, err
}
return storage.NewMergeQuerier(nil, []storage.Querier{querier}, storage.ChainedSeriesMerge), nil
}

View File

@@ -204,8 +204,9 @@ func (client *client) getFingerprintsFromClickhouseQuery(ctx context.Context, qu
return fingerprints, nil
}
func (client *client) querySamples(ctx context.Context, start int64, end int64, fingerprints map[uint64][]prompb.Label, metricName string, subQuery string, args []any) ([]*prompb.TimeSeries, error) {
ctx = client.withClickhousePrometheusContext(ctx, "querySamples")
// buildSamplesQuery renders the self-contained samples SQL (and args) that
// fetches data points for the series selected by subQuery.
func buildSamplesQuery(start int64, end int64, metricName string, subQuery string, args []any) (string, []any) {
argCount := len(args)
query := fmt.Sprintf(`
@@ -217,6 +218,13 @@ func (client *client) querySamples(ctx context.Context, start int64, end int64,
allArgs := append([]any{metricName}, args...)
allArgs = append(allArgs, start, end)
return query, allArgs
}
func (client *client) querySamples(ctx context.Context, start int64, end int64, fingerprints map[uint64][]prompb.Label, metricName string, subQuery string, args []any) ([]*prompb.TimeSeries, error) {
ctx = client.withClickhousePrometheusContext(ctx, "querySamples")
query, allArgs := buildSamplesQuery(start, end, metricName, subQuery, args)
rows, err := client.telemetryStore.ClickhouseDB().Query(ctx, query, allArgs...)
if err != nil {

View File

@@ -5,8 +5,8 @@ import (
"sort"
"testing"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
cmock "github.com/SigNoz/clickhouse-go-mock"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
"github.com/stretchr/testify/require"
"github.com/DATA-DOG/go-sqlmock"

View File

@@ -64,3 +64,15 @@ func (provider *provider) Querier(mint, maxt int64) (storage.Querier, error) {
return storage.NewMergeQuerier(nil, []storage.Querier{querier}, storage.ChainedSeriesMerge), nil
}
// CapturingStorage implements prometheus.StatementCapturer. A fresh recorder is
// created per call so concurrent dry-runs don't share state.
func (provider *provider) CapturingStorage() (storage.Queryable, prometheus.StatementRecorder) {
recorder := &statementRecorder{}
capture := &captureClient{
client: &client{settings: provider.settings, telemetryStore: provider.telemetryStore},
recorder: recorder,
}
queryable := remote.NewSampleAndChunkQueryableClient(capture, labels.EmptyLabels(), []*labels.Matcher{}, false, stCallback)
return captureQueryable{inner: queryable}, recorder
}

View File

@@ -15,3 +15,23 @@ type Prometheus interface {
Storage() storage.Queryable
Parser() Parser
}
// CapturedStatement is one datastore statement a PromQL query would run,
// captured without executing it.
type CapturedStatement struct {
Query string
Args []any
}
// StatementRecorder reads back the statements captured against a capturing
// Storage (see StatementCapturer).
type StatementRecorder interface {
Statements() []CapturedStatement
}
// StatementCapturer is an optional Prometheus-provider capability: it returns a
// Storage that records each Select's statement without executing it, plus a
// recorder to read them back. Discovered via type assertion.
type StatementCapturer interface {
CapturingStorage() (storage.Queryable, StatementRecorder)
}

View File

@@ -73,6 +73,53 @@ func (handler *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {
render.Success(rw, http.StatusOK, queryRangeResponse)
}
// QueryRangePreview is the dry-run counterpart of QueryRange: it validates and
// renders each query without executing it.
func (handler *handler) QueryRangePreview(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.CodeNamespace: "querier",
instrumentationtypes.CodeFunctionName: "QueryRangePreview",
})
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
var queryRangeRequest qbtypes.QueryRangeRequest
if err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {
render.Error(rw, err)
return
}
// Validation is deferred to QueryRangePreview, which validates each query
// individually and reports per-query errors instead of failing fast.
orgID, err := valuer.NewUUID(claims.OrgID)
if err != nil {
render.Error(rw, err)
return
}
previewParams := qbtypes.QueryRangePreviewParams{Verbose: req.URL.Query().Get("verbose")}
previewOpts, err := previewParams.Validate()
if err != nil {
render.Error(rw, err)
return
}
preview, err := handler.querier.QueryRangePreview(ctx, orgID, &queryRangeRequest, previewOpts)
if err != nil {
render.Error(rw, err)
return
}
render.Success(rw, http.StatusOK, preview)
}
func (handler *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()

View File

@@ -34,6 +34,7 @@ type builderQuery[T any] struct {
}
var _ qbtypes.Query = (*builderQuery[any])(nil)
var _ qbtypes.StatementProvider = (*builderQuery[any])(nil)
func newBuilderQuery[T any](
logger *slog.Logger,
@@ -194,6 +195,11 @@ func (q *builderQuery[T]) isWindowList() bool {
return true
}
// Statement renders the SQL without executing it, for the preview path.
func (q *builderQuery[T]) Statement(ctx context.Context) (*qbtypes.Statement, error) {
return q.stmtBuilder.Build(ctx, q.fromMS, q.toMS, q.kind, q.spec, q.variables)
}
func (q *builderQuery[T]) Execute(ctx context.Context) (*qbtypes.Result, error) {
// can we do window based pagination?

View File

@@ -32,6 +32,7 @@ type chSQLQuery struct {
}
var _ qbtypes.Query = (*chSQLQuery)(nil)
var _ qbtypes.StatementProvider = (*chSQLQuery)(nil)
func newchSQLQuery(
logger *slog.Logger,
@@ -99,6 +100,15 @@ func (q *chSQLQuery) renderVars(query string, vars map[string]qbtypes.VariableIt
return newQuery.String(), nil
}
// Statement renders the SQL without executing it, for the preview path.
func (q *chSQLQuery) Statement(_ context.Context) (*qbtypes.Statement, error) {
rendered, err := q.renderVars(q.query.Query, q.vars, q.fromMS, q.toMS)
if err != nil {
return nil, err
}
return &qbtypes.Statement{Query: rendered, Args: q.args}, nil
}
func (q *chSQLQuery) Execute(ctx context.Context) (*qbtypes.Result, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.QueryDuration: instrumentationtypes.DurationBucket(q.fromMS, q.toMS),

View File

@@ -14,6 +14,8 @@ type Querier interface {
QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest) (*qbtypes.QueryRangeResponse, error)
QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest, client *qbtypes.RawStream)
statsreporter.StatsCollector
// QueryRangePreview validates and renders the queries without executing them.
QueryRangePreview(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest, opts qbtypes.QueryRangePreviewOptions) (*qbtypes.QueryRangePreviewResponse, error)
}
// BucketCache is the interface for bucket-based caching.
@@ -26,6 +28,8 @@ type BucketCache interface {
type Handler interface {
QueryRange(rw http.ResponseWriter, req *http.Request)
// QueryRangePreview is the dry-run endpoint: validate and render without executing.
QueryRangePreview(rw http.ResponseWriter, req *http.Request)
QueryRawStream(rw http.ResponseWriter, req *http.Request)
ReplaceVariables(rw http.ResponseWriter, req *http.Request)
}

553
pkg/querier/preview.go Normal file
View File

@@ -0,0 +1,553 @@
package querier
import (
"context"
"encoding/json"
"fmt"
"reflect"
"slices"
"strings"
"sync"
chproto "github.com/ClickHouse/ch-go/proto"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/SigNoz/signoz/pkg/errors"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
)
// userFacingClickHouseErrorCodes are the ClickHouse error codes that indicate a
// bad query (map to 400) rather than an infra failure (500).
//
// TODO(#10679): replace with the shared querier.mapClickHouseError once it lands.
var userFacingClickHouseErrorCodes = map[chproto.Error]bool{
chproto.ErrSyntaxError: true,
chproto.ErrUnknownTable: true,
chproto.ErrUnknownDatabase: true,
chproto.ErrUnknownIdentifier: true,
chproto.ErrUnknownFunction: true,
chproto.ErrUnknownAggregateFunction: true,
chproto.ErrUnknownType: true,
chproto.ErrUnknownStorage: true,
chproto.ErrUnknownElementInAst: true,
chproto.ErrUnknownTypeOfQuery: true,
chproto.ErrIllegalTypeOfArgument: true,
chproto.ErrIllegalColumn: true,
chproto.ErrNumberOfArgumentsDoesntMatch: true,
chproto.ErrTooManyArgumentsForFunction: true,
chproto.ErrTooLessArgumentsForFunction: true,
}
// previewTask is one rendered statement queued for granule/estimate analysis.
// stmtIdx is where its results merge back into the query's Statements.
type previewTask struct {
name string
stmtIdx int
query string
args []any
}
type explainPlanNode struct {
NodeType string `json:"Node Type"`
Description string `json:"Description"`
Indexes []explainPlanIndex `json:"Indexes"`
Plans []explainPlanNode `json:"Plans"`
}
type explainPlanIndex struct {
Type string `json:"Type"`
Name string `json:"Name"`
Keys []string `json:"Keys"`
Condition string `json:"Condition"`
InitialParts *int64 `json:"Initial Parts"`
SelectedParts *int64 `json:"Selected Parts"`
InitialGranules *int64 `json:"Initial Granules"`
SelectedGranules *int64 `json:"Selected Granules"`
}
// QueryRangePreview validates and renders each query without executing it.
// When opts.Verbose, it also attaches each statement's EXPLAIN ESTIMATE and
// granule analysis.
func (q *querier) QueryRangePreview(
ctx context.Context,
_ valuer.UUID,
req *qbtypes.QueryRangeRequest,
opts qbtypes.QueryRangePreviewOptions,
) (*qbtypes.QueryRangePreviewResponse, error) {
validationOpts, err := req.ValidateRequestScope()
if err != nil {
return nil, err
}
dependencyQueries, err := q.constructTraceOperatorDependencyMap(req.CompositeQuery.Queries)
if err != nil {
return nil, err
}
results := make(map[string]qbtypes.QueryPreview, len(req.CompositeQuery.Queries))
prepared := make(map[string]qbtypes.QueryPreview, len(req.CompositeQuery.Queries))
missingMetricQuerySet := make(map[string]bool)
for idx := range req.CompositeQuery.Queries {
name := req.CompositeQuery.Queries[idx].GetQueryName()
ps := qbtypes.QueryPreview{}
if vErr := req.CompositeQuery.Queries[idx].Validate(validationOpts...); vErr != nil {
ps.Error = vErr
prepared[name] = ps
continue
}
env := []qbtypes.QueryEnvelope{req.CompositeQuery.Queries[idx]}
ps.Warnings = q.adjustStepInterval(env, req.Start, req.End)
missingMetricQueries, metricWarnings, mErr := q.resolveMetricMetadata(ctx, env, req.Start, req.End)
if mErr != nil {
// Report this query's error but keep previewing the rest.
ps.Error = mErr
} else {
ps.Warnings = append(ps.Warnings, metricWarnings...)
if len(missingMetricQueries) > 0 {
missingMetricQuerySet[name] = true
if len(metricWarnings) == 0 {
if metricNames := missingMetricNames(env[0]); len(metricNames) > 0 {
ps.Warnings = append(ps.Warnings, fmt.Sprintf(
"query %q references metric(s) %s with no data available; it will return an empty result",
name, strings.Join(metricNames, ", ")))
}
}
}
}
req.CompositeQuery.Queries[idx] = env[0]
prepared[name] = ps
}
skip := make(map[string]bool, len(prepared))
for name, ps := range prepared {
if ps.Error != nil || missingMetricQuerySet[name] {
skip[name] = true
}
}
providers, buildErrs := q.buildPreviewProviders(req, dependencyQueries, missingMetricQuerySet, skip)
// Render each executing query's statement and collect the ClickHouse-bound
// analysis work to run concurrently.
var previewTasks []previewTask
for _, query := range req.CompositeQuery.Queries {
name := query.GetQueryName()
ps := prepared[name]
// Surface an earlier error without rendering.
if ps.Error != nil {
results[name] = ps
continue
}
// Fully-missing metric: QueryRange renders no SQL, so neither do we.
if missingMetricQuerySet[name] {
results[name] = ps
continue
}
// Attribute a build error to this query instead of aborting the preview.
if bErr := buildErrs[name]; bErr != nil {
ps.Error = bErr
results[name] = ps
continue
}
provider, ok := providers[name]
if !ok {
// Formula/join/sub-query render no standalone statement; report them
// as valid with a note rather than failing them.
if !rendersStandaloneStatement(query.Type) {
ps.Warnings = append(ps.Warnings, fmt.Sprintf(
"query type %q has no standalone statement to preview; it is evaluated from the queries it references", query.Type.StringValue()))
results[name] = ps
continue
}
ps.Error = errors.NewInternalf(errors.CodeInternal, "query produced no provider")
results[name] = ps
continue
}
stmtProvider, ok := provider.(qbtypes.StatementProvider)
if !ok {
ps.Error = errors.NewInternalf(errors.CodeInternal, "query does not support preview")
results[name] = ps
continue
}
stmt, sErr := stmtProvider.Statement(ctx)
if sErr != nil {
ps.Error = sErr
results[name] = ps
continue
}
ps.Warnings = append(ps.Warnings, stmt.Warnings...)
// clickhouse_sql is user-authored, so verify it parses and binds via
// EXPLAIN PLAN. Engine-generated SQL is well-formed by construction.
if query.Type == qbtypes.QueryTypeClickHouseSQL {
if bindErr := q.explainBindCheck(ctx, stmt.Query, stmt.Args); bindErr != nil {
if errors.Ast(bindErr, errors.TypeInvalidInput) {
ps.Error = bindErr
results[name] = ps
continue
}
// Infra failure, not a query problem: warn, don't mark invalid.
ps.Warnings = append(ps.Warnings, "could not validate ClickHouse SQL: "+bindErr.Error())
}
}
if !opts.Verbose {
results[name] = ps
continue
}
if query.Type == qbtypes.QueryTypePromQL {
if pq, ok := provider.(*promqlQuery); ok {
sqlStmts, pErr := pq.PreviewStatements(ctx)
if pErr != nil {
ps.Warnings = append(ps.Warnings, "could not render underlying ClickHouse SQL: "+pErr.Error())
} else {
for _, s := range sqlStmts {
ps.Statements = append(ps.Statements, qbtypes.PreviewStatement{Query: s.Query, Args: s.Args})
}
}
}
} else {
ps.Statements = []qbtypes.PreviewStatement{{Query: stmt.Query, Args: stmt.Args}}
}
results[name] = ps
for j := range ps.Statements {
previewTasks = append(previewTasks, previewTask{name: name, stmtIdx: j, query: ps.Statements[j].Query, args: ps.Statements[j].Args})
}
}
q.runPreviewTasks(ctx, previewTasks, results)
return &qbtypes.QueryRangePreviewResponse{
CompositeQuery: results,
}, nil
}
// missingMetricNames returns the distinct metric names referenced by a metric
// builder query, or nil for a non-metric query.
func missingMetricNames(env qbtypes.QueryEnvelope) []string {
spec, ok := env.Spec.(qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation])
if !ok {
return nil
}
names := make([]string, 0, len(spec.Aggregations))
for _, agg := range spec.Aggregations {
if agg.MetricName != "" && !slices.Contains(names, agg.MetricName) {
names = append(names, agg.MetricName)
}
}
return names
}
func (q *querier) buildPreviewProviders(
req *qbtypes.QueryRangeRequest,
dependencyQueries map[string]bool,
missingMetricQuerySet map[string]bool,
skip map[string]bool,
) (providers map[string]qbtypes.Query, errs map[string]error) {
providers = make(map[string]qbtypes.Query)
errs = make(map[string]error)
event := &qbtypes.QBEvent{} // preview emits no analytics
for _, query := range req.CompositeQuery.Queries {
name := query.GetQueryName()
if skip[name] {
continue
}
sub := *req // shallow copy: only CompositeQuery and RequestType are swapped
// deps is the set buildQueries skips: empty for a standalone query, the
// operator's referenced siblings for a trace operator.
var deps map[string]bool
switch {
case query.GetType() == qbtypes.QueryTypeTraceOperator:
refs, rErr := q.traceOperatorPreviewComposite(req, query)
if rErr != nil {
errs[name] = rErr
continue
}
sub.CompositeQuery = qbtypes.CompositeQuery{Queries: refs}
deps = dependencyQueries
case dependencyQueries[name]:
sub.RequestType = qbtypes.RequestTypeRaw
sub.CompositeQuery = qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{query}}
default:
sub.CompositeQuery = qbtypes.CompositeQuery{Queries: []qbtypes.QueryEnvelope{query}}
}
built, _, bErr := q.buildQueries(&sub, deps, missingMetricQuerySet, event)
if bErr != nil {
errs[name] = bErr
continue
}
if provider, ok := built[name]; ok {
providers[name] = provider
}
}
return providers, errs
}
// rendersStandaloneStatement reports whether a query type renders its own
// statement. Formula/join/sub-query don't — they reference other queries.
func rendersStandaloneStatement(t qbtypes.QueryType) bool {
switch t {
case qbtypes.QueryTypeBuilder,
qbtypes.QueryTypePromQL,
qbtypes.QueryTypeClickHouseSQL,
qbtypes.QueryTypeTraceOperator:
return true
default:
return false
}
}
func (q *querier) traceOperatorPreviewComposite(req *qbtypes.QueryRangeRequest, operator qbtypes.QueryEnvelope) ([]qbtypes.QueryEnvelope, error) {
spec, ok := operator.Spec.(qbtypes.QueryBuilderTraceOperator)
if !ok {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid trace operator query spec %T", operator.Spec)
}
if err := spec.ParseExpression(); err != nil {
return nil, err
}
referenced := make(map[string]bool)
for _, name := range spec.CollectReferencedQueries(spec.ParsedExpression) {
referenced[name] = true
}
queries := make([]qbtypes.QueryEnvelope, 0, len(referenced)+1)
for _, qe := range req.CompositeQuery.Queries {
if referenced[qe.GetQueryName()] {
queries = append(queries, qe)
}
}
return append(queries, operator), nil
}
func (q *querier) runPreviewTasks(ctx context.Context, tasks []previewTask, previews map[string]qbtypes.QueryPreview) {
if len(tasks) == 0 {
return
}
type outcome struct {
granules *qbtypes.Granules
estimate []qbtypes.EstimateEntry
warnings []string
}
outcomes := make([]outcome, len(tasks))
var wg sync.WaitGroup
for i := range tasks {
wg.Add(1)
go func(i int) {
defer wg.Done()
t := tasks[i]
var out outcome
if granules, ok, scErr := q.computeGranuleStats(ctx, t.query, t.args); scErr != nil {
out.warnings = append(out.warnings, "could not compute granule stats: "+scErr.Error())
} else if ok {
out.granules = &granules
}
if estimate, eErr := q.runExplainEstimate(ctx, t.query, t.args); eErr != nil {
out.warnings = append(out.warnings, "could not run EXPLAIN ESTIMATE: "+eErr.Error())
} else {
out.estimate = estimate
}
outcomes[i] = out
}(i)
}
wg.Wait()
for i := range tasks {
ps := previews[tasks[i].name]
if idx := tasks[i].stmtIdx; idx >= 0 && idx < len(ps.Statements) {
if outcomes[i].granules != nil {
ps.Statements[idx].Granules = outcomes[i].granules
}
if len(outcomes[i].estimate) > 0 {
ps.Statements[idx].Estimate = outcomes[i].estimate
}
}
ps.Warnings = append(ps.Warnings, outcomes[i].warnings...)
previews[tasks[i].name] = ps
}
}
func (q *querier) runExplainEstimate(ctx context.Context, stmt string, args []any) ([]qbtypes.EstimateEntry, error) {
rows, err := q.telemetryStore.ClickhouseDB().Query(ctx, "EXPLAIN ESTIMATE "+stmt, args...)
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to run EXPLAIN ESTIMATE")
}
defer rows.Close()
colTypes := rows.ColumnTypes()
var entries []qbtypes.EstimateEntry
for rows.Next() {
dest := make([]any, len(colTypes))
for i, ct := range colTypes {
dest[i] = reflect.New(ct.ScanType()).Interface()
}
if err := rows.Scan(dest...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan EXPLAIN ESTIMATE row")
}
var entry qbtypes.EstimateEntry
for i, ct := range colTypes {
val := reflect.ValueOf(dest[i]).Elem().Interface()
switch strings.ToLower(ct.Name()) {
case "database":
entry.Database = fmt.Sprintf("%v", val)
case "table":
entry.Table = fmt.Sprintf("%v", val)
case "parts":
entry.Parts = toInt64(val)
case "rows":
entry.Rows = toInt64(val)
case "marks":
entry.Marks = toInt64(val)
}
}
entries = append(entries, entry)
}
if err := rows.Err(); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "EXPLAIN ESTIMATE row iteration failed")
}
return entries, nil
}
// toInt64 coerces a driver-scanned numeric value to int64 (0 if non-numeric).
func toInt64(v any) int64 {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return rv.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int64(rv.Uint())
case reflect.Float32, reflect.Float64:
return int64(rv.Float())
default:
return 0
}
}
func (q *querier) explainBindCheck(ctx context.Context, stmt string, args []any) error {
rows, err := q.telemetryStore.ClickhouseDB().Query(ctx, "EXPLAIN PLAN "+stmt, args...)
if err != nil {
var ex *clickhouse.Exception
if errors.As(err, &ex) && userFacingClickHouseErrorCodes[chproto.Error(ex.Code)] {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid ClickHouse SQL: %s", ex.Message)
}
return err
}
rows.Close()
return nil
}
func (q *querier) computeGranuleStats(ctx context.Context, stmt string, args []any) (qbtypes.Granules, bool, error) {
rows, err := q.telemetryStore.ClickhouseDB().Query(ctx, "EXPLAIN json = 1, indexes = 1 "+stmt, args...)
if err != nil {
return qbtypes.Granules{}, false, errors.WrapInternalf(err, errors.CodeInternal, "failed to run EXPLAIN for granule stats")
}
defer rows.Close()
// json=1 emits one JSON document; join rows in case the driver splits it.
var sb strings.Builder
for rows.Next() {
var line string
if err := rows.Scan(&line); err != nil {
return qbtypes.Granules{}, false, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan EXPLAIN json row")
}
sb.WriteString(line)
sb.WriteByte('\n')
}
if err := rows.Err(); err != nil {
return qbtypes.Granules{}, false, errors.WrapInternalf(err, errors.CodeInternal, "EXPLAIN json row iteration failed")
}
var plans []struct {
Plan explainPlanNode `json:"Plan"`
}
if err := json.Unmarshal([]byte(sb.String()), &plans); err != nil {
return qbtypes.Granules{}, false, errors.WrapInternalf(err, errors.CodeInternal, "failed to parse EXPLAIN json")
}
var totalInitial, totalSelected int64
var reads []qbtypes.MergeTreeRead
for i := range plans {
collectMergeTreeReads(&plans[i].Plan, &reads, &totalInitial, &totalSelected)
}
if totalInitial <= 0 {
// No MergeTree index analysis — nothing to report.
return qbtypes.Granules{}, false, nil
}
if totalSelected < 0 {
totalSelected = 0
}
skippedGranules := totalInitial - totalSelected
if skippedGranules < 0 {
skippedGranules = 0
}
return qbtypes.Granules{
Initial: totalInitial,
Selected: totalSelected,
Skipped: skippedGranules,
Reads: reads,
}, true, nil
}
func derefInt64(p *int64) int64 {
if p == nil {
return 0
}
return *p
}
func collectMergeTreeReads(node *explainPlanNode, reads *[]qbtypes.MergeTreeRead, totalInitial, totalSelected *int64) {
if node.NodeType == "ReadFromMergeTree" && len(node.Indexes) > 0 {
steps := make([]qbtypes.IndexStep, 0, len(node.Indexes))
var initial, selected *int64
for i := range node.Indexes {
idx := node.Indexes[i]
if idx.InitialGranules != nil && initial == nil {
initial = idx.InitialGranules
}
if idx.SelectedGranules != nil {
selected = idx.SelectedGranules
}
steps = append(steps, qbtypes.IndexStep{
Type: idx.Type,
Name: idx.Name,
Keys: idx.Keys,
Condition: idx.Condition,
InitialParts: derefInt64(idx.InitialParts),
SelectedParts: derefInt64(idx.SelectedParts),
InitialGranules: derefInt64(idx.InitialGranules),
SelectedGranules: derefInt64(idx.SelectedGranules),
})
}
if initial != nil && selected != nil {
*totalInitial += *initial
*totalSelected += *selected
}
*reads = append(*reads, qbtypes.MergeTreeRead{Table: node.Description, Steps: steps})
}
for i := range node.Plans {
collectMergeTreeReads(&node.Plans[i], reads, totalInitial, totalSelected)
}
}

View File

@@ -101,6 +101,7 @@ type promqlQuery struct {
}
var _ qbv5.Query = (*promqlQuery)(nil)
var _ qbv5.StatementProvider = (*promqlQuery)(nil)
func newPromqlQuery(
logger *slog.Logger,
@@ -220,6 +221,62 @@ func (q *promqlQuery) renderVars(query string, vars map[string]qbv5.VariableItem
return newQuery.String(), nil
}
// Statement renders the PromQL string (no SQL args) without executing it, for
// the preview path.
func (q *promqlQuery) Statement(_ context.Context) (*qbv5.Statement, error) {
rendered, err := q.renderVars(q.query.Query, q.vars, q.tr.From, q.tr.To)
if err != nil {
return nil, err
}
return &qbv5.Statement{Query: rendered}, nil
}
// PreviewStatements returns the ClickHouse statement(s) this PromQL query would
// run, captured by driving the engine with a Storage that records each
// selector's SQL and returns empty results. Returns nil if capture is unsupported.
func (q *promqlQuery) PreviewStatements(ctx context.Context) ([]prometheus.CapturedStatement, error) {
storer, ok := q.promEngine.(prometheus.StatementCapturer)
if !ok {
return nil, nil
}
rendered, err := q.renderVars(q.query.Query, q.vars, q.tr.From, q.tr.To)
if err != nil {
return nil, err
}
start := int64(querybuilder.ToNanoSecs(q.tr.From))
end := int64(querybuilder.ToNanoSecs(q.tr.To))
capStorage, recorder := storer.CapturingStorage()
qry, err := q.promEngine.Engine().NewRangeQuery(
ctx,
capStorage,
nil,
rendered,
time.Unix(0, start),
time.Unix(0, end),
q.query.Step.Duration,
)
if err != nil {
if e := tryEnhancePromQLExecError(err); e != nil {
return nil, e
}
return nil, enhancePromQLError(rendered, err)
}
defer qry.Close()
// Exec drives a Select per selector (recording SQL) but reads no data.
if res := qry.Exec(ctx); res.Err != nil {
if e := tryEnhancePromQLExecError(res.Err); e != nil {
return nil, e
}
return nil, errors.Newf(errors.TypeInternal, errors.CodeInternal, "query execution error: %v", res.Err)
}
return recorder.Statements(), nil
}
func (q *promqlQuery) Execute(ctx context.Context) (*qbv5.Result, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{

View File

@@ -23,6 +23,7 @@ type traceOperatorQuery struct {
}
var _ qbtypes.Query = (*traceOperatorQuery)(nil)
var _ qbtypes.StatementProvider = (*traceOperatorQuery)(nil)
func (q *traceOperatorQuery) Fingerprint() string {
return ""
@@ -32,6 +33,11 @@ func (q *traceOperatorQuery) Window() (uint64, uint64) {
return q.fromMS, q.toMS
}
// Statement renders the SQL without executing it, for the preview path.
func (q *traceOperatorQuery) Statement(ctx context.Context) (*qbtypes.Statement, error) {
return q.stmtBuilder.Build(ctx, q.fromMS, q.toMS, q.kind, q.spec, q.compositeQuery)
}
func (q *traceOperatorQuery) Execute(ctx context.Context) (*qbtypes.Result, error) {
stmt, err := q.stmtBuilder.Build(
ctx,

View File

@@ -145,7 +145,7 @@ func PrepareWhereClause(query string, opts FilterExprVisitorOpts) (PreparedWhere
"Found %d syntax errors while parsing the search expression.",
len(parserErrorListener.SyntaxErrors),
)
additionals := make([]string, len(parserErrorListener.SyntaxErrors))
additionals := make([]string, 0, len(parserErrorListener.SyntaxErrors))
for _, err := range parserErrorListener.SyntaxErrors {
if err.Error() != "" {
additionals = append(additionals, err.Error())

View File

@@ -58,3 +58,8 @@ type TraceOperatorStatementBuilder interface {
// Build builds the trace operator query.
Build(ctx context.Context, start, end uint64, requestType RequestType, query QueryBuilderTraceOperator, compositeQuery *CompositeQuery) (*Statement, error)
}
// StatementProvider renders a query's underlying statement without executing it.
type StatementProvider interface {
Statement(ctx context.Context) (*Statement, error)
}

View File

@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/swaggest/jsonschema-go"
@@ -64,6 +65,103 @@ type QueryRangeResponse struct {
QBEvent *QBEvent `json:"-"`
}
// QueryRangePreviewResponse is the dry-run output: one QueryPreview per query,
// keyed by the request's query names.
type QueryRangePreviewResponse struct {
CompositeQuery map[string]QueryPreview `json:"compositeQuery" required:"true" nullable:"true"`
}
// QueryRangePreviewOptions carries per-call options for the dry-run endpoint.
type QueryRangePreviewOptions struct {
Verbose bool
}
// QueryRangePreviewParams are the query-string parameters of the dry-run endpoint.
type QueryRangePreviewParams struct {
Verbose string `query:"verbose"`
}
// PrepareJSONSchema adds description to the QueryRangePreviewResponse schema.
func (q *QueryRangePreviewResponse) PrepareJSONSchema(schema *jsonschema.Schema) error {
schema.WithDescription("Response from the v5 query range preview (dry-run) endpoint. For each query in the composite query, returns the underlying ClickHouse statement(s) it renders to without executing them (one per PromQL metric selector; exactly one for builder/ClickHouse/trace-operator queries), with the optional EXPLAIN ESTIMATE and granule analysis attached per statement when requested.")
return nil
}
// QueryPreview is the dry-run result for a single query.
type QueryPreview struct {
Valid bool `json:"valid" required:"true" nullable:"true"`
Error error `json:"error" required:"true"`
Warnings []string `json:"warnings" required:"true" nullable:"true"`
Statements []PreviewStatement `json:"statements" required:"true" nullable:"true"`
}
// PreviewStatement is one rendered ClickHouse statement with its args and, when
// requested, its EXPLAIN ESTIMATE and granule breakdown. The query/args JSON
// keys follow the OpenTelemetry db.statement.* convention.
type PreviewStatement struct {
Query string `json:"db.statement.query" required:"true" nullable:"true"`
Args []any `json:"db.statement.args" required:"true" nullable:"true"`
Estimate []EstimateEntry `json:"estimate" required:"true" nullable:"true"`
Granules *Granules `json:"granules" required:"true" nullable:"true"`
}
// EstimateEntry is ClickHouse's EXPLAIN ESTIMATE for one table read: the
// absolute parts, rows, and marks it estimates it will scan.
type EstimateEntry struct {
Database string `json:"database" required:"true" nullable:"true"`
Table string `json:"table" required:"true" nullable:"true"`
Parts int64 `json:"parts" required:"true" nullable:"true"`
Rows int64 `json:"rows" required:"true" nullable:"true"`
Marks int64 `json:"marks" required:"true" nullable:"true"`
}
// Granules is the granule-skip breakdown for one statement, parsed from
// `EXPLAIN json = 1, indexes = 1` and summed across every ReadFromMergeTree node.
type Granules struct {
Initial int64 `json:"initial" required:"true" nullable:"true"`
Selected int64 `json:"selected" required:"true" nullable:"true"`
Skipped int64 `json:"skipped" required:"true" nullable:"true"`
Reads []MergeTreeRead `json:"reads" required:"true" nullable:"true"`
}
// MergeTreeRead is the index-pruning funnel for one ReadFromMergeTree node. The
// Steps run in sequence, so each step's Initial* matches the previous Selected*.
type MergeTreeRead struct {
Table string `json:"table" required:"true" nullable:"true"`
Steps []IndexStep `json:"steps" required:"true" nullable:"true"`
}
// IndexStep is one index applied during a MergeTree read, with the parts and
// granules entering (Initial*) and surviving (Selected*) it. Type is the index
// kind (MinMax, Partition, PrimaryKey, or Skip).
type IndexStep struct {
Type string `json:"type" required:"true" nullable:"true"`
Name string `json:"name" required:"true" nullable:"true"`
Keys []string `json:"keys" required:"true" nullable:"true"`
Condition string `json:"condition" required:"true" nullable:"true"`
InitialParts int64 `json:"initialParts" required:"true" nullable:"true"`
SelectedParts int64 `json:"selectedParts" required:"true" nullable:"true"`
InitialGranules int64 `json:"initialGranules" required:"true" nullable:"true"`
SelectedGranules int64 `json:"selectedGranules" required:"true" nullable:"true"`
}
// MarshalJSON renders Error in its structured form (code/message/suggestions)
// rather than the empty object a bare error produces.
func (p QueryPreview) MarshalJSON() ([]byte, error) {
type alias QueryPreview
out := struct {
alias
Error *errors.JSON `json:"error"`
}{alias: alias(p)}
out.alias.Error = nil
// Derive the verdict so the two can't desync.
out.Valid = p.Error == nil
if p.Error != nil {
out.Error = errors.AsJSON(p.Error)
}
return json.Marshal(out)
}
var _ jsonschema.Preparer = &QueryRangeResponse{}
// PrepareJSONSchema adds description to the QueryRangeResponse schema.

View File

@@ -575,6 +575,75 @@ func (r *QueryRangeRequest) Validate(opts ...ValidationOption) error {
return nil
}
// ValidateRequestScope validates request-level invariants without validating
// individual query specs, returning the request type's ValidationOptions. The
// dry-run path uses this so per-query errors can be attributed individually
// (via QueryEnvelope.Validate) instead of failing fast the way Validate does.
func (r *QueryRangeRequest) ValidateRequestScope() ([]ValidationOption, error) {
if r.RequestType != RequestTypeRawStream && r.Start >= r.End {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "start time must be before end time")
}
var opts []ValidationOption
switch r.RequestType {
case RequestTypeRaw, RequestTypeRawStream, RequestTypeTrace, RequestTypeTimeSeries, RequestTypeScalar:
opts = GetValidationOptions(r.RequestType)
default:
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid request type: %s", r.RequestType).
WithAdditional("Valid request types are: raw, timeseries, scalar")
}
if r.RequestType == RequestTypeRaw || r.RequestType == RequestTypeRawStream || r.RequestType == RequestTypeTrace {
for _, envelope := range r.CompositeQuery.Queries {
if envelope.GetSignal() == telemetrytypes.SignalMetrics {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "raw request type is not supported for metric queries")
}
}
}
if len(r.CompositeQuery.Queries) == 0 {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "at least one query is required")
}
// Builder query names must be unique across the composite query.
queryNames := make(map[string]bool)
for _, envelope := range r.CompositeQuery.Queries {
if envelope.Type == QueryTypeBuilder || envelope.Type == QueryTypeSubQuery {
name := envelope.GetQueryName()
if name != "" {
if queryNames[name] {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "duplicate query name '%s'", name)
}
queryNames[name] = true
}
}
}
if err := r.validateAllQueriesNotDisabled(); err != nil {
return nil, err
}
return opts, nil
}
// Validate parses the preview query-string parameters. Verbose defaults to true
// and accepts true/1/false/0; any other value is rejected.
func (p *QueryRangePreviewParams) Validate() (QueryRangePreviewOptions, error) {
switch strings.ToLower(strings.TrimSpace(p.Verbose)) {
case "", "true", "1":
return QueryRangePreviewOptions{Verbose: true}, nil
case "false", "0":
return QueryRangePreviewOptions{Verbose: false}, nil
}
return QueryRangePreviewOptions{}, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid verbose value %q (allowed: true, false)", p.Verbose)
}
// Validate validates a single query envelope's spec — the per-query counterpart
// to ValidateRequestScope, used by the dry-run to report errors independently.
func (e QueryEnvelope) Validate(opts ...ValidationOption) error {
return validateQueryEnvelope(e, opts...)
}
// validateAllQueriesNotDisabled validates that at least one query in the composite query is enabled.
func (r *QueryRangeRequest) validateAllQueriesNotDisabled() error {
for _, envelope := range r.CompositeQuery.Queries {