SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore: refactor error response + normalize ClickHouse telemetrystore errors (#11740)
Tushar Vats1700ad06e6dd
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 4a7750f65e..5a7fff53f0 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -3755,10 +3755,16 @@ components:type:type: stringurl:+ nullable: truetype: stringrequired:+ - type- code- message+ - url+ - errors+ - retry+ - suggestionstype: objectErrorsResponseerroradditional:properties:@@ -3768,11 +3774,17 @@ components:items:type: stringtype: array+ required:+ - message+ - suggestionstype: objectErrorsResponseretryjson:+ nullable: trueproperties:delay:$ref: '#/components/schemas/TimeDuration'+ required:+ - delaytype: objectFactoryResponse:properties:diff --git a/docs/contributing/go/errors.md b/docs/contributing/go/errors.mdindex 7c5ce1eb36..8b73f2e257 100644--- a/docs/contributing/go/errors.md+++ b/docs/contributing/go/errors.md@@ -36,6 +36,55 @@ var (> 💡 **Note**: Error codes must match the regex `^[a-z_]+$` otherwise the code will panic.+### Message+The primary, human-readable summary of what went wrong, set when the error is created via `errors.New` / `errors.Newf`. Note there are two distinct `message` fields in the response: this top-level one states the overall failure, while each entry under [Additional](#additional) carries its own [message](#message-1) explaining one specific facet of it.++### Url+An optional link to documentation that explains the error in more depth, set with `WithUrl`. It is left empty when the error has no associated doc.++```go+return errors.New(errors.TypeInvalidInput, CodeBadThing, "bad thing").+ WithUrl("https://signoz.io/docs/...")+```++### Additional+`errors` is a list of supplementary details that explain the top-level `message`. Each entry has its own `message` and `suggestions`, so a single error can surface several distinct problems individually. Attach details with `WithAdditional` (message only) or `WithSuggestiveAdditional` (message plus the suggestions that belong to it):++#### Message+A single, self-contained sentence describing one specific facet of the error (e.g. ``field `filed` not found``), distinct from the top-level [Message](#message). Prefer one detail per distinct problem over concatenating several into one message.++#### Suggestions+The suggestions tied to that specific detail — typically a ``did you mean: `x` `` correction for the value the detail is about. These are distinct from the error-wide [Suggestions](#suggestions) below: detail-scoped suggestions never leak into the top-level list.++```go+return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown field %q", field).+ WithAdditional("field `field` not found")+return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown field %q", field).+ WithSuggestiveAdditional("field `filed` not found", "did you mean: `field`")+```++### Retry+Carries the `delay` the client should wait before retrying, set with `WithRetryAfter`. It is `null` when the error is not retryable.++```go+return errors.NewTimeoutf(CodeSlow, "upstream timed out").+ WithRetryAfter(5 * time.Second)+```++### Suggestions+`WithSuggestions` sets the error-wide `suggestions` list — hints about the error as a whole (e.g. "narrow the time range window"), as opposed to suggestions tied to a single detail. Prefer the builders in [pkg/errors/suggestions.go](/pkg/errors/suggestions.go) over hand-writing the strings so the phrasing stays consistent:++- `NewSuggestionsOnLevenshteinDistance(invalidInput, noun, validInputs)` — returns a ``did you mean: `x` `` correction (when a close typo match exists) followed by the valid-references list.+- `NewValidReferences(noun, values...)` — formats a capped list as ``valid <noun> are `a`, `b` `` (e.g. `"valid fields are"`, `"valid keys are"`). Returns `""` for an empty set.+- `NewSuggestionsFromFunc(produce)` — wraps a caller-computed correction string as a one-element ``did you mean: `x` `` slice (or nil when it returns `""`), for callers with their own matching strategy.++`noun` names the kind of value being suggested. Use one of the exported `Noun*` constants (`errors.NounFields`, `errors.NounKeys`, `errors.NounServices`, …) so the wording stays uniform across the codebase.++```go+return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown field %q", field).+ WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field, errors.NounFields, validFields)...)+```+## Show me some examples### Using the errordiff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex e7261308dd..a2e95eb37b 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -2178,16 +2178,21 @@ export interface ErrorsResponseerroradditionalDTO {/*** @type string*/- message?: string;+ message: string;/*** @type array*/- suggestions?: string[];+ suggestions: string[];}-export interface ErrorsResponseretryjsonDTO {- delay?: TimeDurationDTO;-}+export type ErrorsResponseretryjsonDTOAnyOf = {+ delay: TimeDurationDTO;+};++/**+ * @nullable+ */+export type ErrorsResponseretryjsonDTO = ErrorsResponseretryjsonDTOAnyOf | null;export interface ErrorsJSONDTO {/**@@ -2197,24 +2202,24 @@ export interface ErrorsJSONDTO {/*** @type array*/- errors?: ErrorsResponseerroradditionalDTO[];+ errors: ErrorsResponseerroradditionalDTO[];/*** @type string*/message: string;- retry?: ErrorsResponseretryjsonDTO;+ retry: ErrorsResponseretryjsonDTO | null;/*** @type array*/- suggestions?: string[];+ suggestions: string[];/*** @type string*/- type?: string;+ type: string;/**- * @type string+ * @type string,null*/- url?: string;+ url: string | null;}export interface AuthtypesOrgSessionContextDTO {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.tsindex b0d5640fb2..7194e5a5d4 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts@@ -26,7 +26,13 @@ describe('panelStatusFromError', () => {code: 'invalid_query',message: 'Query is invalid',url: 'https://docs/err',- errors: [{ message: 'missing aggregation' }, { message: 'bad filter' }],+ errors: [+ { message: 'missing aggregation', suggestions: [] },+ { message: 'bad filter', suggestions: [] },+ ],+ retry: null,+ suggestions: [],+ type: '',});expect(panelStatusFromError(error)).toStrictEqual({@@ -48,7 +54,15 @@ describe('panelStatusFromError', () => {it('omits docsUrl when the API error has no url', () => {const error = axiosErrorWith(- { code: 'x', message: 'y', url: '', errors: [] },+ {+ code: 'x',+ message: 'y',+ url: '',+ errors: [],+ retry: null,+ suggestions: [],+ type: '',+ },StatusCodes.INTERNAL_SERVER_ERROR,);diff --git a/go.mod b/go.modindex 42bdb0e1b3..33f86e3582 100644--- a/go.mod+++ b/go.mod@@ -180,7 +180,7 @@ require (github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirectgithub.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirectgithub.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.0github.com/Masterminds/squirrel v1.5.4 // indirectgithub.com/Yiling-J/theine-go v0.6.2 // indirectgithub.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52bdiff --git a/pkg/errors/errors.go b/pkg/errors/errors.goindex 758ad4a23e..964b8c7cc9 100644--- a/pkg/errors/errors.go+++ b/pkg/errors/errors.go@@ -75,6 +75,12 @@ func (b *base) Error() string {return b.m}+// Unwrap exposes the wrapped cause so stdlib errors.Is / errors.As can walk+// the chain — e.g. errors.Is(WrapCanceledf(context.Canceled, …), context.Canceled).+func (b *base) Unwrap() error {+ return b.e+}+// New returns a base error. It requires type, code and message as input.func New(t typ, code Code, message string) *base {return &base{@@ -337,6 +343,16 @@ func NewTimeoutf(code Code, format string, args ...any) *base {return Newf(TypeTimeout, code, format, args...)}+// WrapCanceledf is a wrapper around Wrapf with TypeCanceled.+func WrapCanceledf(cause error, code Code, format string, args ...any) *base {+ return Wrapf(cause, TypeCanceled, code, format, args...)+}++// NewCanceledf is a wrapper around Newf with TypeCanceled.+func NewCanceledf(code Code, format string, args ...any) *base {+ return Newf(TypeCanceled, code, format, args...)+}+// WrapUnauthenticatedf is a wrapper around Wrapf with TypeUnauthenticated.func WrapUnauthenticatedf(cause error, code Code, format string, args ...any) *base {return Wrapf(cause, TypeUnauthenticated, code, format, args...)diff --git a/pkg/errors/errors_test.go b/pkg/errors/errors_test.goindex 423bb45eef..c737fdca92 100644--- a/pkg/errors/errors_test.go+++ b/pkg/errors/errors_test.go@@ -1,6 +1,7 @@package errorsimport (+ "context""errors" //nolint:depguard"testing""time"@@ -84,7 +85,7 @@ func TestWithSuggestiveAdditional(t *testing.T) {assert.Equal(t, []responseerroradditional{{Message: "field `filed` not found", Suggestions: []string{"did you mean: `field`"}},}, j.Errors)- assert.Nil(t, j.Suggestions, "detail-scoped suggestions must not leak into the error-wide list")+ assert.Empty(t, j.Suggestions, "detail-scoped suggestions must not leak into the error-wide list")}func TestWithRetryAfter(t *testing.T) {@@ -106,7 +107,12 @@ func TestAsJSONBaseError(t *testing.T) {assert.Equal(t, "bad_input", j.Code)assert.Equal(t, "field foo is bad", j.Message)assert.Equal(t, "https://docs/bad_input", j.Url)- assert.Equal(t, []responseerroradditional{{Message: "hint1"}, {Message: "hint2"}}, j.Errors)+ // A detail with no suggestions carries an empty (non-nil) slice — the+ // suggestions field is non-nullable, so it marshals to [] rather than null.+ assert.Equal(t, []responseerroradditional{+ {Message: "hint1", Suggestions: []string{}},+ {Message: "hint2", Suggestions: []string{}},+ }, j.Errors)// InvalidInput auto-applies the after_fix policy via NewInvalidInputf — but// New (bare constructor) does not. The retry block should reflect that.@@ -157,9 +163,16 @@ func TestAsJSONRetryBlock(t *testing.T) {})}-func TestAsJSONOptionalFieldsOmittedWhenEmpty(t *testing.T) {+func TestAsJSONEmptyWhenNoneSet(t *testing.T) {+ // errors and suggestions are non-nullable in the OpenAPI spec, so AsJSON+ // leaves them as empty (non-nil) slices when the error carries none — they+ // marshal to [] rather than null.j := AsJSON(New(TypeInternal, MustNewCode("boom"), "boom"))- assert.Nil(t, j.Suggestions, "no suggestions set => Suggestions must be nil so json omitempty drops it")++ assert.NotNil(t, j.Suggestions)+ assert.Empty(t, j.Suggestions)+ assert.NotNil(t, j.Errors)+ assert.Empty(t, j.Errors)}func TestWithStacktrace(t *testing.T) {@@ -173,3 +186,16 @@ func TestWithStacktrace(t *testing.T) {assert.Equal(t, "test_code", code.String())assert.Equal(t, "panic", message)}++// Wrapped context sentinels must remain detectable via errors.Is so callers+// that branch on context.Canceled / context.DeadlineExceeded keep working+// after the error passes through one of the signoz Wrap* helpers.+func TestWrapPreservesContextSentinels(t *testing.T) {+ canceled := WrapCanceledf(context.Canceled, MustNewCode("canceled"), "op canceled")+ assert.True(t, Is(canceled, context.Canceled))+ assert.False(t, Is(canceled, context.DeadlineExceeded))++ deadline := WrapTimeoutf(context.DeadlineExceeded, MustNewCode("timeout"), "op timed out")+ assert.True(t, Is(deadline, context.DeadlineExceeded))+ assert.False(t, Is(deadline, context.Canceled))+}diff --git a/pkg/errors/http.go b/pkg/errors/http.goindex b60baf36e1..3ea5544f59 100644--- a/pkg/errors/http.go+++ b/pkg/errors/http.go@@ -7,32 +7,29 @@ import ()type JSON struct {- Type string `json:"type,omitempty"`+ Type string `json:"type" required:"true"`Code string `json:"code" required:"true"`Message string `json:"message" required:"true"`- Url string `json:"url,omitempty"`- Errors []responseerroradditional `json:"errors,omitempty"`- Retry *responseretryjson `json:"retry,omitempty"`- Suggestions []string `json:"suggestions,omitempty"`+ Url string `json:"url" required:"true" nullable:"true"`+ Errors []responseerroradditional `json:"errors" required:"true" nullable:"false"`+ Retry *responseretryjson `json:"retry" required:"true" nullable:"true"`+ Suggestions []string `json:"suggestions" required:"true" nullable:"false"`}type responseretryjson struct {- Delay time.Duration `json:"delay"`+ Delay time.Duration `json:"delay" required:"true" nullable:"false"`}type responseerroradditional struct {- Message string `json:"message,omitempty"`- Suggestions []string `json:"suggestions,omitempty"`+ Message string `json:"message" required:"true"`+ Suggestions []string `json:"suggestions" required:"true" nullable:"false"`}func AsJSON(cause error) *JSON {// See if this is an instance of the base error or nott, c, m, _, u, a := Unwrapb(cause)- rea := make([]responseerroradditional, len(a))- for k, v := range a {- rea[k] = responseerroradditional{Message: v.message, Suggestions: v.suggestions}- }+ rea := responseAdditionals(a)var retry *responseretryjsonif r := retryOf(cause); r != nil {@@ -46,7 +43,7 @@ func AsJSON(cause error) *JSON {Url: u,Errors: rea,Retry: retry,- Suggestions: suggestionsOf(cause),+ Suggestions: nonNilStrings(suggestionsOf(cause)),}}@@ -54,10 +51,7 @@ func AsURLValues(cause error) url.Values {// See if this is an instance of the base error or not_, c, m, _, u, a := Unwrapb(cause)- rea := make([]responseerroradditional, len(a))- for k, v := range a {- rea[k] = responseerroradditional{Message: v.message, Suggestions: v.suggestions}- }+ rea := responseAdditionals(a)errors, err := json.Marshal(rea)if err != nil {@@ -75,3 +69,20 @@ func AsURLValues(cause error) url.Values {"errors": {string(errors)},}}++func responseAdditionals(a []additional) []responseerroradditional {+ rea := make([]responseerroradditional, len(a))+ for k, v := range a {+ rea[k] = responseerroradditional{Message: v.message, Suggestions: nonNilStrings(v.suggestions)}+ }++ return rea+}++func nonNilStrings(s []string) []string {+ if s == nil {+ return []string{}+ }++ return s+}diff --git a/pkg/errors/suggestions.go b/pkg/errors/suggestions.goindex 4aa2e9555a..69a5771164 100644--- a/pkg/errors/suggestions.go+++ b/pkg/errors/suggestions.go@@ -5,6 +5,18 @@ import ("strings")+// Nouns name the kind of value a suggestion refers to. Pass one to+// NewValidReferences / NewSuggestionsOnLevenshteinDistance to phrase the+// "valid <noun> are ..." list consistently across the codebase.+const (+ NounFields = "fields"+ NounKeys = "keys"+ NounServices = "services"+ NounQueryTypes = "query types"+ NounSignals = "signals"+ NounReferences = "references"+)+const (typoSuggestionThreshold = 0.75// maxValidReferences caps how many valid references are listed so@@ -13,17 +25,18 @@ const (maxValidReferences = 20)-// SuggestionsOnLevenshteinDistance returns a "did you mean" correction (only+// NewSuggestionsOnLevenshteinDistance returns a "did you mean" correction (only// when a close match at least typoSuggestionThreshold similar exists) followed-// by the valid-references list.-func SuggestionsOnLevenshteinDistance(invalidInput string, validInputs []string) []string {+// by the valid-references list. noun names the kind of value being suggested+// (e.g. "fields", "keys") and is used to phrase the valid-references list.+func NewSuggestionsOnLevenshteinDistance(invalidInput string, noun string, validInputs []string) []string {suggestions := make([]string, 0, 2)if match, ok := ClosestLevenshteinMatch(invalidInput, validInputs); ok {suggestions = append(suggestions, didYouMean(match))}- if refs := ValidReferences(validInputs...); refs != "" {+ if refs := NewValidReferences(noun, validInputs...); refs != "" {suggestions = append(suggestions, refs)}@@ -52,10 +65,10 @@ func ClosestLevenshteinMatch(input string, candidates []string) (string, bool) {return "", false}-// SuggestionsFromFunc formats the string produce returns as a one-element+// NewSuggestionsFromFunc formats the string produce returns as a one-element// "did you mean: `x`" slice, or nil when it returns the empty string (so callers// with their own matching strategy compose into a suggestions list cleanly).-func SuggestionsFromFunc(produce func() string) []string {+func NewSuggestionsFromFunc(produce func() string) []string {s := produce()if s == "" {return nil@@ -64,12 +77,12 @@ func SuggestionsFromFunc(produce func() string) []string {return []string{didYouMean(s)}}-// ValidReferences formats values as "valid references: `a`, `b`", capped at-// maxValidReferences with a "(+N more)" suffix. Each value is rendered as its-// own string, an Enum() element's StringValue(), or fmt.Sprint as a fallback.-// It returns "" when there are no values, so callers don't surface a bare-// "valid references: " with nothing after it.-func ValidReferences[T any](values ...T) string {+// NewValidReferences formats values as "valid <noun> are `a`, `b`" (e.g. noun+// "fields", "functions", "keys"), capped at maxValidReferences with a "(+N more)"+// suffix. Each value is rendered as its own string, an Enum() element's+// StringValue(), or fmt.Sprint as a fallback. It returns "" when there are no+// values, so callers don't surface a bare "valid <noun> are" with nothing after it.+func NewValidReferences[T any](noun string, values ...T) string {if len(values) == 0 {return ""}@@ -97,7 +110,7 @@ func ValidReferences[T any](values ...T) string {quoted[i] = "`" + r + "`"}- out := "valid references: " + strings.Join(quoted, ", ")+ out := "valid " + noun + " are " + strings.Join(quoted, ", ")if truncated > 0 {out += fmt.Sprintf(" (+%d more)", truncated)}diff --git a/pkg/errors/suggestions_test.go b/pkg/errors/suggestions_test.goindex 603e066584..f435364a89 100644--- a/pkg/errors/suggestions_test.go+++ b/pkg/errors/suggestions_test.go@@ -6,26 +6,28 @@ import ("github.com/stretchr/testify/assert")-func TestValidReferences(t *testing.T) {- // An empty set returns "" so callers don't surface a bare "valid references: ".- assert.Equal(t, "", ValidReferences[string]())+func TestNewValidReferences(t *testing.T) {+ // An empty set returns "" so callers don't surface a bare "valid <noun> are".+ assert.Equal(t, "", NewValidReferences[string](NounFields))- assert.Equal(t, "valid references: `a`, `b`", ValidReferences("a", "b"))+ // The noun phrases the list, e.g. "valid fields are", "valid keys are".+ assert.Equal(t, "valid fields are `a`, `b`", NewValidReferences(NounFields, "a", "b"))+ assert.Equal(t, "valid keys are `a`, `b`", NewValidReferences(NounKeys, "a", "b"))}-func TestSuggestionsOnLevenshteinDistance(t *testing.T) {- // No valid inputs => no suggestions at all (no bare "valid references: ").- assert.Empty(t, SuggestionsOnLevenshteinDistance("foo", nil))+func TestNewSuggestionsOnLevenshteinDistance(t *testing.T) {+ // No valid inputs => no suggestions at all (no bare "valid <noun> are").+ assert.Empty(t, NewSuggestionsOnLevenshteinDistance("foo", NounFields, nil))// Close match => did-you-mean plus the valid-references list.assert.Equal(t,- []string{"did you mean: `name`", "valid references: `name`, `color`"},- SuggestionsOnLevenshteinDistance("nam", []string{"name", "color"}),+ []string{"did you mean: `name`", "valid fields are `name`, `color`"},+ NewSuggestionsOnLevenshteinDistance("nam", NounFields, []string{"name", "color"}),)// No close match => valid-references list only.assert.Equal(t,- []string{"valid references: `name`, `color`"},- SuggestionsOnLevenshteinDistance("zzzzz", []string{"name", "color"}),+ []string{"valid fields are `name`, `color`"},+ NewSuggestionsOnLevenshteinDistance("zzzzz", NounFields, []string{"name", "color"}),)}diff --git a/pkg/http/binding/json.go b/pkg/http/binding/json.goindex e275ab420c..60b4ecf2ae 100644--- a/pkg/http/binding/json.go+++ b/pkg/http/binding/json.go@@ -3,10 +3,10 @@ package bindingimport ("encoding/json""io"- "reflect""strings""github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/jsonschema")const (@@ -76,7 +76,7 @@ func (b *jsonBinding) BindBody(body io.Reader, obj any, opts ...BindBodyOption)return errors.NewInvalidInputf(errors.CodeInvalidInput, message, field).- WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field, JSONFieldNames(obj))...)+ WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field, errors.NounFields, jsonschema.JSONFieldNames(obj))...)}}@@ -86,37 +86,6 @@ func (b *jsonBinding) BindBody(body io.Reader, obj any, opts ...BindBodyOption)return nil}-// JSONFieldNames returns the JSON field names of a struct (or pointer to one),-// skipping fields tagged "-" or without a json tag.-func JSONFieldNames(v any) []string {- var fields []string-- t := reflect.TypeOf(v)- if t.Kind() == reflect.Pointer {- t = t.Elem()- }-- if t.Kind() != reflect.Struct {- return fields- }-- for i := 0; i < t.NumField(); i++ {- field := t.Field(i)- jsonTag := field.Tag.Get("json")-- if jsonTag == "" || jsonTag == "-" {- continue- }-- fieldName := strings.Split(jsonTag, ",")[0]- if fieldName != "" {- fields = append(fields, fieldName)- }- }-- return fields-}-// extractUnknownField pulls fieldname out of a `json: unknown field "fieldname"`// decoder message, or returns "" when the message has no quoted field.func extractUnknownField(errMsg string) string {diff --git a/pkg/http/binding/json_test.go b/pkg/http/binding/json_test.goindex 2963d3331e..ae2df33028 100644--- a/pkg/http/binding/json_test.go+++ b/pkg/http/binding/json_test.go@@ -90,21 +90,21 @@ func TestJSONBinding_BindBody_UnknownFieldSuggestions(t *testing.T) {body: `{"shape":"round"}`,opts: []BindBodyOption{WithDisallowUnknownFields(true)},message: `unknown field "shape"`,- suggestions: []string{"valid references: `name`, `color`"},+ suggestions: []string{"valid fields are `name`, `color`"},},{name: "WithContext",body: `{"shape":"round"}`,opts: []BindBodyOption{WithDisallowUnknownFields(true), WithUnknownFieldContext("widget spec")},message: `unknown field "shape" in widget spec`,- suggestions: []string{"valid references: `name`, `color`"},+ suggestions: []string{"valid fields are `name`, `color`"},},{name: "NearMatch",body: `{"nam":"x"}`,opts: []BindBodyOption{WithDisallowUnknownFields(true)},message: `unknown field "nam"`,- suggestions: []string{"did you mean: `name`", "valid references: `name`, `color`"},+ suggestions: []string{"did you mean: `name`", "valid fields are `name`, `color`"},},}diff --git a/pkg/http/render/render_test.go b/pkg/http/render/render_test.goindex 46432a7f72..a793df0cc4 100644--- a/pkg/http/render/render_test.go+++ b/pkg/http/render/render_test.go@@ -99,13 +99,13 @@ func TestError(t *testing.T) {name: "AlreadyExists",statusCode: http.StatusConflict,err: errors.New(errors.TypeAlreadyExists, errors.MustNewCode("already_exists"), "already exists").WithUrl("https://already_exists"),- expected: []byte(`{"status":"error","error":{"type":"already-exists","code":"already_exists","message":"already exists","url":"https://already_exists"}}`),+ expected: []byte(`{"status":"error","error":{"type":"already-exists","code":"already_exists","message":"already exists","url":"https://already_exists","errors":[],"retry":null,"suggestions":[]}}`),},"/unauthenticated": {name: "Unauthenticated",statusCode: http.StatusUnauthorized,err: errors.New(errors.TypeUnauthenticated, errors.MustNewCode("not_allowed"), "not allowed").WithUrl("https://unauthenticated").WithAdditional("a1", "a2"),- expected: []byte(`{"status":"error","error":{"type":"unauthenticated","code":"not_allowed","message":"not allowed","url":"https://unauthenticated","errors":[{"message":"a1"},{"message":"a2"}]}}`),+ expected: []byte(`{"status":"error","error":{"type":"unauthenticated","code":"not_allowed","message":"not allowed","url":"https://unauthenticated","errors":[{"message":"a1","suggestions":[]},{"message":"a2","suggestions":[]}],"retry":null,"suggestions":[]}}`),},}@@ -177,8 +177,8 @@ func TestErrorRetryAfterHeader(t *testing.T) {name: "BareErrorNoHeaderNoRetryBlock",err: errors.New(errors.TypeInternal, errors.MustNewCode("boom"), "boom"),wantRetryAfter: "",- wantBodyContains: `"code":"boom"`,- wantBodyNotContains: `"retry"`,+ wantBodyContains: `"retry":null`,+ wantBodyNotContains: `"delay"`,},}diff --git a/pkg/jsonschema/fields.go b/pkg/jsonschema/fields.gonew file mode 100644index 0000000000..0c620355e9--- /dev/null+++ b/pkg/jsonschema/fields.go@@ -0,0 +1,38 @@+// Package jsonschema holds small reflection helpers shared across packages.+package jsonschema++import (+ "reflect"+ "strings"+)++// JSONFieldNames returns the JSON field names of a struct (or pointer to one),+// skipping fields tagged "-" or without a json tag.+func JSONFieldNames(v any) []string {+ var fields []string++ t := reflect.TypeOf(v)+ if t.Kind() == reflect.Pointer {+ t = t.Elem()+ }++ if t.Kind() != reflect.Struct {+ return fields+ }++ for i := 0; i < t.NumField(); i++ {+ field := t.Field(i)+ jsonTag := field.Tag.Get("json")++ if jsonTag == "" || jsonTag == "-" {+ continue+ }++ fieldName := strings.Split(jsonTag, ",")[0]+ if fieldName != "" {+ fields = append(fields, fieldName)+ }+ }++ return fields+}diff --git a/pkg/querybuilder/fallback_expr.go b/pkg/querybuilder/fallback_expr.goindex b95d57781e..38ab1b9d77 100644--- a/pkg/querybuilder/fallback_expr.go+++ b/pkg/querybuilder/fallback_expr.go@@ -81,7 +81,7 @@ func CollisionHandledFinalExpr(// - it is not a static field// - the next best thing to do is see if there is a typo// and suggest a correction- wrappedErr := errors.WithSuggestiveAdditionalf(fieldForErr, errors.SuggestionsOnLevenshteinDistance(field.Name, maps.Keys(keys)), "field `%s` not found", field.Name)+ wrappedErr := errors.WithSuggestiveAdditionalf(fieldForErr, errors.NewSuggestionsOnLevenshteinDistance(field.Name, errors.NounKeys, maps.Keys(keys)), "field `%s` not found", field.Name)return "", nil, wrappedErr} else {for _, key := range keysForField {diff --git a/pkg/querybuilder/having_expression_validator.go b/pkg/querybuilder/having_expression_validator.goindex 5c0fb1044b..2870ccd365 100644--- a/pkg/querybuilder/having_expression_validator.go+++ b/pkg/querybuilder/having_expression_validator.go@@ -300,7 +300,7 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (stringvar suggestions []stringif len(v.invalid) == 1 {inv := v.invalid[0]- suggestions = errors.SuggestionsFromFunc(func() string {+ suggestions = errors.NewSuggestionsFromFunc(func() string {match, ok := errors.ClosestLevenshteinMatch(inv, validKeys)if !ok || strings.Contains(original, inv+"(") || strings.Contains(match, "(") {return ""@@ -309,7 +309,7 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string})}- suggestions = append(suggestions, errors.ValidReferences(validKeys...))+ suggestions = append(suggestions, errors.NewValidReferences(errors.NounReferences, validKeys...))havingErr := errors.NewInvalidInputf(errors.CodeInvalidInput,"Invalid references in `Having` expression: [%s]",@@ -339,7 +339,7 @@ func (r *HavingExpressionRewriter) rewriteAndValidate(expression string) (string// multiple errors are surfaced as one additional detail each. If the parser// produced no message (rare), the top-level message stands on its own.if len(allSyntaxErrors) == 1 && len(msgs) == 1 {- suggestions := errors.SuggestionsFromFunc(func() string {+ suggestions := errors.NewSuggestionsFromFunc(func() string {return havingSuggestion(allSyntaxErrors[0], original)})diff --git a/pkg/querybuilder/having_rewriter_test.go b/pkg/querybuilder/having_rewriter_test.goindex c6d64afee4..d1da4487da 100644--- a/pkg/querybuilder/having_rewriter_test.go+++ b/pkg/querybuilder/having_rewriter_test.go@@ -593,7 +593,7 @@ func TestRewriteForLogsAndTraces_InOperator(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [ghost]",wantAdditional: []string{"Valid references are: [__result, __result0, count(), total]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `count()`, `total`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `count()`, `total`"},},{name: "IN with end bracked missing",@@ -655,7 +655,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [unknown_alias]",wantAdditional: []string{"Valid references are: [__result, __result0, count(), total]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `count()`, `total`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `count()`, `total`"},},{name: "typo in identifier suggests closest match",@@ -666,7 +666,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [totol]",wantAdditional: []string{"Valid references are: [__result, __result0, count(), total]"},- wantSuggestions: []string{"did you mean: `total > 100`", "valid references: `__result`, `__result0`, `count()`, `total`"},+ wantSuggestions: []string{"did you mean: `total > 100`", "valid references are `__result`, `__result0`, `count()`, `total`"},},{name: "expression not in column map",@@ -677,7 +677,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [sum]",wantAdditional: []string{"Valid references are: [__result, __result0, count()]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `count()`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `count()`"},},{name: "one valid one invalid reference",@@ -688,7 +688,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [ghost]",wantAdditional: []string{"Valid references are: [__result, __result0, count(), total]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `count()`, `total`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `count()`, `total`"},},{name: "__result ambiguous with multiple aggregations",@@ -700,7 +700,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [__result]",wantAdditional: []string{"Valid references are: [__result0, __result1, count(), sum(bytes)]"},- wantSuggestions: []string{"did you mean: `__result0 > 100`", "valid references: `__result0`, `__result1`, `count()`, `sum(bytes)`"},+ wantSuggestions: []string{"did you mean: `__result0 > 100`", "valid references are `__result0`, `__result1`, `count()`, `sum(bytes)`"},},{name: "out-of-range __result_N index",@@ -711,7 +711,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [__result_9]",wantAdditional: []string{"Valid references are: [__result, __result0, count()]"},- wantSuggestions: []string{"did you mean: `__result > 100`", "valid references: `__result`, `__result0`, `count()`"},+ wantSuggestions: []string{"did you mean: `__result > 100`", "valid references are `__result`, `__result0`, `count()`"},},{name: "__result_1 out of range for single aggregation",@@ -722,7 +722,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [__result_1]",wantAdditional: []string{"Valid references are: [__result, __result0, count()]"},- wantSuggestions: []string{"did you mean: `__result > 100`", "valid references: `__result`, `__result0`, `count()`"},+ wantSuggestions: []string{"did you mean: `__result > 100`", "valid references are `__result`, `__result0`, `count()`"},},{name: "cascaded function calls",@@ -733,7 +733,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [sum]",wantAdditional: []string{"Valid references are: [__result, __result0, count()]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `count()`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `count()`"},},{name: "function call with multiple args not in column map",@@ -744,7 +744,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [sum]",wantAdditional: []string{"Valid references are: [__result, __result0, sum(a)]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `sum(a)`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `sum(a)`"},},{name: "unquoted string value treated as unknown identifier",@@ -755,7 +755,7 @@ func TestRewriteForLogsAndTraces_ErrorInvalidReferences(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [xyz]",wantAdditional: []string{"Valid references are: [__result, __result0, sum(bytes)]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `sum(bytes)`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `sum(bytes)`"},},})}@@ -1030,7 +1030,7 @@ func TestRewriteForMetrics(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [wrong_metric]",wantAdditional: []string{"Valid references are: [__result, __result0, sum(cpu_usage)]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `sum(cpu_usage)`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `sum(cpu_usage)`"},},// --- Error: string literal (not allowed in HAVING) ---{@@ -1077,7 +1077,7 @@ func TestRewriteForMetrics(t *testing.T) {wantErr: true,wantErrMsg: "Invalid references in `Having` expression: [count]",wantAdditional: []string{"Valid references are: [__result, __result0, sum(cpu_usage)]"},- wantSuggestions: []string{"valid references: `__result`, `__result0`, `sum(cpu_usage)`"},+ wantSuggestions: []string{"valid references are `__result`, `__result0`, `sum(cpu_usage)`"},},}diff --git a/pkg/telemetryaudit/field_mapper.go b/pkg/telemetryaudit/field_mapper.goindex 8f5c4e9b09..a90bc42484 100644--- a/pkg/telemetryaudit/field_mapper.go+++ b/pkg/telemetryaudit/field_mapper.go@@ -109,7 +109,7 @@ func (m *fieldMapper) ColumnExpressionFor(field.FieldContext = telemetrytypes.FieldContextLogfieldExpression, _ = m.FieldFor(ctx, tsStart, tsEnd, field)} else {- wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field.Name, maps.Keys(keys))...)+ wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field.Name, errors.NounKeys, maps.Keys(keys))...)return "", wrappedErr}} else {diff --git a/pkg/telemetrylogs/field_mapper.go b/pkg/telemetrylogs/field_mapper.goindex 29dc63a8de..0fb1b03934 100644--- a/pkg/telemetrylogs/field_mapper.go+++ b/pkg/telemetrylogs/field_mapper.go@@ -263,7 +263,7 @@ func (m *fieldMapper) ColumnExpressionFor(// - it is not a static field// - the next best thing to do is see if there is a typo// and suggest a correction- wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field.Name, maps.Keys(keys))...)+ wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field.Name, errors.NounKeys, maps.Keys(keys))...)return "", wrappedErr}} else if len(keysForField) == 1 {diff --git a/pkg/telemetrymetadata/field_mapper.go b/pkg/telemetrymetadata/field_mapper.goindex ddc30c1567..f3daaa2764 100644--- a/pkg/telemetrymetadata/field_mapper.go+++ b/pkg/telemetrymetadata/field_mapper.go@@ -91,7 +91,7 @@ func (m *fieldMapper) ColumnExpressionFor(// - it is not a static field// - the next best thing to do is see if there is a typo// and suggest a correction- wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field.Name, maps.Keys(keys))...)+ wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field.Name, errors.NounKeys, maps.Keys(keys))...)return "", wrappedErr}} else if len(keysForField) == 1 {diff --git a/pkg/telemetrystore/clickhousetelemetrystore/provider.go b/pkg/telemetrystore/clickhousetelemetrystore/provider.goindex 193c59f434..cfd51455a9 100644--- a/pkg/telemetrystore/clickhousetelemetrystore/provider.go+++ b/pkg/telemetrystore/clickhousetelemetrystore/provider.go@@ -3,13 +3,76 @@ package clickhousetelemetrystoreimport ("context"+ chproto "github.com/ClickHouse/ch-go/proto""github.com/ClickHouse/clickhouse-go/v2""github.com/ClickHouse/clickhouse-go/v2/lib/driver"+ "github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/telemetrystore""go.opentelemetry.io/otel/metric")+var (+ ErrCodeSyntaxError = errors.MustNewCode("syntax_error")+ ErrCodeUnknownTable = errors.MustNewCode("unknown_table")+ ErrCodeUnknownDatabase = errors.MustNewCode("unknown_database")+ ErrCodeUnknownIdentifier = errors.MustNewCode("unknown_identifier")+ ErrCodeIllegalArgument = errors.MustNewCode("illegal_argument")++ ErrCodeQueryCanceled = errors.MustNewCode("query_canceled")+ ErrCodeQueryTimeout = errors.MustNewCode("query_timeout")+ ErrCodeExecutionFailed = errors.MustNewCode("execution_failed")+)++// Codes absent from this map fall through to the raw driver error in castError.+var clickHouseExceptionWrappers = map[chproto.Error]func(cause error, ex *clickhouse.Exception) error{+ chproto.ErrSyntaxError: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeSyntaxError, "SQL syntax error: %s", ex.Message)+ },+ chproto.ErrUnknownTable: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapNotFoundf(cause, ErrCodeUnknownTable, "unknown table: %s", ex.Message)+ },+ chproto.ErrUnknownDatabase: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapNotFoundf(cause, ErrCodeUnknownDatabase, "unknown database: %s", ex.Message)+ },+ chproto.ErrUnknownIdentifier: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "unknown identifier: %s", ex.Message)+ },+ chproto.ErrUnknownFunction: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "unknown function: %s", ex.Message)+ },+ chproto.ErrUnknownAggregateFunction: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "unknown aggregate function: %s", ex.Message)+ },+ chproto.ErrUnknownType: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "unknown type: %s", ex.Message)+ },+ chproto.ErrUnknownStorage: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "unknown storage engine: %s", ex.Message)+ },+ chproto.ErrIllegalColumn: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeUnknownIdentifier, "illegal column: %s", ex.Message)+ },+ chproto.ErrUnknownElementInAst: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeSyntaxError, "unknown element in SQL AST: %s", ex.Message)+ },+ chproto.ErrUnknownTypeOfQuery: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeSyntaxError, "unknown query type: %s", ex.Message)+ },+ chproto.ErrIllegalTypeOfArgument: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeIllegalArgument, "illegal argument type: %s", ex.Message)+ },+ chproto.ErrNumberOfArgumentsDoesntMatch: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeIllegalArgument, "wrong number of arguments: %s", ex.Message)+ },+ chproto.ErrTooManyArgumentsForFunction: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeIllegalArgument, "too many arguments to function: %s", ex.Message)+ },+ chproto.ErrTooLessArgumentsForFunction: func(cause error, ex *clickhouse.Exception) error {+ return errors.WrapInvalidInputf(cause, ErrCodeIllegalArgument, "too few arguments to function: %s", ex.Message)+ },+}+type provider struct {settings factory.ScopedProviderSettingsclickHouseConn clickhouse.Conn@@ -103,7 +166,7 @@ func (p *provider) Query(ctx context.Context, query string, args ...interface{})if err != nil {event.Err = errtelemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return nil, err+ return nil, castError(err)}return &rowsWithHooks{@@ -120,10 +183,15 @@ func (p *provider) QueryRow(ctx context.Context, query string, args ...interfacectx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)row := p.clickHouseConn.QueryRow(ctx, query, args...)+ if row == nil {+ telemetrystore.WrapAfterQuery(p.hooks, ctx, event)+ return nil+ }+event.Err = row.Err()telemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return row+ return &rowWithCastError{Row: row}}func (p *provider) Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error {@@ -135,7 +203,7 @@ func (p *provider) Select(ctx context.Context, dest interface{}, query string, aevent.Err = errtelemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return err+ return castError(err)}func (p *provider) Exec(ctx context.Context, query string, args ...interface{}) error {@@ -147,20 +215,19 @@ func (p *provider) Exec(ctx context.Context, query string, args ...interface{})event.Err = errtelemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return err+ return castError(err)}func (p *provider) AsyncInsert(ctx context.Context, query string, wait bool, args ...interface{}) error {event := telemetrystore.NewQueryEvent(query, args)ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)- // TODO: migrate to WithAsync() — https://github.com/SigNoz/engineering-pod/issues/5093- err := p.clickHouseConn.AsyncInsert(ctx, query, wait, args...) //nolint:staticcheck+ err := p.clickHouseConn.Exec(clickhouse.Context(ctx, clickhouse.WithAsync(wait)), query, args...)event.Err = errtelemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return err+ return castError(err)}func (p *provider) PrepareBatch(ctx context.Context, query string, opts ...driver.PrepareBatchOption) (driver.Batch, error) {@@ -172,7 +239,10 @@ func (p *provider) PrepareBatch(ctx context.Context, query string, opts ...driveevent.Err = errtelemetrystore.WrapAfterQuery(p.hooks, ctx, event)- return batch, err+ if batch == nil {+ return nil, castError(err)+ }+ return &batchWithCastError{Batch: batch}, castError(err)}func (p *provider) ServerVersion() (*driver.ServerVersion, error) {@@ -182,3 +252,27 @@ func (p *provider) ServerVersion() (*driver.ServerVersion, error) {func (p *provider) Contributors() []string {return p.clickHouseConn.Contributors()}++func castError(err error) error {+ if err == nil {+ return nil+ }++ if errors.Is(err, context.Canceled) {+ return errors.WrapCanceledf(err, ErrCodeQueryCanceled, "query canceled")+ }+ if errors.Is(err, context.DeadlineExceeded) {+ return errors.WrapTimeoutf(err, ErrCodeQueryTimeout, "query timed out")+ }++ var ex *clickhouse.Exception+ if !errors.As(err, &ex) {+ return err+ }++ if wrap, ok := clickHouseExceptionWrappers[chproto.Error(ex.Code)]; ok {+ return wrap(err, ex)+ }++ return err+}diff --git a/pkg/telemetrystore/clickhousetelemetrystore/rows.go b/pkg/telemetrystore/clickhousetelemetrystore/rows.goindex 3be2965f1f..8c8292c808 100644--- a/pkg/telemetrystore/clickhousetelemetrystore/rows.go+++ b/pkg/telemetrystore/clickhousetelemetrystore/rows.go@@ -25,13 +25,95 @@ func (r *rowsWithHooks) Close() error {// mark as closed and run the onClose hookr.closed = true- if err := r.Err(); err != nil {+ if err := castError(r.Rows.Err()); err != nil {r.event.Err = err}- closeErr := r.Rows.Close()+ closeErr := castError(r.Rows.Close())if closeErr != nil {r.event.Err = closeErr}r.onClose()return closeErr}++func (r *rowsWithHooks) Err() error {+ return castError(r.Rows.Err())+}++func (r *rowsWithHooks) Scan(dest ...any) error {+ return castError(r.Rows.Scan(dest...))+}++func (r *rowsWithHooks) ScanStruct(dest any) error {+ return castError(r.Rows.ScanStruct(dest))+}++func (r *rowsWithHooks) Totals(dest ...any) error {+ return castError(r.Rows.Totals(dest...))+}++// rowWithCastError wraps driver.Row so errors surfaced by Err/Scan/ScanStruct+// are normalized through castError, matching the rest of the provider's API.+type rowWithCastError struct {+ driver.Row+}++func (r *rowWithCastError) Err() error {+ return castError(r.Row.Err())+}++func (r *rowWithCastError) Scan(dest ...any) error {+ return castError(r.Row.Scan(dest...))+}++func (r *rowWithCastError) ScanStruct(dest any) error {+ return castError(r.Row.ScanStruct(dest))+}++// batchWithCastError wraps driver.Batch so error-returning methods (Append,+// Send, Close, etc.) are normalized through castError.+type batchWithCastError struct {+ driver.Batch+}++func (b *batchWithCastError) Abort() error {+ return castError(b.Batch.Abort())+}++func (b *batchWithCastError) Append(v ...any) error {+ return castError(b.Batch.Append(v...))+}++func (b *batchWithCastError) AppendStruct(v any) error {+ return castError(b.Batch.AppendStruct(v))+}++func (b *batchWithCastError) Flush() error {+ return castError(b.Batch.Flush())+}++func (b *batchWithCastError) Send() error {+ return castError(b.Batch.Send())+}++func (b *batchWithCastError) Close() error {+ return castError(b.Batch.Close())+}++func (b *batchWithCastError) Column(i int) driver.BatchColumn {+ return &batchColumnWithCastError{BatchColumn: b.Batch.Column(i)}+}++// batchColumnWithCastError wraps driver.BatchColumn so column-level appends+// also flow through castError.+type batchColumnWithCastError struct {+ driver.BatchColumn+}++func (c *batchColumnWithCastError) Append(v any) error {+ return castError(c.BatchColumn.Append(v))+}++func (c *batchColumnWithCastError) AppendRow(v any) error {+ return castError(c.BatchColumn.AppendRow(v))+}diff --git a/pkg/telemetrytraces/field_mapper.go b/pkg/telemetrytraces/field_mapper.goindex a97770bdb9..75c802165c 100644--- a/pkg/telemetrytraces/field_mapper.go+++ b/pkg/telemetrytraces/field_mapper.go@@ -368,7 +368,7 @@ func (m *defaultFieldMapper) ColumnExpressionFor(// - it is not a static field// - the next best thing to do is see if there is a typo// and suggest a correction- wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field.Name, maps.Keys(keys))...)+ wrappedErr := errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "field `%s` not found", field.Name).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field.Name, errors.NounKeys, maps.Keys(keys))...)return "", wrappedErr}} else if len(keysForField) == 1 {diff --git a/pkg/types/cloudintegrationtypes/serviceid.go b/pkg/types/cloudintegrationtypes/serviceid.goindex 82a7ee14b4..d9fbc94bf7 100644--- a/pkg/types/cloudintegrationtypes/serviceid.go+++ b/pkg/types/cloudintegrationtypes/serviceid.go@@ -123,5 +123,5 @@ func NewServiceID(provider CloudProviderType, service string) (ServiceID, error)return ServiceID{}, errors.NewInvalidInputf(ErrCodeInvalidServiceID,"invalid service id %q for %s cloud provider", service, provider.StringValue()).- WithSuggestions(errors.SuggestionsOnLevenshteinDistance(service, validServices)...)+ WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(service, errors.NounServices, validServices)...)}diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/req.go b/pkg/types/querybuildertypes/querybuildertypesv5/req.goindex 01826cf1da..850ec9c3fd 100644--- a/pkg/types/querybuildertypes/querybuildertypesv5/req.go+++ b/pkg/types/querybuildertypes/querybuildertypesv5/req.go@@ -8,6 +8,7 @@ import ("github.com/SigNoz/govaluate""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/http/binding"+ signozjsonschema "github.com/SigNoz/signoz/pkg/jsonschema""github.com/SigNoz/signoz/pkg/types/metrictypes""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer"@@ -194,7 +195,7 @@ func (q *QueryEnvelope) UnmarshalJSON(data []byte) error {shadow.Type,).WithAdditional("Valid query types are: builder_query, builder_sub_query, builder_formula, builder_join, builder_trace_operator, promql, clickhouse_sql",- ).WithSuggestions(errors.ValidReferences(QueryType{}.Enum()...))+ ).WithSuggestions(errors.NewValidReferences(errors.NounQueryTypes, QueryType{}.Enum()...))}return nil@@ -238,7 +239,7 @@ func UnmarshalBuilderQueryBySignal(data []byte) (any, error) {errors.CodeInvalidInput,"invalid signal %q",header.Signal.StringValue(),- ).WithSuggestions(errors.ValidReferences(telemetrytypes.Signal{}.Enum()...))+ ).WithSuggestions(errors.NewValidReferences(errors.NounSignals, telemetrytypes.Signal{}.Enum()...))}}@@ -271,7 +272,7 @@ func (c *CompositeQuery) UnmarshalJSON(data []byte) error {// Valid field names are derived from the struct itself so this stays in// sync with the schema (and the generated OpenAPI spec) automatically.- fieldNames := binding.JSONFieldNames((*CompositeQuery)(nil))+ fieldNames := signozjsonschema.JSONFieldNames((*CompositeQuery)(nil))validFields := make(map[string]bool, len(fieldNames))for _, f := range fieldNames {validFields[f] = true@@ -285,7 +286,7 @@ func (c *CompositeQuery) UnmarshalJSON(data []byte) error {field,).WithAdditional("Valid fields are: " + strings.Join(fieldNames, ", "),- ).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field, fieldNames)...)+ ).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field, errors.NounFields, fieldNames)...)return unknownFieldErr}}@@ -632,7 +633,7 @@ func (r *QueryRangeRequest) UnmarshalJSON(data []byte) error {// Valid field names are derived from the struct itself so this stays in// sync with the schema (and the generated OpenAPI spec) automatically.- fieldNames := binding.JSONFieldNames((*QueryRangeRequest)(nil))+ fieldNames := signozjsonschema.JSONFieldNames((*QueryRangeRequest)(nil))validFields := make(map[string]bool, len(fieldNames))for _, f := range fieldNames {validFields[f] = true@@ -646,7 +647,7 @@ func (r *QueryRangeRequest) UnmarshalJSON(data []byte) error {field,).WithAdditional("Valid fields are: " + strings.Join(fieldNames, ", "),- ).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(field, fieldNames)...)+ ).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(field, errors.NounFields, fieldNames)...)return unknownFieldErr}}diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/validation.go b/pkg/types/querybuildertypes/querybuildertypesv5/validation.goindex 419231990d..23f4045338 100644--- a/pkg/types/querybuildertypes/querybuildertypesv5/validation.go+++ b/pkg/types/querybuildertypes/querybuildertypesv5/validation.go@@ -518,7 +518,7 @@ func (q *QueryBuilderQuery[T]) validateOrderByForAggregation() error {orderId,).WithAdditional(fmt.Sprintf("For aggregation queries, order by can only reference group by keys, aggregation aliases/expressions, or aggregation indices. Valid keys are: %s", strings.Join(validKeys, ", ")),- ).WithSuggestions(errors.SuggestionsOnLevenshteinDistance(orderKey, validKeys)...)+ ).WithSuggestions(errors.NewSuggestionsOnLevenshteinDistance(orderKey, errors.NounKeys, validKeys)...)}}@@ -712,7 +712,7 @@ func validateQueryEnvelope(envelope QueryEnvelope, opts ...ValidationOption) errenvelope.Type,).WithAdditional("Valid query types are: builder_query, builder_sub_query, builder_formula, builder_join, promql, clickhouse_sql, trace_operator",- ).WithSuggestions(errors.ValidReferences(QueryType{}.Enum()...))+ ).WithSuggestions(errors.NewValidReferences(errors.NounQueryTypes, QueryType{}.Enum()...))}}