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
feat(rulestatehistory): populate related logs/traces links in v2 history APIs (#12211)
Srikanth Chekuri08715a704aff
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex e0806fda6a..148a4f1771 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -7238,6 +7238,10 @@ components:$ref: '#/components/schemas/RuletypesAlertState'overallStateChanged:type: boolean+ relatedLogsLink:+ type: string+ relatedTracesLink:+ type: stringruleId:type: stringruleName:diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex fd47d51964..f19442c159 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -8320,6 +8320,14 @@ export interface RulestatehistorytypesGettableRuleStateHistoryDTO {* @type boolean*/overallStateChanged: boolean;+ /**+ * @type string+ */+ relatedLogsLink?: string;+ /**+ * @type string+ */+ relatedTracesLink?: string;/*** @type string*/diff --git a/pkg/contextlinks/links.go b/pkg/contextlinks/links.goindex 2330978c78..195106e6f7 100644--- a/pkg/contextlinks/links.go+++ b/pkg/contextlinks/links.go@@ -2,329 +2,82 @@ package contextlinksimport ("encoding/json"- "fmt""net/url""strconv""time"- tracesV3 "github.com/SigNoz/signoz/pkg/query-service/app/traces/v3"- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/query-service/utils"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes")-func PrepareLinksToTraces(start, end time.Time, filterItems []v3.FilterItem) string {-- // Traces list view expects time in nanoseconds- tr := URLShareableTimeRange{- Start: start.UnixNano(),- End: end.UnixNano(),- PageSize: 100,- }-- options := URLShareableOptions{- MaxLines: 2,- Format: "list",- SelectColumns: tracesV3.TracesListViewDefaultSelectedColumns,- }-- period, _ := json.Marshal(tr)- urlEncodedTimeRange := url.QueryEscape(string(period))-- builderQuery := v3.BuilderQuery{- DataSource: v3.DataSourceTraces,- QueryName: "A",- AggregateOperator: v3.AggregateOperatorNoOp,- AggregateAttribute: v3.AttributeKey{},- Filters: &v3.FilterSet{- Items: filterItems,- Operator: "AND",- },- Expression: "A",- Disabled: false,- Having: []v3.Having{},- StepInterval: 60,- OrderBy: []v3.OrderBy{- {- ColumnName: "timestamp",- Order: "desc",- },- },- }-- urlData := URLShareableCompositeQuery{- QueryType: string(v3.QueryTypeBuilder),- Builder: URLShareableBuilderQuery{- QueryData: []LinkQuery{- {BuilderQuery: builderQuery},- },- QueryFormulas: make([]string, 0),- },- }-- data, _ := json.Marshal(urlData)- compositeQuery := url.QueryEscape(url.QueryEscape(string(data)))-- optionsData, _ := json.Marshal(options)- urlEncodedOptions := url.QueryEscape(string(optionsData))-- return fmt.Sprintf("compositeQuery=%s&timeRange=%s&startTime=%d&endTime=%d&options=%s", compositeQuery, urlEncodedTimeRange, tr.Start, tr.End, urlEncodedOptions)-}--func PrepareLinksToLogs(start, end time.Time, filterItems []v3.FilterItem) string {-- // Logs list view expects time in milliseconds- tr := URLShareableTimeRange{- Start: start.UnixMilli(),- End: end.UnixMilli(),- PageSize: 100,- }-- options := URLShareableOptions{- MaxLines: 2,- Format: "list",- SelectColumns: []v3.AttributeKey{},- }-- period, _ := json.Marshal(tr)- urlEncodedTimeRange := url.QueryEscape(string(period))-- builderQuery := v3.BuilderQuery{- DataSource: v3.DataSourceLogs,- QueryName: "A",- AggregateOperator: v3.AggregateOperatorNoOp,- AggregateAttribute: v3.AttributeKey{},- Filters: &v3.FilterSet{- Items: filterItems,- Operator: "AND",- },- Expression: "A",- Disabled: false,- Having: []v3.Having{},- StepInterval: 60,- OrderBy: []v3.OrderBy{- {- ColumnName: "timestamp",- Order: "desc",- },- },- }-- urlData := URLShareableCompositeQuery{- QueryType: string(v3.QueryTypeBuilder),- Builder: URLShareableBuilderQuery{- QueryData: []LinkQuery{- {BuilderQuery: builderQuery},- },- QueryFormulas: make([]string, 0),- },- }-- data, _ := json.Marshal(urlData)- compositeQuery := url.QueryEscape(url.QueryEscape(string(data)))-- optionsData, _ := json.Marshal(options)- urlEncodedOptions := url.QueryEscape(string(optionsData))-- return fmt.Sprintf("compositeQuery=%s&timeRange=%s&startTime=%d&endTime=%d&options=%s", compositeQuery, urlEncodedTimeRange, tr.Start, tr.End, urlEncodedOptions)+// PrepareParamsForTracesV5 returns the traces explorer query params for the+// given range and filter; the traces explorer writes its time params in+// nanoseconds.+func PrepareParamsForTracesV5(start, end time.Time, whereClause string) url.Values {+ return prepareExplorerParams("traces", start.UnixNano(), end.UnixNano(), whereClause)}-// The following function is used to prepare the where clause for the query-// `lbls` contains the key value pairs of the labels from the result of the query-// We iterate over the where clause and replace the labels with the actual values-// There are two cases:-// 1. The label is present in the where clause-// 2. The label is not present in the where clause-//-// Example for case 2:-// Latency by serviceName without any filter-// In this case, for each service with latency > threshold we send a notification-// The expectation will be that clicking on the related traces for service A, will-// take us to the traces page with the filter serviceName=A-// So for all the missing labels in the where clause, we add them as key = value-//-// Example for case 1:-// Severity text IN (WARN, ERROR)-// In this case, the Severity text will appear in the `lbls` if it were part of the group-// by clause, in which case we replace it with the actual value for the notification-// i.e Severity text = WARN-// If the Severity text is not part of the group by clause, then we add it as it is.-func PrepareFilters(labels map[string]string, whereClauseItems []v3.FilterItem, groupByItems []v3.AttributeKey, keys map[string]v3.AttributeKey) []v3.FilterItem {- filterItems := make([]v3.FilterItem, 0)-- //delete predefined alert labels- for _, label := range PredefinedAlertLabels {- delete(labels, label)- }-- added := make(map[string]struct{})-- for _, item := range whereClauseItems {- exists := false- for key, value := range labels {- if item.Key.Key == key {- // if the label is present in the where clause, replace it with key = value- filterItems = append(filterItems, v3.FilterItem{- Key: item.Key,- Operator: v3.FilterOperatorEqual,- Value: value,- })- exists = true- added[key] = struct{}{}- break- }- }-- if !exists {- // if there is no label for the filter item, add it as it is- filterItems = append(filterItems, item)- }- }-- // if there are labels which are not part of the where clause, but- // exist in the result, then they could be part of the group by clause- for key, value := range labels {- if _, ok := added[key]; !ok {- // start by taking the attribute key from the keys map, if not present, create a new one- var attributeKey v3.AttributeKey- var attrFound bool-- // as of now this logic will only apply for logs- for _, tKey := range utils.GenerateEnrichmentKeys(v3.AttributeKey{Key: key}) {- if val, ok := keys[tKey]; ok {- attributeKey = val- attrFound = true- break- }- }-- // check if the attribute key is directly present, as of now this will always be false for logs- // as for logs it will be satisfied in the condition above- if !attrFound {- attributeKey, attrFound = keys[key]- }-- // if the attribute key is not present, create a new one- if !attrFound {- attributeKey = v3.AttributeKey{Key: key}- }-- // if there is a group by item with the same key, use that instead- for _, groupByItem := range groupByItems {- if groupByItem.Key == key {- attributeKey = groupByItem- break- }- }-- filterItems = append(filterItems, v3.FilterItem{- Key: attributeKey,- Operator: v3.FilterOperatorEqual,- Value: value,- })- }- }-- return filterItems+// PrepareParamsForLogsV5 returns the logs explorer query params for the given+// range and filter; the logs explorer writes its time params in milliseconds.+func PrepareParamsForLogsV5(start, end time.Time, whereClause string) url.Values {+ return prepareExplorerParams("logs", start.UnixMilli(), end.UnixMilli(), whereClause)}-func PrepareParamsForTracesV5(start, end time.Time, whereClause string) url.Values {-- // Traces list view expects time in nanoseconds- tr := URLShareableTimeRange{- Start: start.UnixNano(),- End: end.UnixNano(),- PageSize: 100,- }-- options := URLShareableOptions{}-- period, _ := json.Marshal(tr)-- linkQuery := LinkQuery{- BuilderQuery: v3.BuilderQuery{- DataSource: v3.DataSourceTraces,- QueryName: "A",- AggregateOperator: v3.AggregateOperatorNoOp,- AggregateAttribute: v3.AttributeKey{},- Expression: "A",- Disabled: false,- Having: []v3.Having{},- StepInterval: 60,- },- Filter: &FilterExpression{Expression: whereClause},- }-+// The end link is double encoded because otherwise a filter expression with `%` somewhere in it breaks.+func prepareExplorerParams(dataSource string, start, end int64, whereClause string) url.Values {urlData := URLShareableCompositeQuery{- QueryType: string(v3.QueryTypeBuilder),+ QueryType: "builder",Builder: URLShareableBuilderQuery{- QueryData: []LinkQuery{- linkQuery,- },+ QueryData: []LinkQuery{{+ DataSource: dataSource,+ Filter: &FilterExpression{Expression: whereClause},+ }},QueryFormulas: make([]string, 0),},}data, _ := json.Marshal(urlData)- compositeQuery := url.QueryEscape(string(data))-- optionsData, _ := json.Marshal(options)params := url.Values{}- params.Set("compositeQuery", compositeQuery)- params.Set("timeRange", string(period))- params.Set("startTime", strconv.FormatInt(tr.Start, 10))- params.Set("endTime", strconv.FormatInt(tr.End, 10))- params.Set("options", string(optionsData))+ params.Set("compositeQuery", url.QueryEscape(string(data)))+ params.Set("startTime", strconv.FormatInt(start, 10))+ params.Set("endTime", strconv.FormatInt(end, 10))return params}-func PrepareParamsForLogsV5(start, end time.Time, whereClause string) url.Values {+// BuilderQueryForSignal returns the filter expression and group-by keys of the+// builder query for the given signal, or found=false when the composite query+// has no builder query for it (e.g. PromQL or ClickHouse SQL alerts).+// TODO(srikanthccv): re-visit this and support multiple queries.+func BuilderQueryForSignal(queries []qbtypes.QueryEnvelope, signal telemetrytypes.Signal) (string, []qbtypes.GroupByKey, bool) {+ switch signal {+ case telemetrytypes.SignalLogs:+ return builderQueryForSignal[qbtypes.LogAggregation](queries, signal)+ case telemetrytypes.SignalTraces:+ return builderQueryForSignal[qbtypes.TraceAggregation](queries, signal)+ }+ return "", nil, false+}- // Logs list view expects time in milliseconds- tr := URLShareableTimeRange{- Start: start.UnixMilli(),- End: end.UnixMilli(),- PageSize: 100,+func builderQueryForSignal[T any](queries []qbtypes.QueryEnvelope, signal telemetrytypes.Signal) (string, []qbtypes.GroupByKey, bool) {+ var q qbtypes.QueryBuilderQuery[T]+ found := false+ for _, query := range queries {+ if query.Type != qbtypes.QueryTypeBuilder {+ continue+ }+ if spec, ok := query.Spec.(qbtypes.QueryBuilderQuery[T]); ok {+ q = spec+ found = true+ }}-- options := URLShareableOptions{}-- period, _ := json.Marshal(tr)-- linkQuery := LinkQuery{- BuilderQuery: v3.BuilderQuery{- DataSource: v3.DataSourceLogs,- QueryName: "A",- AggregateOperator: v3.AggregateOperatorNoOp,- AggregateAttribute: v3.AttributeKey{},- Expression: "A",- Disabled: false,- Having: []v3.Having{},- StepInterval: 60,- },- Filter: &FilterExpression{Expression: whereClause},+ if !found || q.Signal != signal {+ return "", nil, false}- urlData := URLShareableCompositeQuery{- QueryType: string(v3.QueryTypeBuilder),- Builder: URLShareableBuilderQuery{- QueryData: []LinkQuery{- linkQuery,- },- QueryFormulas: make([]string, 0),- },+ filterExpr := ""+ if q.Filter != nil {+ filterExpr = q.Filter.Expression}-- data, _ := json.Marshal(urlData)- compositeQuery := url.QueryEscape(string(data))-- optionsData, _ := json.Marshal(options)-- params := url.Values{}- params.Set("compositeQuery", compositeQuery)- params.Set("timeRange", string(period))- params.Set("startTime", strconv.FormatInt(tr.Start, 10))- params.Set("endTime", strconv.FormatInt(tr.End, 10))- params.Set("options", string(optionsData))- return params+ return filterExpr, q.GroupBy, true}diff --git a/pkg/contextlinks/links_test.go b/pkg/contextlinks/links_test.gonew file mode 100644index 0000000000..bb8d10d98d--- /dev/null+++ b/pkg/contextlinks/links_test.go@@ -0,0 +1,63 @@+package contextlinks++import (+ "testing"++ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestBuilderQueryForSignal(t *testing.T) {+ logQuery := qbtypes.QueryEnvelope{+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{+ Name: "A",+ Signal: telemetrytypes.SignalLogs,+ Filter: &qbtypes.Filter{Expression: "severity_text = 'ERROR'"},+ GroupBy: []qbtypes.GroupByKey{{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}}},+ },+ }+ traceQuery := qbtypes.QueryEnvelope{+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{+ Name: "B",+ Signal: telemetrytypes.SignalTraces,+ },+ }+ promQuery := qbtypes.QueryEnvelope{+ Type: qbtypes.QueryTypePromQL,+ Spec: qbtypes.PromQuery{Name: "C"},+ }++ t.Run("logs query among mixed queries", func(t *testing.T) {+ filterExpr, groupBy, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{promQuery, logQuery, traceQuery}, telemetrytypes.SignalLogs)+ require.True(t, found)+ assert.Equal(t, "severity_text = 'ERROR'", filterExpr)+ require.Len(t, groupBy, 1)+ assert.Equal(t, "service.name", groupBy[0].Name)+ })++ t.Run("traces query without filter", func(t *testing.T) {+ filterExpr, groupBy, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{logQuery, traceQuery}, telemetrytypes.SignalTraces)+ require.True(t, found)+ assert.Empty(t, filterExpr)+ assert.Empty(t, groupBy)+ })++ t.Run("no builder query for signal", func(t *testing.T) {+ _, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{traceQuery}, telemetrytypes.SignalLogs)+ assert.False(t, found)+ })++ t.Run("no builder queries at all", func(t *testing.T) {+ _, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{promQuery}, telemetrytypes.SignalLogs)+ assert.False(t, found)+ })++ t.Run("unsupported signal", func(t *testing.T) {+ _, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{logQuery}, telemetrytypes.SignalMetrics)+ assert.False(t, found)+ })+}diff --git a/pkg/contextlinks/types.go b/pkg/contextlinks/types.goindex 323fabf086..b0a8af60bb 100644--- a/pkg/contextlinks/types.go+++ b/pkg/contextlinks/types.go@@ -1,29 +1,20 @@package contextlinksimport (- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3""github.com/SigNoz/signoz/pkg/types/ruletypes")// TODO(srikanthccv): Fix the URL management.-type URLShareableTimeRange struct {- Start int64 `json:"start"`- End int64 `json:"end"`- PageSize int64 `json:"pageSize"`-}type FilterExpression struct {Expression string `json:"expression,omitempty"`}-type Aggregation struct {- Expression string `json:"expression,omitempty"`-}-+// LinkQuery carries the only fields the explorer pages read from a shared+// link; the frontend fills in the rest of the query shape with defaults.type LinkQuery struct {- v3.BuilderQuery- Filter *FilterExpression `json:"filter,omitempty"`- Aggregations []*Aggregation `json:"aggregations,omitempty"`+ DataSource string `json:"dataSource"`+ Filter *FilterExpression `json:"filter,omitempty"`}type URLShareableBuilderQuery struct {@@ -36,10 +27,4 @@ type URLShareableCompositeQuery struct {Builder URLShareableBuilderQuery `json:"builder"`}-type URLShareableOptions struct {- MaxLines int `json:"maxLines"`- Format string `json:"format"`- SelectColumns []v3.AttributeKey `json:"selectColumns"`-}-var PredefinedAlertLabels = []string{ruletypes.LabelThresholdName, ruletypes.LabelSeverityName, ruletypes.LabelLastSeen}diff --git a/pkg/modules/rulestatehistory/implrulestatehistory/handler.go b/pkg/modules/rulestatehistory/implrulestatehistory/handler.goindex 9ae24ee0eb..704641a556 100644--- a/pkg/modules/rulestatehistory/implrulestatehistory/handler.go+++ b/pkg/modules/rulestatehistory/implrulestatehistory/handler.go@@ -113,6 +113,8 @@ func (h *handler) GetRuleHistoryTimeline(w http.ResponseWriter, r *http.Request)Labels: item.Labels.ToQBLabels(),Fingerprint: item.Fingerprint,Value: item.Value,+ RelatedTracesLink: item.RelatedTracesLink,+ RelatedLogsLink: item.RelatedLogsLink,})}resp.Total = timelineTotaldiff --git a/pkg/modules/rulestatehistory/implrulestatehistory/links.go b/pkg/modules/rulestatehistory/implrulestatehistory/links.gonew file mode 100644index 0000000000..5c0c9f126e--- /dev/null+++ b/pkg/modules/rulestatehistory/implrulestatehistory/links.go@@ -0,0 +1,104 @@+package implrulestatehistory++import (+ "context"+ "encoding/json"+ "time"++ "github.com/SigNoz/signoz/pkg/contextlinks"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/rulestatehistorytypes"+ "github.com/SigNoz/signoz/pkg/types/ruletypes"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/SigNoz/signoz/pkg/valuer"+)++// relatedLinkBuilder builds logs/traces explorer links that carry the rule's+// filter and the entry's labels, so a history entry can be opened in the+// explorer with the context that produced it.+type relatedLinkBuilder struct {+ alertType ruletypes.AlertType+ evaluation ruletypes.Evaluation+ filterExpr string+ groupBy []qbtypes.GroupByKey+}++// relatedLinkBuilderForRule returns nil when the rule cannot be loaded or is+// not a logs/traces rule; callers then leave the links empty.+func (m *module) relatedLinkBuilderForRule(ctx context.Context, orgID valuer.UUID, ruleID string) *relatedLinkBuilder {+ id, err := valuer.NewUUID(ruleID)+ if err != nil {+ return nil+ }++ storableRule, err := m.ruleStore.GetStoredRule(ctx, orgID, id)+ if err != nil {+ return nil+ }++ rule := ruletypes.PostableRule{}+ if err := json.Unmarshal([]byte(storableRule.Data), &rule); err != nil {+ return nil+ }++ if rule.AlertType != ruletypes.AlertTypeLogs && rule.AlertType != ruletypes.AlertTypeTraces {+ return nil+ }+ if rule.RuleCondition == nil || rule.RuleCondition.CompositeQuery == nil {+ return nil+ }++ builder := &relatedLinkBuilder{alertType: rule.AlertType}+ if rule.Evaluation != nil {+ if evaluation, err := rule.Evaluation.GetEvaluation(); err == nil {+ builder.evaluation = evaluation+ }+ }+ if builder.evaluation == nil {+ evalWindow := rule.EvalWindow+ if evalWindow.IsZero() {+ evalWindow = valuer.MustParseTextDuration("5m")+ }+ builder.evaluation = ruletypes.RollingWindow{EvalWindow: evalWindow}+ }++ signal := telemetrytypes.SignalLogs+ if rule.AlertType == ruletypes.AlertTypeTraces {+ signal = telemetrytypes.SignalTraces+ }+ // links are still built from the labels alone when the rule has no builder+ // query for the signal (e.g. ClickHouse SQL alerts)+ builder.filterExpr, builder.groupBy, _ = contextlinks.BuilderQueryForSignal(rule.RuleCondition.CompositeQuery.Queries, signal)++ return builder+}++// queryWindow returns the range the rule evaluated when it recorded a state+// change at unixMilli.+// why are we subtracting 3 minutes?+// the query range is calculated based on the rule's evaluation window and+// evalDelay; alerts have 2 minutes delay built in, so we need to subtract+// that from the start time to get the correct query range.+func (b *relatedLinkBuilder) queryWindow(unixMilli int64) (time.Time, time.Time) {+ start, end := b.evaluation.NextWindowFor(time.Unix(unixMilli/1000, 0))+ return start.Add(-3 * time.Minute), end+}++// links returns the encoded logs and traces explorer query params for the+// given entry labels and time range; at most one of the two is non-empty.+func (b *relatedLinkBuilder) links(labels rulestatehistorytypes.LabelsString, start, end time.Time) (string, string) {+ lbls := map[string]string{}+ if err := json.Unmarshal([]byte(labels), &lbls); err != nil {+ return "", ""+ }++ whereClause := contextlinks.PrepareFilterExpression(lbls, b.filterExpr, b.groupBy)++ switch b.alertType {+ case ruletypes.AlertTypeLogs:+ return contextlinks.PrepareParamsForLogsV5(start, end, whereClause).Encode(), ""+ case ruletypes.AlertTypeTraces:+ return "", contextlinks.PrepareParamsForTracesV5(start, end, whereClause).Encode()+ }+ return "", ""+}diff --git a/pkg/modules/rulestatehistory/implrulestatehistory/module.go b/pkg/modules/rulestatehistory/implrulestatehistory/module.goindex 588e6e78ec..9a8509bbb6 100644--- a/pkg/modules/rulestatehistory/implrulestatehistory/module.go+++ b/pkg/modules/rulestatehistory/implrulestatehistory/module.go@@ -13,11 +13,12 @@ import ()type module struct {- store rulestatehistorytypes.Store+ store rulestatehistorytypes.Store+ ruleStore ruletypes.RuleStore}-func NewModule(store rulestatehistorytypes.Store) rulestatehistory.Module {- return &module{store: store}+func NewModule(store rulestatehistorytypes.Store, ruleStore ruletypes.RuleStore) rulestatehistory.Module {+ return &module{store: store, ruleStore: ruleStore}}func (m *module) GetLastSavedRuleStateHistory(ctx context.Context, ruleID string) ([]rulestatehistorytypes.RuleStateHistory, error) {@@ -25,7 +26,19 @@ func (m *module) GetLastSavedRuleStateHistory(ctx context.Context, ruleID string}func (m *module) GetHistoryTimeline(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistory, uint64, error) {- return m.store.ReadRuleStateHistoryByRuleID(ctx, orgID, ruleID, &query)+ items, total, err := m.store.ReadRuleStateHistoryByRuleID(ctx, orgID, ruleID, &query)+ if err != nil {+ return nil, 0, err+ }++ if builder := m.relatedLinkBuilderForRule(ctx, orgID, ruleID); builder != nil {+ for idx := range items {+ start, end := builder.queryWindow(items[idx].UnixMilli)+ items[idx].RelatedLogsLink, items[idx].RelatedTracesLink = builder.links(items[idx].Labels, start, end)+ }+ }++ return items, total, nil}func (m *module) GetHistoryFilterKeys(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query, search string, limit int64) (*telemetrytypes.GettableFieldKeys, error) {@@ -37,7 +50,21 @@ func (m *module) GetHistoryFilterValues(ctx context.Context, orgID valuer.UUID,}func (m *module) GetHistoryContributors(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistoryContributor, error) {- return m.store.ReadRuleStateHistoryTopContributorsByRuleID(ctx, orgID, ruleID, &query)+ contributors, err := m.store.ReadRuleStateHistoryTopContributorsByRuleID(ctx, orgID, ruleID, &query)+ if err != nil {+ return nil, err+ }++ if builder := m.relatedLinkBuilderForRule(ctx, orgID, ruleID); builder != nil {+ // contributor counts aggregate the whole selected range, so the links+ // span it too instead of a single evaluation window+ start, end := time.UnixMilli(query.Start), time.UnixMilli(query.End)+ for idx := range contributors {+ contributors[idx].RelatedLogsLink, contributors[idx].RelatedTracesLink = builder.links(contributors[idx].Labels, start, end)+ }+ }++ return contributors, nil}func (m *module) GetHistoryOverallStatus(ctx context.Context, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.GettableRuleStateWindow, error) {diff --git a/pkg/modules/rulestatehistory/rulestatehistory.go b/pkg/modules/rulestatehistory/rulestatehistory.goindex 9d8cc61f3d..412c546c0c 100644--- a/pkg/modules/rulestatehistory/rulestatehistory.go+++ b/pkg/modules/rulestatehistory/rulestatehistory.go@@ -23,7 +23,8 @@ type Module interface {GetHistoryStats(context.Context, string, rulestatehistorytypes.Query) (rulestatehistorytypes.GettableRuleStateHistoryStats, error)// GetHistoryTimeline returns a time-ordered list of rule state history entries and a total count- // for the given query, suitable for paginated timeline views.+ // for the given query, suitable for paginated timeline views. For logs/traces rules, each entry+ // carries a related logs/traces explorer link scoped to the entry's labels and evaluation window.GetHistoryTimeline(context.Context, valuer.UUID, string, rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistory, uint64, error)// GetHistoryFilterKeys returns the available filter keys for rule state history queries.@@ -33,6 +34,8 @@ type Module interface {GetHistoryFilterValues(context.Context, valuer.UUID, string, string, rulestatehistorytypes.Query, string, int64) (*telemetrytypes.GettableFieldValues, error)// GetHistoryContributors returns the top contributors to trigger alert, for the given query.+ // For logs/traces rules, each contributor carries a related logs/traces explorer link scoped+ // to the contributor's labels and the queried range.GetHistoryContributors(context.Context, valuer.UUID, string, rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistoryContributor, error)// GetHistoryOverallStatus returns the overall status windows for rule state history,diff --git a/pkg/query-service/rules/threshold_rule.go b/pkg/query-service/rules/threshold_rule.goindex c981bd0987..4930e8523c 100644--- a/pkg/query-service/rules/threshold_rule.go+++ b/pkg/query-service/rules/threshold_rule.go@@ -100,27 +100,12 @@ func (r *ThresholdRule) prepareParamsForLogs(ctx context.Context, ts time.Time,return nil}- var q qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]-- for _, query := range r.ruleCondition.CompositeQuery.Queries {- if query.Type == qbtypes.QueryTypeBuilder {- switch spec := query.Spec.(type) {- case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:- q = spec- }- }- }-- if q.Signal != telemetrytypes.SignalLogs {+ filterExpr, groupBy, found := contextlinks.BuilderQueryForSignal(r.ruleCondition.CompositeQuery.Queries, telemetrytypes.SignalLogs)+ if !found {return nil}- filterExpr := ""- if q.Filter != nil && q.Filter.Expression != "" {- filterExpr = q.Filter.Expression- }-- whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, q.GroupBy)+ whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, groupBy)return contextlinks.PrepareParamsForLogsV5(start, end, whereClause)}@@ -140,27 +125,12 @@ func (r *ThresholdRule) prepareParamsForTraces(ctx context.Context, ts time.Timereturn nil}- var q qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]-- for _, query := range r.ruleCondition.CompositeQuery.Queries {- if query.Type == qbtypes.QueryTypeBuilder {- switch spec := query.Spec.(type) {- case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:- q = spec- }- }- }-- if q.Signal != telemetrytypes.SignalTraces {+ filterExpr, groupBy, found := contextlinks.BuilderQueryForSignal(r.ruleCondition.CompositeQuery.Queries, telemetrytypes.SignalTraces)+ if !found {return nil}- filterExpr := ""- if q.Filter != nil && q.Filter.Expression != "" {- filterExpr = q.Filter.Expression- }-- whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, q.GroupBy)+ whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, groupBy)return contextlinks.PrepareParamsForTracesV5(start, end, whereClause)}diff --git a/pkg/query-service/rules/threshold_rule_test.go b/pkg/query-service/rules/threshold_rule_test.goindex 850bd5a205..a190c07877 100644--- a/pkg/query-service/rules/threshold_rule_test.go+++ b/pkg/query-service/rules/threshold_rule_test.go@@ -4,6 +4,7 @@ import ("context""fmt""math"+ "net/url""strings""testing""time"@@ -195,10 +196,16 @@ func TestPrepareParamsForLogs(t *testing.T) {ts := time.UnixMilli(1705469040000)- params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{}).Encode()- assert.Contains(t, params, "&timeRange=%7B%22start%22%3A1705468620000%2C%22end%22%3A1705468920000%2C%22pageSize%22%3A100%7D")- assert.Contains(t, params, "&startTime=1705468620000")- assert.Contains(t, params, "&endTime=1705468920000")+ params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{})+ assert.Equal(t, "1705468620000", params.Get("startTime"))+ assert.Equal(t, "1705468920000", params.Get("endTime"))++ // the frontend decodes compositeQuery twice, so it must be escaped once+ // before being encoded into the params+ assert.Contains(t, params.Encode(), "compositeQuery=%257B")+ compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))+ assert.NoError(t, err)+ assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"logs","filter":{}}],"queryFormulas":[]}}`, compositeQuery)}func TestPrepareParamsForLogsFilterExpression(t *testing.T) {@@ -257,8 +264,13 @@ func TestPrepareParamsForLogsFilterExpression(t *testing.T) {ts := time.UnixMilli(1753527163000)- params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{}).Encode()- assert.Contains(t, params, "compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522queryName%2522%253A%2522A%2522%252C%2522stepInterval%2522%253A60%252C%2522dataSource%2522%253A%2522logs%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522key%2522%253A%2522%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522type%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522limit%2522%253A0%252C%2522offset%2522%253A0%252C%2522pageSize%2522%253A0%252C%2522ShiftBy%2522%253A0%252C%2522IsAnomaly%2522%253Afalse%252C%2522QueriesUsedInFormula%2522%253Anull%252C%2522filter%2522%253A%257B%2522expression%2522%253A%2522service.name%2BEXISTS%2522%257D%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%257D&endTime=1753527000000&options=%7B%22maxLines%22%3A0%2C%22format%22%3A%22%22%2C%22selectColumns%22%3Anull%7D&startTime=1753526700000&timeRange=%7B%22start%22%3A1753526700000%2C%22end%22%3A1753527000000%2C%22pageSize%22%3A100%7D")+ params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{})+ assert.Equal(t, "1753526700000", params.Get("startTime"))+ assert.Equal(t, "1753527000000", params.Get("endTime"))++ compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))+ assert.NoError(t, err)+ assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"logs","filter":{"expression":"service.name EXISTS"}}],"queryFormulas":[]}}`, compositeQuery)}func TestPrepareParamsForTracesFilterExpression(t *testing.T) {@@ -317,8 +329,13 @@ func TestPrepareParamsForTracesFilterExpression(t *testing.T) {ts := time.UnixMilli(1753527163000)- params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{}).Encode()- assert.Contains(t, params, "compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522queryName%2522%253A%2522A%2522%252C%2522stepInterval%2522%253A60%252C%2522dataSource%2522%253A%2522traces%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522key%2522%253A%2522%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522type%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522limit%2522%253A0%252C%2522offset%2522%253A0%252C%2522pageSize%2522%253A0%252C%2522ShiftBy%2522%253A0%252C%2522IsAnomaly%2522%253Afalse%252C%2522QueriesUsedInFormula%2522%253Anull%252C%2522filter%2522%253A%257B%2522expression%2522%253A%2522service.name%2BEXISTS%2522%257D%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%257D&endTime=1753527000000000000&options=%7B%22maxLines%22%3A0%2C%22format%22%3A%22%22%2C%22selectColumns%22%3Anull%7D&startTime=1753526700000000000&timeRange=%7B%22start%22%3A1753526700000000000%2C%22end%22%3A1753527000000000000%2C%22pageSize%22%3A100%7D")+ params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{})+ assert.Equal(t, "1753526700000000000", params.Get("startTime"))+ assert.Equal(t, "1753527000000000000", params.Get("endTime"))++ compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))+ assert.NoError(t, err)+ assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"traces","filter":{"expression":"service.name EXISTS"}}],"queryFormulas":[]}}`, compositeQuery)}func TestPrepareParamsForTraces(t *testing.T) {@@ -375,10 +392,16 @@ func TestPrepareParamsForTraces(t *testing.T) {ts := time.UnixMilli(1705469040000)- params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{}).Encode()- assert.Contains(t, params, "&timeRange=%7B%22start%22%3A1705468620000000000%2C%22end%22%3A1705468920000000000%2C%22pageSize%22%3A100%7D")- assert.Contains(t, params, "&startTime=1705468620000000000")- assert.Contains(t, params, "&endTime=1705468920000000000")+ params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{})+ assert.Equal(t, "1705468620000000000", params.Get("startTime"))+ assert.Equal(t, "1705468920000000000", params.Get("endTime"))++ // the frontend decodes compositeQuery twice, so it must be escaped once+ // before being encoded into the params+ assert.Contains(t, params.Encode(), "compositeQuery=%257B")+ compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))+ assert.NoError(t, err)+ assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"traces","filter":{}}],"queryFormulas":[]}}`, compositeQuery)}func TestThresholdRuleLabelNormalization(t *testing.T) {diff --git a/pkg/signoz/module.go b/pkg/signoz/module.goindex 8efd861936..0ff4a4bf6e 100644--- a/pkg/signoz/module.go+++ b/pkg/signoz/module.go@@ -159,7 +159,7 @@ func NewModules(ServiceAccount: serviceAccount,ServiceAccountGetter: serviceAccountGetter,LogsPipeline: impllogspipeline.NewModule(sqlstore),- RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger)),+ RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger), ruleStore),CloudIntegration: cloudIntegrationModule,TraceDetail: impltracedetail.NewModule(impltracedetail.NewTraceStore(telemetryStore), providerSettings, config.TraceDetail),SpanMapper: implspanmapper.NewModule(implspanmapper.NewStore(sqlstore), fl),diff --git a/pkg/types/rulestatehistorytypes/response.go b/pkg/types/rulestatehistorytypes/response.goindex 89587c1cd3..c0375e9453 100644--- a/pkg/types/rulestatehistorytypes/response.go+++ b/pkg/types/rulestatehistorytypes/response.go@@ -22,6 +22,8 @@ type GettableRuleStateHistory struct {Labels []*qbtypes.Label `json:"labels" required:"true"`Fingerprint uint64 `json:"fingerprint" required:"true"`Value float64 `json:"value" required:"true"`+ RelatedTracesLink string `json:"relatedTracesLink,omitempty"`+ RelatedLogsLink string `json:"relatedLogsLink,omitempty"`}type GettableRuleStateHistoryContributor struct {diff --git a/pkg/types/rulestatehistorytypes/store.go b/pkg/types/rulestatehistorytypes/store.goindex 34f26a2dd0..5255449df8 100644--- a/pkg/types/rulestatehistorytypes/store.go+++ b/pkg/types/rulestatehistorytypes/store.go@@ -76,6 +76,9 @@ type RuleStateHistory struct {Labels LabelsString `ch:"labels"`Fingerprint uint64 `ch:"fingerprint"`Value float64 `ch:"value"`++ RelatedTracesLink string+ RelatedLogsLink string}type RuleStateHistoryContributor struct {diff --git a/tests/fixtures/alerts.py b/tests/fixtures/alerts.pyindex 95dc679b4c..e8ac1c5991 100644--- a/tests/fixtures/alerts.py+++ b/tests/fixtures/alerts.py@@ -1,6 +1,8 @@import base64import jsonimport time+import urllib.parse+import uuidfrom collections.abc import Callablefrom datetime import UTC, datetime, timedeltafrom http import HTTPStatus@@ -58,6 +60,97 @@ def create_alert_rule(signoz: types.SigNoz, get_token: Callable[[str, str], str]logger.error("Error deleting rule: %s", {"rule_id": rule_id, "error": e})[email protected](name="create_alert_rule_with_channel", scope="function")+def create_alert_rule_with_channel(+ notification_channel: types.TestContainerDocker,+ create_webhook_notification_channel: Callable[[str, str, dict, bool], str],+ create_alert_rule: Callable[[dict], str],+) -> Callable[[str], str]:+ """Creates the rule from the given testdata path with a throwaway webhook channel."""++ def _create_alert_rule_with_channel(rule_path: str) -> str:+ channel_name = str(uuid.uuid4())+ create_webhook_notification_channel(+ channel_name=channel_name,+ webhook_url=notification_channel.container_configs["8080"].get(f"/alert/{channel_name}"),+ http_config={},+ send_resolved=False,+ )++ with open(get_testdata_file_path(rule_path), encoding="utf-8") as f:+ rule_data = json.loads(f.read())+ update_rule_channel_name(rule_data, channel_name)+ return create_alert_rule(rule_data)++ return _create_alert_rule_with_channel+++def labels_to_map(labels: list[dict]) -> dict[str, str]:+ """Converts the label list shape of the v2 rule history APIs to a plain map."""+ return {label["key"]["name"]: label["value"] for label in labels or []}+++def parse_related_link(link: str) -> dict:+ """Parses the query params of a related logs/traces explorer link."""+ params = urllib.parse.parse_qs(link)+ for key in ("compositeQuery", "startTime", "endTime"):+ assert key in params, f"related link is missing param {key}, link: {link}"+ return {+ "start": int(params["startTime"][0]),+ "end": int(params["endTime"][0]),+ # the compositeQuery value is query-escaped before being encoded into+ # the params, so it needs one more unquote than the other params+ "composite_query": json.loads(urllib.parse.unquote_plus(params["compositeQuery"][0])),+ }+++def assert_related_link_query(link: dict, data_source: str, expression_pieces: list[str]) -> None:+ query_data = link["composite_query"]["builder"]["queryData"]+ assert len(query_data) == 1+ assert query_data[0]["dataSource"] == data_source+ expression = query_data[0]["filter"]["expression"]+ for piece in expression_pieces:+ assert piece in expression, f"expected {piece} in link filter expression: {expression}"+++def wait_for_firing_timeline_entry(signoz: types.SigNoz, token: str, rule_id: str, start_ms: int, wait_seconds: int = 60) -> tuple[dict, int]:+ """Polls the v2 timeline API until the rule records a firing entry.++ Rules in the alert scenarios evaluate every 15s and their data is set up to+ fire on the first evaluation, so the default wait leaves plenty of slack.+ Returns the firing entry and the end of the queried range.+ """+ deadline = time.time() + wait_seconds+ items = []+ while time.time() < deadline:+ end_ms = int(datetime.now(tz=UTC).timestamp() * 1000) + 60_000+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/rules/{rule_id}/history/timeline"),+ params={"start": start_ms, "end": end_ms, "limit": 50, "order": "desc"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, f"Failed to get rule history timeline, api returned {response.status_code} with response: {response.text}"+ items = response.json()["data"]["items"] or []+ firing = [item for item in items if item["state"] == "firing"]+ if len(firing) > 0:+ return (firing[0], end_ms)+ time.sleep(2)++ raise AssertionError(f"No firing entry recorded in rule state history within {wait_seconds}s, items: {items}")+++def get_rule_history_top_contributors(signoz: types.SigNoz, token: str, rule_id: str, start_ms: int, end_ms: int) -> list[dict]:+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/rules/{rule_id}/history/top_contributors"),+ params={"start": start_ms, "end": end_ms},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, f"Failed to get rule history top contributors, api returned {response.status_code} with response: {response.text}"+ return response.json()["data"] or []++@pytest.fixture(name="insert_alert_data", scope="function")def insert_alert_data(insert_metrics: Callable[[list[Metrics]], None],diff --git a/tests/integration/testdata/alerts/test_scenarios/multi_threshold_rule_test/rule.json b/tests/integration/testdata/alerts/test_scenarios/multi_threshold_rule_test/rule.jsonindex b00ed4b78b..713f4fe563 100644--- a/tests/integration/testdata/alerts/test_scenarios/multi_threshold_rule_test/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/multi_threshold_rule_test/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 30,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"]@@ -18,8 +18,8 @@{"name": "warning","target": 20,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"]@@ -27,8 +27,8 @@{"name": "info","target": 10,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/no_data_rule_test/rule.json b/tests/integration/testdata/alerts/test_scenarios/no_data_rule_test/rule.jsonindex bc16f95357..142fef6e8f 100644--- a/tests/integration/testdata/alerts/test_scenarios/no_data_rule_test/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/no_data_rule_test/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/alert_data.jsonl b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/alert_data.jsonlnew file mode 100644index 0000000000..d485962bff--- /dev/null+++ b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/alert_data.jsonl@@ -0,0 +1,8 @@+{ "timestamp": "2026-01-29T10:00:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:00:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:01:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:01:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:02:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:02:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:03:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }+{ "timestamp": "2026-01-29T10:03:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }diff --git a/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/rule.json b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/rule.jsonnew file mode 100644index 0000000000..4ee91f1aaf--- /dev/null+++ b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_logs/rule.json@@ -0,0 +1,73 @@+{+ "alert": "rule_state_history_logs",+ "ruleType": "threshold_rule",+ "alertType": "LOGS_BASED_ALERT",+ "condition": {+ "thresholds": {+ "kind": "basic",+ "spec": [+ {+ "name": "critical",+ "target": 0,+ "matchType": "at_least_once",+ "op": "above",+ "channels": [+ "test channel"+ ]+ }+ ]+ },+ "compositeQuery": {+ "queryType": "builder",+ "panelType": "graph",+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "filter": {+ "expression": "body CONTAINS 'payment success'"+ },+ "groupBy": [+ {+ "name": "service.name",+ "fieldContext": "resource",+ "fieldDataType": "string"+ }+ ],+ "aggregations": [+ {+ "expression": "count()"+ }+ ]+ }+ }+ ]+ },+ "selectedQueryName": "A"+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m0s",+ "frequency": "15s"+ }+ },+ "labels": {},+ "annotations": {+ "description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",+ "summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"+ },+ "notificationSettings": {+ "groupBy": [],+ "usePolicy": false,+ "renotify": {+ "enabled": false,+ "interval": "30m",+ "alertStates": []+ }+ },+ "version": "v5",+ "schemaVersion": "v2alpha1"+}diff --git a/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/alert_data.jsonl b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/alert_data.jsonlnew file mode 100644index 0000000000..062d7c8898--- /dev/null+++ b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/alert_data.jsonl@@ -0,0 +1,8 @@+{ "timestamp": "2026-01-29T10:00:00.000000Z", "duration": "PT0.8S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a1", "span_id": "b1b2c3d4e5f6a7b8", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:00:30.000000Z", "duration": "PT0.9S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a2", "span_id": "b2b3c4d5e6f7a8b9", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:01:00.000000Z", "duration": "PT1.1S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a3", "span_id": "b3b4c5d6e7f8a9b0", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:01:30.000000Z", "duration": "PT0.7S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a4", "span_id": "b4b5c6d7e8f9a0b1", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:02:00.000000Z", "duration": "PT1.3S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a5", "span_id": "b5b6c7d8e9f0a1b2", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:02:30.000000Z", "duration": "PT0.6S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a6", "span_id": "b6b7c8d9e0f1a2b3", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:03:00.000000Z", "duration": "PT1.0S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a7", "span_id": "b7b8c9d0e1f2a3b4", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }+{ "timestamp": "2026-01-29T10:03:30.000000Z", "duration": "PT0.8S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a8", "span_id": "b8b9c0d1e2f3a4b5", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }diff --git a/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/rule.json b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/rule.jsonnew file mode 100644index 0000000000..f2e2427ebc--- /dev/null+++ b/tests/integration/testdata/alerts/test_scenarios/rule_state_history_traces/rule.json@@ -0,0 +1,73 @@+{+ "alert": "rule_state_history_traces",+ "ruleType": "threshold_rule",+ "alertType": "TRACES_BASED_ALERT",+ "condition": {+ "thresholds": {+ "kind": "basic",+ "spec": [+ {+ "name": "critical",+ "target": 0,+ "matchType": "at_least_once",+ "op": "above",+ "channels": [+ "test channel"+ ]+ }+ ]+ },+ "compositeQuery": {+ "queryType": "builder",+ "panelType": "graph",+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "traces",+ "filter": {+ "expression": "http.request.path = '/order'"+ },+ "groupBy": [+ {+ "name": "service.name",+ "fieldContext": "resource",+ "fieldDataType": "string"+ }+ ],+ "aggregations": [+ {+ "expression": "count()"+ }+ ]+ }+ }+ ]+ },+ "selectedQueryName": "A"+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m0s",+ "frequency": "15s"+ }+ },+ "labels": {},+ "annotations": {+ "description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",+ "summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"+ },+ "notificationSettings": {+ "groupBy": [],+ "usePolicy": false,+ "renotify": {+ "enabled": false,+ "interval": "30m",+ "alertStates": []+ }+ },+ "version": "v5",+ "schemaVersion": "v2alpha1"+}diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_above_all_the_time/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_above_all_the_time/rule.jsonindex 7bfcced756..a147f05338 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_above_all_the_time/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_above_all_the_time/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "2",- "op": "1",+ "matchType": "all_the_times",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_above_at_least_once/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_above_at_least_once/rule.jsonindex 51fcd73b29..e4f51b2822 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_above_at_least_once/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_above_at_least_once/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_above_average/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_above_average/rule.jsonindex 1d5e2c8cfb..e87f6552a3 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_above_average/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_above_average/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 1,- "matchType": "3",- "op": "1",+ "matchType": "on_average",+ "op": "above","channels": ["test channel"],diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_above_in_total/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_above_in_total/rule.jsonindex f18531ee1e..d3dc85ab48 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_above_in_total/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_above_in_total/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 5,- "matchType": "4",- "op": "1",+ "matchType": "in_total",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_above_last/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_above_last/rule.jsonindex ed1c380e46..e1395b21c3 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_above_last/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_above_last/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "5",- "op": "1",+ "matchType": "last",+ "op": "above","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_below_all_the_time/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_below_all_the_time/rule.jsonindex 8d88f20ba6..01f62d6c4f 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_below_all_the_time/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_below_all_the_time/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "2",- "op": "2",+ "matchType": "all_the_times",+ "op": "below","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_below_at_least_once/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_below_at_least_once/rule.jsonindex e680451ce6..3ddf37bcc5 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_below_at_least_once/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_below_at_least_once/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "1",- "op": "2",+ "matchType": "at_least_once",+ "op": "below","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_below_average/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_below_average/rule.jsonindex 034369a47f..d375fa971a 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_below_average/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_below_average/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "3",- "op": "2",+ "matchType": "on_average",+ "op": "below","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_below_in_total/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_below_in_total/rule.jsonindex b49471a64f..ea114ce2ad 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_below_in_total/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_below_in_total/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "4",- "op": "2",+ "matchType": "in_total",+ "op": "below","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_below_last/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_below_last/rule.jsonindex fca793af60..5386a3ac5f 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_below_last/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_below_last/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "5",- "op": "2",+ "matchType": "last",+ "op": "below","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_all_the_time/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_all_the_time/rule.jsonindex c85ff57aef..01788ee293 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_all_the_time/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_all_the_time/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "2",- "op": "3",+ "matchType": "all_the_times",+ "op": "equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_at_least_once/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_at_least_once/rule.jsonindex 1388623b1a..c87e709c5e 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_at_least_once/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_at_least_once/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "1",- "op": "3",+ "matchType": "at_least_once",+ "op": "equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_average/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_average/rule.jsonindex 2e7acfc98a..91f2d71ee7 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_average/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_average/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "3",- "op": "3",+ "matchType": "on_average",+ "op": "equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_in_total/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_in_total/rule.jsonindex 3c2fd9795c..b4f3a5d51e 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_in_total/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_in_total/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "4",- "op": "3",+ "matchType": "in_total",+ "op": "equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_last/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_last/rule.jsonindex 404151fd88..6f363319e2 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_last/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_equal_to_last/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "5",- "op": "3",+ "matchType": "last",+ "op": "equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_all_the_time/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_all_the_time/rule.jsonindex 9f890304f8..bf5b866467 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_all_the_time/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_all_the_time/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "2",- "op": "4",+ "matchType": "all_the_times",+ "op": "not_equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_at_least_once/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_at_least_once/rule.jsonindex 09b932d3c0..79fc8dd54b 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_at_least_once/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_at_least_once/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 5,- "matchType": "1",- "op": "4",+ "matchType": "at_least_once",+ "op": "not_equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_average/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_average/rule.jsonindex 7458be4cda..35d92068b9 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_average/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_average/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "3",- "op": "4",+ "matchType": "on_average",+ "op": "not_equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_in_total/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_in_total/rule.jsonindex b689ab7536..de80598a92 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_in_total/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_in_total/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "4",- "op": "4",+ "matchType": "in_total",+ "op": "not_equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_last/rule.json b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_last/rule.jsonindex c497e619dd..2442660beb 100644--- a/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_last/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/threshold_not_equal_to_last/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 10,- "matchType": "5",- "op": "4",+ "matchType": "last",+ "op": "not_equal","channels": ["test channel"]diff --git a/tests/integration/testdata/alerts/test_scenarios/unit_conversion_bytes_to_mb/rule.json b/tests/integration/testdata/alerts/test_scenarios/unit_conversion_bytes_to_mb/rule.jsonindex c53181398a..560f434db8 100644--- a/tests/integration/testdata/alerts/test_scenarios/unit_conversion_bytes_to_mb/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/unit_conversion_bytes_to_mb/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 1.5,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"],diff --git a/tests/integration/testdata/alerts/test_scenarios/unit_conversion_ms_to_second/rule.json b/tests/integration/testdata/alerts/test_scenarios/unit_conversion_ms_to_second/rule.jsonindex be86825047..ed854486e7 100644--- a/tests/integration/testdata/alerts/test_scenarios/unit_conversion_ms_to_second/rule.json+++ b/tests/integration/testdata/alerts/test_scenarios/unit_conversion_ms_to_second/rule.json@@ -9,8 +9,8 @@{"name": "critical","target": 3,- "matchType": "1",- "op": "1",+ "matchType": "at_least_once",+ "op": "above","channels": ["test channel"],diff --git a/tests/integration/tests/alerts/03_rule_state_history.py b/tests/integration/tests/alerts/03_rule_state_history.pynew file mode 100644index 0000000000..a457741827--- /dev/null+++ b/tests/integration/tests/alerts/03_rule_state_history.py@@ -0,0 +1,103 @@+from collections.abc import Callable+from datetime import UTC, datetime, timedelta++from fixtures import types+from fixtures.alerts import (+ assert_related_link_query,+ get_rule_history_top_contributors,+ labels_to_map,+ parse_related_link,+ wait_for_firing_timeline_entry,+)+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.logger import setup_logger++logger = setup_logger(__name__)++# Related links cover [ts - evalWindow - 3m, ts]: the rules use a 5m eval+# window and the backend widens it by 3m for the built-in evaluation delay.+RELATED_LINK_WINDOW_SECONDS = (5 + 3) * 60+++def test_logs_rule_history_related_links(+ signoz: types.SigNoz,+ create_alert_rule_with_channel: Callable[[str], str],+ insert_alert_data: Callable[[list[types.AlertData], datetime], None],+ get_token: Callable[[str, str], str],+):+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)++ insert_alert_data(+ [types.AlertData(type="logs", data_path="alerts/test_scenarios/rule_state_history_logs/alert_data.jsonl")],+ base_time=datetime.now(tz=UTC) - timedelta(minutes=5),+ )+ rule_id = create_alert_rule_with_channel("alerts/test_scenarios/rule_state_history_logs/rule.json")++ (item, query_end_ms) = wait_for_firing_timeline_entry(signoz, token, rule_id, query_start_ms)++ assert labels_to_map(item["labels"]).get("service.name") == "payment-service"+ assert item.get("relatedTracesLink", "") == ""+ assert item.get("relatedLogsLink", "") != ""++ # logs explorer links carry the time range in milliseconds, anchored to the+ # second-truncated entry timestamp+ link = parse_related_link(item["relatedLogsLink"])+ assert link["end"] == (item["unixMilli"] // 1000) * 1000+ assert link["end"] - link["start"] == RELATED_LINK_WINDOW_SECONDS * 1000+ assert_related_link_query(link, "logs", ["payment success", "service.name", "payment-service"])++ contributors = get_rule_history_top_contributors(signoz, token, rule_id, query_start_ms, query_end_ms)+ contributors = [c for c in contributors if labels_to_map(c["labels"]).get("service.name") == "payment-service"]+ assert len(contributors) == 1+ assert contributors[0]["count"] >= 1+ assert contributors[0].get("relatedTracesLink", "") == ""+ assert contributors[0].get("relatedLogsLink", "") != ""++ # contributor counts aggregate the whole queried range, so their links span it+ contributor_link = parse_related_link(contributors[0]["relatedLogsLink"])+ assert contributor_link["start"] == query_start_ms+ assert contributor_link["end"] == query_end_ms+ assert_related_link_query(contributor_link, "logs", ["payment success", "service.name", "payment-service"])+++def test_traces_rule_history_related_links(+ signoz: types.SigNoz,+ create_alert_rule_with_channel: Callable[[str], str],+ insert_alert_data: Callable[[list[types.AlertData], datetime], None],+ get_token: Callable[[str, str], str],+):+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)++ insert_alert_data(+ [types.AlertData(type="traces", data_path="alerts/test_scenarios/rule_state_history_traces/alert_data.jsonl")],+ base_time=datetime.now(tz=UTC) - timedelta(minutes=5),+ )+ rule_id = create_alert_rule_with_channel("alerts/test_scenarios/rule_state_history_traces/rule.json")++ (item, query_end_ms) = wait_for_firing_timeline_entry(signoz, token, rule_id, query_start_ms)++ assert labels_to_map(item["labels"]).get("service.name") == "order-service"+ assert item.get("relatedLogsLink", "") == ""+ assert item.get("relatedTracesLink", "") != ""++ # traces explorer links carry the time range in nanoseconds, anchored to the+ # second-truncated entry timestamp+ link = parse_related_link(item["relatedTracesLink"])+ assert link["end"] == (item["unixMilli"] // 1000) * 1_000_000_000+ assert link["end"] - link["start"] == RELATED_LINK_WINDOW_SECONDS * 1_000_000_000+ assert_related_link_query(link, "traces", ["http.request.path", "/order", "service.name", "order-service"])++ contributors = get_rule_history_top_contributors(signoz, token, rule_id, query_start_ms, query_end_ms)+ contributors = [c for c in contributors if labels_to_map(c["labels"]).get("service.name") == "order-service"]+ assert len(contributors) == 1+ assert contributors[0]["count"] >= 1+ assert contributors[0].get("relatedLogsLink", "") == ""+ assert contributors[0].get("relatedTracesLink", "") != ""++ # contributor counts aggregate the whole queried range, so their links span it+ contributor_link = parse_related_link(contributors[0]["relatedTracesLink"])+ assert contributor_link["start"] == query_start_ms * 1_000_000+ assert contributor_link["end"] == query_end_ms * 1_000_000+ assert_related_link_query(contributor_link, "traces", ["http.request.path", "/order", "service.name", "order-service"])