diff --git a/admin/server/alerts.go b/admin/server/alerts.go index e4231ca216b9..431a69c5e2c9 100644 --- a/admin/server/alerts.go +++ b/admin/server/alerts.go @@ -680,6 +680,8 @@ func (s *Server) yamlForManagedAlert(opts *adminv1.AlertOptions, ownerUserID, em return nil, err } // Notification options + // An AI alert's check fails when the analysis can't determine whether its condition holds, so its owner hears about errors. + res.OnError = opts.Resolver == "ai" res.Renotify = opts.Renotify res.RenotifyAfter = opts.RenotifyAfterSeconds res.Notify.RowsLimit = opts.NotifyRowsLimit @@ -828,6 +830,7 @@ type alertYAML struct { IncludeHeader bool `yaml:"include_header"` Limit uint64 `yaml:"limit,omitempty"` } `yaml:"export,omitempty"` // Omitted unless attaching, so runtimes that predate it can parse the YAML + OnError bool `yaml:"on_error,omitempty"` Renotify bool `yaml:"renotify"` RenotifyAfter uint32 `yaml:"renotify_after"` Notify struct { diff --git a/admin/server/alerts_test.go b/admin/server/alerts_test.go index 951318350e72..7da87219e043 100644 --- a/admin/server/alerts_test.go +++ b/admin/server/alerts_test.go @@ -7,6 +7,7 @@ import ( adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1" runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1" "github.com/rilldata/rill/runtime" + "github.com/rilldata/rill/runtime/parser" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/structpb" "gopkg.in/yaml.v3" @@ -219,3 +220,34 @@ func TestYAMLForAlertNotifyRowsLimit(t *testing.T) { opts.NotifyRowsLimit = 10 } } + +// TestYAMLForManagedAIAlertNotifiesOnError checks that AI alerts notify on errors, +// since a check fails when the analysis can't determine whether the condition holds. +func TestYAMLForManagedAIAlertNotifiesOnError(t *testing.T) { + s := &Server{} + props, err := structpb.NewStruct(map[string]any{"prompt": "Revenue dropped", "explore": "e1"}) + require.NoError(t, err) + opts := &adminv1.AlertOptions{ + DisplayName: "Alert", + MetricsViewName: "mv1", + RefreshCron: "0 9 * * *", + Resolver: "ai", + ResolverProperties: props, + EmailRecipients: []string{"user_1@example.com"}, + } + parse := func() *parser.AlertYAML { + data, err := s.yamlForManagedAlert(opts, "owner", "", "", nil) + require.NoError(t, err) + res := &parser.AlertYAML{} + require.NoError(t, yaml.Unmarshal(data, res)) + return res + } + onError := parse().OnError + require.NotNil(t, onError) + require.True(t, *onError) + + // Other alerts keep the parser's default, which doesn't notify on errors + opts.Resolver, opts.ResolverProperties = "", nil + opts.QueryName, opts.QueryArgsJson = "MetricsViewAggregation", `{"metrics_view":"mv1"}` + require.Nil(t, parse().OnError) +} diff --git a/docs/docs/reference/project-files/alerts.md b/docs/docs/reference/project-files/alerts.md index 63ff46b1e276..82abd97c98c9 100644 --- a/docs/docs/reference/project-files/alerts.md +++ b/docs/docs/reference/project-files/alerts.md @@ -111,11 +111,11 @@ _[oneOf]_ - Data source for the alert _(required)_ - **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_ - - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports. + - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts. - **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_ - - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. + - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks. - **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps. @@ -264,3 +264,27 @@ notify: channels: - '#rill-cloud-alerts' ``` + +```yaml +# Example: To send an email when an AI analysis finds that a condition written in words holds +type: alert +display_name: Weekly revenue drop +# AI alerts must run on a cron schedule of at most once an hour, and can't set `refresh.every`, `refresh.ref_update` or `intervals`. +refresh: + cron: 0 9 * * * + time_zone: America/New_York +# AI alerts must set the Rill Cloud user whose access and AI session the analysis runs with. +for: + user_id: +# The prompt is the condition; the alert fails, and notifies, when the analysis finds that it holds. +data: + ai: + prompt: Revenue dropped by more than 10% compared with the previous 7 days + explore: sales_explore + time_range: + expression: 7D as of latest/D+1D # the last 7 days with data +notify: + email: + recipients: + - jane@example.com +``` diff --git a/docs/docs/reference/project-files/models.md b/docs/docs/reference/project-files/models.md index 327a060415e4..6546086f1ec7 100644 --- a/docs/docs/reference/project-files/models.md +++ b/docs/docs/reference/project-files/models.md @@ -178,11 +178,11 @@ _[oneOf]_ - Refers to the explicitly defined state of your model, cannot be used - **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_ - - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports. + - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts. - **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_ - - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. + - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks. - **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps. @@ -272,11 +272,11 @@ _[oneOf]_ - Refers to how your data is partitioned; cannot be used with state. ( - **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_ - - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports. + - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts. - **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_ - - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. + - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks. - **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps. diff --git a/docs/docs/reference/project-files/reports.md b/docs/docs/reference/project-files/reports.md index 1f41eaf32a75..823cf5ba8d60 100644 --- a/docs/docs/reference/project-files/reports.md +++ b/docs/docs/reference/project-files/reports.md @@ -117,11 +117,11 @@ Supports ai resolvers only as of now. - **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_ - - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports. + - **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts. - **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_ - - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. + - **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks. - **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps. diff --git a/runtime/ai/analyst_agent.go b/runtime/ai/analyst_agent.go index 5068fb2f55a3..2910578ef714 100644 --- a/runtime/ai/analyst_agent.go +++ b/runtime/ai/analyst_agent.go @@ -43,6 +43,7 @@ type AnalystAgentArgs struct { ComparisonTimeEnd time.Time `json:"comparison_time_end" yaml:"comparison_time_end" jsonschema:"Optional comparison period end time."` DisableCharts bool `json:"disable_charts" yaml:"disable_charts" jsonschema:"Flag indicating whether to disable chart creation in the analysis."` IsReport bool `json:"is_report" yaml:"is_report" jsonschema:"Flag indicating this is an automated report."` + IsAlert bool `json:"is_alert" yaml:"is_alert" jsonschema:"Flag indicating this checks an AI alert's condition, which is the prompt. The result then includes a verdict."` } func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock { @@ -55,8 +56,19 @@ func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock { type AnalystAgentResult struct { Response string `json:"response"` + // AlertOutcome is the verdict on an AI alert's condition (see AnalystAgentArgs.IsAlert). + AlertOutcome AlertOutcome `json:"alert_outcome,omitempty"` } +// AlertOutcome is the analyst's verdict on whether an AI alert's condition holds. +type AlertOutcome string + +const ( + AlertOutcomeMet AlertOutcome = "met" + AlertOutcomeNotMet AlertOutcome = "not_met" + AlertOutcomeCannotDetermine AlertOutcome = "cannot_determine" +) + func (r *AnalystAgentResult) ToLLM() *aiv1.ContentBlock { return &aiv1.ContentBlock{ BlockType: &aiv1.ContentBlock_Text{ @@ -253,9 +265,42 @@ func (t *AnalystAgent) Handler(ctx context.Context, args *AnalystAgentArgs) (*An return nil, err } + // An AI alert's analysis ends with a verdict on its condition. + // The verdict is a separate call without tools, since some providers (e.g. Gemini) reject requests that combine tools with an output schema. + if args.IsAlert { + outcome, err := alertOutcome(ctx, s, args.Prompt, response) + if err != nil { + return nil, err + } + return &AnalystAgentResult{Response: response, AlertOutcome: outcome}, nil + } + return &AnalystAgentResult{Response: response}, nil } +// alertOutcome classifies the analysis of an AI alert's condition as met, not met, or not answerable from the data. +func alertOutcome(ctx context.Context, s *Session, condition, analysis string) (AlertOutcome, error) { + var verdict struct { + Outcome AlertOutcome `json:"outcome" jsonschema:"One of \"met\", \"not_met\" or \"cannot_determine\"."` + } + err := s.Complete(ctx, "Alert verdict", &verdict, &CompleteOptions{ + Messages: []*aiv1.CompletionMessage{ + NewTextCompletionMessage(RoleSystem, `You read an analysis that checked whether an alert's condition holds, and give the analysis's verdict. +The outcome is "met" if the analysis shows that the condition holds, "not_met" if it shows that the condition does not hold, +and "cannot_determine" if the analysis could not tell, for example because the data has no measure or dimension that the condition refers to.`), + NewTextCompletionMessage(RoleUser, fmt.Sprintf("The alert's condition:\n%s\n\nThe analysis:\n%s", condition, analysis)), + }, + }) + if err != nil { + return "", fmt.Errorf("failed to get a verdict on the alert's condition: %w", err) + } + switch verdict.Outcome { + case AlertOutcomeMet, AlertOutcomeNotMet, AlertOutcomeCannotDetermine: + return verdict.Outcome, nil + } + return "", fmt.Errorf("invalid verdict on the alert's condition: %q", verdict.Outcome) +} + func (t *AnalystAgent) systemPrompt(ctx context.Context) (string, error) { instr, err := instructions.Load("analysis.md", instructions.Options{Memory: GetSession(ctx).MemoryEnabled()}) if err != nil { @@ -307,6 +352,7 @@ func (t *AnalystAgent) userPrompt(ctx context.Context, metricsViewNames []string "measures": strings.Join(measuresQuoted, ", "), "forked": session.Forked(), "is_report": args.IsReport, + "is_alert": args.IsAlert, "now": time.Now(), "max_query_limit": instanceCfg.AIMaxQueryLimit, "external_servers": session.ExternalServerPromptData(ctx, "analyst"), @@ -349,9 +395,18 @@ You are operating in an automated scheduled insight report mode where you will c {{ if .is_prompt }}The user has provided a custom prompt for this scheduled insight report. Tailor your analysis to address this prompt specifically.{{ end }} {{ end }} +{{ if .is_alert }} +You are checking the condition of an automated alert, without additional user input. +The condition is the user's request at the end of this message: a statement about the data that either holds or does not. +Query the data to decide whether it holds. Do not ask questions, since nobody will answer them. +If the data can't tell whether the condition holds, for example because it refers to a measure or dimension that doesn't exist, say so instead of guessing. +Relative expressions in the condition, such as "this month", "today" or "compared with the previous period", refer to {{ if (and .time_start .time_end) }}the time range start={{.time_start}}, end={{.time_end}}{{ else }}the latest data available{{ end }}, not to today's date. +Begin your final response with a summary wrapped in tags: one to three plain sentences that say whether the condition holds and give the figures it rests on, without citation links. +{{ end }} + {{ if .explore }} Your goal is to analyze the contents of the dashboard "{{ .explore }}", which is powered by the metrics view(s) {{ .metrics_views }}. -{{ if not .is_report }}The user is actively viewing this dashboard, and it's what they refer to if they use expressions like "this dashboard", "the current view", etc. {{ end }} +{{ if not (or .is_report .is_alert) }}The user is actively viewing this dashboard, and it's what they refer to if they use expressions like "this dashboard", "the current view", etc. {{ end }} The metrics view's definition and time range of available data has been provided in your tool calls. Here is an overview of the settings applied to the dashboard: diff --git a/runtime/ai/analyst_alert_test.go b/runtime/ai/analyst_alert_test.go new file mode 100644 index 000000000000..685ab8ecc427 --- /dev/null +++ b/runtime/ai/analyst_alert_test.go @@ -0,0 +1,126 @@ +package ai_test + +import ( + "testing" + + "github.com/google/jsonschema-go/jsonschema" + aiv1 "github.com/rilldata/rill/proto/gen/rill/ai/v1" + "github.com/rilldata/rill/runtime/ai" + "github.com/rilldata/rill/runtime/drivers" + "github.com/rilldata/rill/runtime/testruntime" + "github.com/stretchr/testify/require" +) + +func TestAnalystAlert(t *testing.T) { + alertArgs := &ai.RouterAgentArgs{ + Prompt: "There are orders from Denmark", + Agent: ai.AnalystAgentName, + AnalystAgentArgs: &ai.AnalystAgentArgs{IsAlert: true}, + } + analysis := "Denmark has orders. Orders come from Denmark." + + cases := []struct { + verdict string + want ai.AlertOutcome + wantErr string + }{ + {verdict: `{"outcome": "met"}`, want: ai.AlertOutcomeMet}, + {verdict: `{"outcome": "not_met"}`, want: ai.AlertOutcomeNotMet}, + {verdict: `{"outcome": "cannot_determine"}`, want: ai.AlertOutcomeCannotDetermine}, + {verdict: `{"outcome": "maybe"}`, wantErr: "invalid verdict"}, + {verdict: `The condition holds.`, wantErr: "verdict"}, + } + for _, tc := range cases { + t.Run(tc.verdict, func(t *testing.T) { + var schemas []*jsonschema.Schema + recordSchema := func(turn turnFunc) turnFunc { + return func(opts *drivers.CompleteOptions) *aiv1.CompletionMessage { + schemas = append(schemas, opts.OutputSchema) + return turn(opts) + } + } + script := &scriptedAIService{turns: []turnFunc{recordSchema(textTurn(analysis)), recordSchema(textTurn(tc.verdict))}} + s := newSkillReferencesSession(t, script) + + var res *ai.RouterAgentResult + _, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, &res, alertArgs) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + return + } + require.NoError(t, err) + require.Equal(t, tc.want, res.AlertOutcome) + require.Equal(t, analysis, res.Response) + + // The analysis runs with tools and the verdict with an output schema, in separate requests, + // since some providers reject a request that combines them. + require.Len(t, schemas, 2) + require.Contains(t, script.tools[0], ai.QueryMetricsViewName) + require.Nil(t, schemas[0]) + require.Empty(t, script.tools[1]) + require.Contains(t, schemas[1].Properties, "outcome") + // The verdict is given on the analysis + require.Contains(t, script.inputs[1][len(script.inputs[1])-1].Content[0].GetText(), analysis) + }) + } +} + +func TestAnalystAlertEval(t *testing.T) { + // Eight weeks of daily revenue for three countries. + // Revenue is around 100 a day for every country, except Spain, which drops to around 30 a day in the last week. + rt, instanceID := testruntime.NewInstanceWithOptions(t, testruntime.InstanceOptions{ + AIConnector: "openai", + Files: map[string]string{ + "models/orders.yaml": ` +type: model +materialize: true +sql: | + SELECT + d::TIMESTAMP AS event_time, + c AS country, + CASE WHEN c = 'Spain' AND d >= DATE '2025-10-19' THEN 30 ELSE 100 END + (hash(d::DATE, c) % 7)::INTEGER AS revenue + FROM range(DATE '2025-08-31', DATE '2025-10-26', INTERVAL 1 DAY) AS t(d), (VALUES ('Spain'), ('France'), ('Germany')) AS countries(c) +`, + "metrics/orders.yaml": ` +type: metrics_view +model: orders +timeseries: event_time +dimensions: +- column: country +measures: +- name: revenue + expression: SUM(revenue) +`, + "explores/orders.yaml": ` +type: explore +metrics_view: orders +`, + }, + }) + testruntime.RequireReconcileState(t, rt, instanceID, 3, 0, 0) + + cases := []struct { + condition string + want ai.AlertOutcome + }{ + {"Revenue in Spain dropped sharply in the last week compared with the previous weeks", ai.AlertOutcomeMet}, + {"Spain is the country with the lowest revenue in the last week", ai.AlertOutcomeMet}, + {"Revenue in France dropped sharply in the last week compared with the previous weeks", ai.AlertOutcomeNotMet}, + {"There are orders from Italy", ai.AlertOutcomeNotMet}, + // The data has no profit + {"The profit margin in Spain fell below 10% in the last week", ai.AlertOutcomeCannotDetermine}, + } + for _, tc := range cases { + t.Run(tc.condition, func(t *testing.T) { + s := newEval(t, rt, instanceID) + var res *ai.RouterAgentResult + _, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, &res, &ai.RouterAgentArgs{ + Prompt: tc.condition, + Agent: ai.AnalystAgentName, + AnalystAgentArgs: &ai.AnalystAgentArgs{Explore: "orders", IsAlert: true}, + }) + require.NoError(t, err) + require.Equal(t, tc.want, res.AlertOutcome, res.Response) + }) + } +} diff --git a/runtime/ai/router_agent.go b/runtime/ai/router_agent.go index c213942462fc..4f8ff5825720 100644 --- a/runtime/ai/router_agent.go +++ b/runtime/ai/router_agent.go @@ -38,6 +38,8 @@ type RouterAgentArgs struct { type RouterAgentResult struct { Response string `json:"response"` Agent string `json:"agent"` + // AlertOutcome is the analyst's verdict when it checked an AI alert's condition. + AlertOutcome AlertOutcome `json:"alert_outcome,omitempty"` } func (t *RouterAgent) Spec() *mcp.Tool { @@ -169,7 +171,7 @@ func (t *RouterAgent) Handler(ctx context.Context, args *RouterAgentArgs) (*Rout if err != nil { return nil, mapAgentErr(err) } - return &RouterAgentResult{Response: res.Response, Agent: args.Agent}, nil + return &RouterAgentResult{Response: res.Response, Agent: args.Agent, AlertOutcome: res.AlertOutcome}, nil case DeveloperAgentName: developerAgentArgs := args.DeveloperAgentArgs diff --git a/runtime/drivers/notifier.go b/runtime/drivers/notifier.go index 54e7e128f7c2..916056c7282b 100644 --- a/runtime/drivers/notifier.go +++ b/runtime/drivers/notifier.go @@ -20,6 +20,7 @@ type AlertStatus struct { FailColumns []string // Column names of FailRows, in the order of the alert query's result FailRows [][]string // Display values of the rows that matched the alert criteria; it has at most the alert's rows limit FailRowsTruncated bool // True if more rows matched the alert criteria than FailRows contains + Reason string // The AI analysis's reason when an AI alert fires; it's shown instead of the fail rows ExecutionError string OpenLink string EditLink string diff --git a/runtime/drivers/slack/notifier.go b/runtime/drivers/slack/notifier.go index a816260c3873..9decb9cd071f 100644 --- a/runtime/drivers/slack/notifier.go +++ b/runtime/drivers/slack/notifier.go @@ -127,6 +127,7 @@ func (n *notifier) SendAlertStatus(s *drivers.AlertStatus) error { DisplayName: s.DisplayName, ExecutionTimeString: s.ExecutionTime.Format(time.RFC1123), FailRowsTruncated: s.FailRowsTruncated, + Reason: slackTextEscaper.Replace(s.Reason), // Escaped but not truncated, since it's the whole message OpenLink: htemplate.URL(s.OpenLink), EditLink: htemplate.URL(s.EditLink), } @@ -146,7 +147,7 @@ func (n *notifier) SendAlertStatus(s *drivers.AlertStatus) error { DisplayName: s.DisplayName, ExecutionTimeString: s.ExecutionTime.Format(time.RFC1123), IsError: true, - ErrorMessage: s.ExecutionError, + ErrorMessage: slackTextEscaper.Replace(s.ExecutionError), // Escaped, since an AI alert's error carries the analysis's text OpenLink: htemplate.URL(s.EditLink), EditLink: htemplate.URL(s.EditLink), }) @@ -297,6 +298,7 @@ type AlertFailData struct { FailRowLines []string // One line per row that matched the alert criteria, if several rows are listed FailRowsLeadColumn string // The column whose value leads each of FailRowLines FailRowsTruncated bool // True if more rows matched the alert criteria than are listed + Reason string // The AI analysis's reason when an AI alert fires, shown instead of the rows OpenLink htemplate.URL EditLink htemplate.URL } diff --git a/runtime/drivers/slack/notifier_test.go b/runtime/drivers/slack/notifier_test.go index 5bd84a1a1408..a12ab4b4a513 100644 --- a/runtime/drivers/slack/notifier_test.go +++ b/runtime/drivers/slack/notifier_test.go @@ -58,6 +58,33 @@ func TestSendAlertFail(t *testing.T) { require.Len(t, texts, 3) require.Contains(t, texts[2], "The first 2 rows that matched your alert criteria are listed by *country*:") require.Contains(t, texts[2], "More rows matched your alert criteria.") + + // An AI alert shows the analysis's reason instead of rows, and links to the analysis + reason := strings.Repeat("Revenue fell 40% against the previous four weeks. ", 5) + require.NoError(t, n.SendAlertStatus(&drivers.AlertStatus{ + DisplayName: "Revenue drop", + ExecutionTime: time.Date(2026, 11, 12, 0, 0, 0, 0, time.UTC), + Status: runtimev1.AssertionStatus_ASSERTION_STATUS_FAIL, + Reason: reason, + OpenLink: "https://example.com/open?session_id=s1", + EditLink: "https://example.com/edit", + })) + require.Len(t, texts, 4) + require.Contains(t, texts[3], "The AI analysis found that the condition holds:\n\n"+reason+"\n") + require.Contains(t, texts[3], "") + require.NotContains(t, texts[3], "matched your alert criteria") + + // An error's message is escaped too, since an AI alert's error carries the analysis's text + require.NoError(t, n.SendAlertStatus(&drivers.AlertStatus{ + DisplayName: "Revenue drop", + ExecutionTime: time.Date(2026, 11, 12, 0, 0, 0, 0, time.UTC), + Status: runtimev1.AssertionStatus_ASSERTION_STATUS_ERROR, + ExecutionError: "the AI analysis could not determine whether the condition holds: has no revenue & cost data", + EditLink: "https://example.com/edit", + })) + require.Len(t, texts, 5) + require.Contains(t, texts[4], "_the AI analysis could not determine whether the condition holds: <!channel> has no revenue & cost data_") + require.NotContains(t, texts[4], "") } func TestSlackText(t *testing.T) { diff --git a/runtime/drivers/slack/templates/slack/alert_fail.slack b/runtime/drivers/slack/templates/slack/alert_fail.slack index 6839391c693f..6eca363e7f77 100644 --- a/runtime/drivers/slack/templates/slack/alert_fail.slack +++ b/runtime/drivers/slack/templates/slack/alert_fail.slack @@ -2,7 +2,11 @@ Your alert triggered for {{ .ExecutionTimeString }}. -{{ if .FailFields -}} +{{ if .Reason -}} +The AI analysis found that the condition holds: + +{{ .Reason }} +{{- else if .FailFields -}} The first row that matched your alert criteria is: {{ range .FailFields }} • *{{ .Name }}*: {{ .Value }} @@ -16,6 +20,6 @@ The first row that matched your alert criteria is: {{ if .FailRowsTruncated }} More rows matched your alert criteria. {{ end }} -<{{ .OpenLink }}|Open in browser> +<{{ .OpenLink }}|{{ if .Reason }}View full analysis{{ else }}Open in browser{{ end }}> To edit or unsubscribe from this alert, <{{ .EditLink }}|click here>. diff --git a/runtime/parser/parse_alert.go b/runtime/parser/parse_alert.go index 24fc9ed61401..7be14b426130 100644 --- a/runtime/parser/parse_alert.go +++ b/runtime/parser/parse_alert.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "math/bits" "net/mail" "strings" "time" @@ -12,6 +13,7 @@ import ( "github.com/rilldata/rill/runtime/drivers/slack" "github.com/rilldata/rill/runtime/pkg/duration" "github.com/rilldata/rill/runtime/pkg/pbutil" + "github.com/robfig/cron/v3" "google.golang.org/protobuf/types/known/structpb" ) @@ -248,6 +250,20 @@ func (p *Parser) parseAlert(node *Node) error { } } + // Every check of an AI alert runs an AI analysis, so AI alerts are checked on a schedule of at most once an hour. + if resolver == "ai" { + err := validateAIAlertSchedule(tmp.Refresh) + if err != nil { + return err + } + if tmp.Intervals.Duration != "" { + return errors.New(`AI alerts can't set "intervals", since every interval is a separate AI analysis`) + } + if queryForUserID == "" { + return errors.New(`AI alerts must set "for.user_id", the user whose access and AI session the analysis runs with`) + } + } + // Parse export options, which only apply to the export attached to email notifications for failed checks. var exportFormat runtimev1.ExportFormat if tmp.Export.Attach { @@ -437,3 +453,38 @@ func (p *Parser) parseAlert(node *Node) error { return nil } + +// validateAIAlertSchedule checks that an AI alert is checked on a cron schedule that runs at most once an hour. +// AI alerts can't be checked when their data refreshes or on a ticker, which can run far more often. +func validateAIAlertSchedule(raw *ScheduleYAML) error { + if raw != nil && raw.Disable { + return nil + } + if raw == nil || raw.Cron == "" { + return errors.New(`AI alerts must set "refresh.cron"`) + } + if raw.Every != "" { + return errors.New(`AI alerts can't set "refresh.every"; use "refresh.cron"`) + } + if raw.RefUpdate != nil && *raw.RefUpdate { + return errors.New(`AI alerts can't set "refresh.ref_update"`) + } + + schedule, err := cron.ParseStandard(raw.Cron) + if err != nil { + return fmt.Errorf("invalid cron schedule: %w", err) + } + switch schedule := schedule.(type) { + case *cron.SpecSchedule: + // A cron schedule runs at most once an hour if it runs at a single minute of the hour. + // The highest bit marks a "*" field. + if bits.OnesCount64(schedule.Minute&^(1<<63)) > 1 { + return fmt.Errorf(`AI alerts can run at most once an hour, but "refresh.cron" %q runs more often`, raw.Cron) + } + case cron.ConstantDelaySchedule: + if schedule.Delay < time.Hour { + return fmt.Errorf(`AI alerts can run at most once an hour, but "refresh.cron" %q runs more often`, raw.Cron) + } + } + return nil +} diff --git a/runtime/parser/parser_test.go b/runtime/parser/parser_test.go index d5f4a064eb1f..f3935a2f8451 100644 --- a/runtime/parser/parser_test.go +++ b/runtime/parser/parser_test.go @@ -2170,6 +2170,105 @@ notify: }) } +func TestAIAlertSchedule(t *testing.T) { + ctx := context.Background() + aiAlert := func(extra string) string { + return ` +type: alert +data: + ai: + prompt: Revenue dropped sharply + explore: e1 +notify: + email: + recipients: + - user_1@example.com +` + extra + } + repo := makeRepo(t, map[string]string{ + `rill.yaml`: ``, + // Checked hourly + `alerts/a1.yaml`: aiAlert(` +refresh: + cron: 5 * * * * +for: + user_id: u1 +`), + // Checked on data refreshes + `alerts/a2.yaml`: aiAlert(` +for: + user_id: u1 +`), + // Checked every 30 minutes + `alerts/a3.yaml`: aiAlert(` +refresh: + cron: "*/30 * * * *" +for: + user_id: u1 +`), + `alerts/a4.yaml`: aiAlert(` +refresh: + cron: "@every 30m" +for: + user_id: u1 +`), + // Checked on data refreshes too + `alerts/a5.yaml`: aiAlert(` +refresh: + cron: 0 * * * * + ref_update: true +for: + user_id: u1 +`), + // Checked for several intervals at once + `alerts/a6.yaml`: aiAlert(` +refresh: + cron: 0 * * * * +intervals: + duration: PT1H +for: + user_id: u1 +`), + // Without a user to run as + `alerts/a7.yaml`: aiAlert(` +refresh: + cron: 0 * * * * +`), + }) + + resources := []*Resource{ + { + Name: ResourceName{Kind: ResourceKindAlert, Name: "a1"}, + Paths: []string{"/alerts/a1.yaml"}, + Refs: []ResourceName{{Kind: ResourceKindExplore, Name: "e1"}}, + AlertSpec: &runtimev1.AlertSpec{ + DisplayName: "A1", + RefreshSchedule: &runtimev1.Schedule{Cron: "5 * * * *"}, + Resolver: "ai", + ResolverProperties: must(structpb.NewStruct(map[string]any{ + "prompt": "Revenue dropped sharply", + "explore": "e1", + })), + QueryFor: &runtimev1.AlertSpec_QueryForUserId{QueryForUserId: "u1"}, + NotifyOnFail: true, + NotifyRowsLimit: 5, + Notifiers: []*runtimev1.Notifier{{Connector: "email", Properties: must(structpb.NewStruct(map[string]any{"recipients": []any{"user_1@example.com"}}))}}, + }, + }, + } + + p, err := Parse(ctx, repo, "", "", "duckdb", true) + require.NoError(t, err) + requireResourcesAndErrors(t, p, resources, []*runtimev1.ParseError{ + {Message: `AI alerts must set "refresh.cron"`, FilePath: "/alerts/a2.yaml"}, + {Message: `AI alerts can run at most once an hour, but "refresh.cron" "*/30 * * * *" runs more often`, FilePath: "/alerts/a3.yaml"}, + {Message: `AI alerts can run at most once an hour, but "refresh.cron" "@every 30m" runs more often`, FilePath: "/alerts/a4.yaml"}, + {Message: `AI alerts can't set "refresh.ref_update"`, FilePath: "/alerts/a5.yaml"}, + {Message: `AI alerts can't set "intervals", since every interval is a separate AI analysis`, FilePath: "/alerts/a6.yaml"}, + {Message: `AI alerts must set "for.user_id", the user whose access and AI session the analysis runs with`, FilePath: "/alerts/a7.yaml"}, + }) +} + func TestMetricsViewAvoidSelfCyclicRef(t *testing.T) { ctx := context.Background() repo := makeRepo(t, map[string]string{ diff --git a/runtime/parser/schema/project.schema.yaml b/runtime/parser/schema/project.schema.yaml index a67811776437..6c96a2a3d4b7 100644 --- a/runtime/parser/schema/project.schema.yaml +++ b/runtime/parser/schema/project.schema.yaml @@ -3085,6 +3085,27 @@ definitions: slack: channels: - '#rill-cloud-alerts' + - # Example: To send an email when an AI analysis finds that a condition written in words holds + type: alert + display_name: Weekly revenue drop + # AI alerts must run on a cron schedule of at most once an hour, and can't set `refresh.every`, `refresh.ref_update` or `intervals`. + refresh: + cron: 0 9 * * * + time_zone: America/New_York + # AI alerts must set the Rill Cloud user whose access and AI session the analysis runs with. + for: + user_id: + # The prompt is the condition; the alert fails, and notifies, when the analysis finds that it holds. + data: + ai: + prompt: Revenue dropped by more than 10% compared with the previous 7 days + explore: sales_explore + time_range: + expression: 7D as of latest/D+1D # the last 7 days with data + notify: + email: + recipients: + - jane@example.com allOf: - title: Properties type: object @@ -4687,7 +4708,7 @@ definitions: start: dir/year=2025/month=03/day=01 - title: AI Resolver type: object - description: Uses AI to generate insights and analysis from metrics data. Only available for reports. + description: Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts. properties: ai: type: object @@ -4695,7 +4716,7 @@ definitions: properties: prompt: type: string - description: Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. + description: Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks. time_range: type: object description: Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps. diff --git a/runtime/parser/schema_test.go b/runtime/parser/schema_test.go index 85650ddffb19..193d8bbc5c5c 100644 --- a/runtime/parser/schema_test.go +++ b/runtime/parser/schema_test.go @@ -110,21 +110,32 @@ func TestJSONSchemaForResourceType(t *testing.T) { } } -// TestThemeSchemaExamples checks that the theme examples in the schema, which are published in the docs, parse as themes. -func TestThemeSchemaExamples(t *testing.T) { - schema, err := JSONSchemaForResourceType(ResourceKindTheme) - require.NoError(t, err) - require.NotEmpty(t, schema.Examples) - - files := map[string]string{"rill.yaml": ""} - for i, example := range schema.Examples { - data, err := yaml.Marshal(example) - require.NoError(t, err) - files[fmt.Sprintf("themes/example_%d.yaml", i)] = string(data) +// TestSchemaExamples checks that the examples in the schema, which are published in the docs, parse as resources of their kind. +func TestSchemaExamples(t *testing.T) { + tests := []struct { + kind ResourceKind + dir string + }{ + {kind: ResourceKindTheme, dir: "themes"}, + {kind: ResourceKindAlert, dir: "alerts"}, } + for _, tt := range tests { + t.Run(tt.dir, func(t *testing.T) { + schema, err := JSONSchemaForResourceType(tt.kind) + require.NoError(t, err) + require.NotEmpty(t, schema.Examples) - p, err := Parse(context.Background(), makeRepo(t, files), "", "", "duckdb", true) - require.NoError(t, err) - require.Empty(t, p.Errors) - require.Len(t, p.Resources, len(schema.Examples)) + files := map[string]string{"rill.yaml": ""} + for i, example := range schema.Examples { + data, err := yaml.Marshal(example) + require.NoError(t, err) + files[fmt.Sprintf("%s/example_%d.yaml", tt.dir, i)] = string(data) + } + + p, err := Parse(context.Background(), makeRepo(t, files), "", "", "duckdb", true) + require.NoError(t, err) + require.Empty(t, p.Errors) + require.Len(t, p.Resources, len(schema.Examples)) + }) + } } diff --git a/runtime/pkg/email/email.go b/runtime/pkg/email/email.go index 6379deca3edb..22a93aca714a 100644 --- a/runtime/pkg/email/email.go +++ b/runtime/pkg/email/email.go @@ -104,6 +104,7 @@ type AlertStatus struct { FailColumns []string // Column names of FailRows, in the order of the alert query's result FailRows [][]string // Display values of the rows that matched the alert criteria FailRowsTruncated bool // True if more rows matched the alert criteria than FailRows contains + Reason string // The AI analysis's reason when an AI alert fires; it's shown instead of the fail rows ExecutionError string OpenLink string EditLink string @@ -131,6 +132,7 @@ func (c *Client) SendAlertStatus(opts *AlertStatus) error { FailColumns: opts.FailColumns, FailRows: opts.FailRows, FailRowsTruncated: opts.FailRowsTruncated, + Reason: opts.Reason, OpenLink: template.URL(opts.OpenLink), EditLink: template.URL(opts.EditLink), UnsubscribeLink: template.URL(opts.UnsubscribeLink), @@ -158,6 +160,7 @@ type alertFailData struct { FailColumns []string FailRows [][]string FailRowsTruncated bool + Reason string OpenLink template.URL EditLink template.URL UnsubscribeLink template.URL diff --git a/runtime/pkg/email/email_test.go b/runtime/pkg/email/email_test.go index e9c26e2eaee3..51423c522cea 100644 --- a/runtime/pkg/email/email_test.go +++ b/runtime/pkg/email/email_test.go @@ -150,6 +150,16 @@ func TestAlertFail(t *testing.T) { require.NoError(t, err) require.Contains(t, mock.body, "The first 2 rows that matched your alert criteria are:") require.Contains(t, mock.body, "More rows matched your alert criteria.") + + // An AI alert shows the analysis's reason instead of rows, and links to the analysis + opts.FailColumns, opts.FailRows, opts.FailRowsTruncated = nil, nil, false + opts.Reason = "Revenue fell 40% against the previous four weeks." + err = client.SendAlertStatus(opts) + require.NoError(t, err) + require.Contains(t, mock.body, "The AI analysis found that the condition holds:") + require.Contains(t, mock.body, opts.Reason) + require.Contains(t, mock.body, "View full analysis") + require.NotContains(t, mock.body, "matched your alert criteria") } func TestAlertRecover(t *testing.T) { diff --git a/runtime/pkg/email/templates/alert_fail.mjml b/runtime/pkg/email/templates/alert_fail.mjml index 2bad5f350d0e..46af9e712716 100644 --- a/runtime/pkg/email/templates/alert_fail.mjml +++ b/runtime/pkg/email/templates/alert_fail.mjml @@ -26,7 +26,15 @@ {{ .DisplayName }} - {{ if eq (len .FailRows) 1 }} + {{ if .Reason }} + + Your alert triggered for {{ .ExecutionTimeString }}. The AI analysis found that the condition holds: + + + + {{ .Reason }} + + {{ else if eq (len .FailRows) 1 }} Your alert triggered for {{ .ExecutionTimeString }}. The first row that matched your alert criteria is: @@ -77,7 +85,7 @@ - Open in browser + {{ if .Reason }}View full analysis{{ else }}Open in browser{{ end }} diff --git a/runtime/pkg/email/templates/gen/alert_fail.html b/runtime/pkg/email/templates/gen/alert_fail.html index 2206092c5b71..9cce243b21f2 100644 --- a/runtime/pkg/email/templates/gen/alert_fail.html +++ b/runtime/pkg/email/templates/gen/alert_fail.html @@ -126,7 +126,18 @@
{{ .DisplayName }}
- {{ if eq (len .FailRows) 1 }} + {{ if .Reason }} + + +
Your alert triggered for {{ .ExecutionTimeString }}. The AI analysis found that the condition holds:
+ + + + +
{{ .Reason }}
+ + + {{ else if eq (len .FailRows) 1 }}
Your alert triggered for {{ .ExecutionTimeString }}. The first row that matched your alert criteria is:
@@ -194,7 +205,9 @@ - Open in browser + + {{ if .Reason }}View full analysis{{ else }}Open in browser{{ end }} + diff --git a/runtime/reconcilers/alert.go b/runtime/reconcilers/alert.go index 41ad356ce88b..9bec34660eaa 100644 --- a/runtime/reconcilers/alert.go +++ b/runtime/reconcilers/alert.go @@ -21,7 +21,6 @@ import ( "github.com/rilldata/rill/runtime/pkg/embedopen" "github.com/rilldata/rill/runtime/pkg/observability" "github.com/rilldata/rill/runtime/pkg/pbutil" - "github.com/rilldata/rill/runtime/queries" "go.opentelemetry.io/otel/attribute" "go.uber.org/zap" "golang.org/x/exp/slices" @@ -631,7 +630,7 @@ func (r *AlertReconciler) executeAllWrapped(ctx context.Context, self *runtimev1 // Evaluate watermark unless refs check failed. watermark := triggerTime if a.Spec.WatermarkInherit { - t, ok, err := r.computeInheritedWatermark(ctx, self.Meta.Refs) + t, ok, err := computeInheritedWatermark(ctx, r.C, self.Meta.Refs, alertQueryPriority) if err != nil { return err } @@ -734,18 +733,31 @@ func (r *AlertReconciler) executeSingleWrapped(ctx context.Context, self *runtim // Tag as alert execution so the metrics queries it runs are attributed to the "alert" source for billing. ctx = runtime.WithRequestSource(ctx, runtime.RequestSourceAlert) + props := a.Spec.ResolverProperties.AsMap() + args := map[string]any{ + "priority": alertQueryPriority, + "execution_time": executionTime, + "format": true, + "limit": rowsLimit + 1, // The extra row tells whether more rows matched than the notifications include. + } + claims := alertQueryClaims(a, adminMeta, nil) + if a.Spec.Resolver == "ai" { + // The ai resolver judges the prompt as the alert's condition, and returns a row if it holds. + props["is_alert"] = true + // Share the analysis, so every recipient's link can open it, like an AI report in creator mode. + args["create_shared_session"] = true + // The analysis runs in a session owned by the user the alert runs for (the parser requires one), with the permissions an AI report gets. + claims.UserID = a.Spec.GetQueryForUserId() + claims.Permissions = []runtime.Permission{runtime.ReadObjects, runtime.ReadMetrics, runtime.UseAI} + } + res, info, err := r.C.Runtime.Resolve(ctx, &runtime.ResolveOptions{ InstanceID: r.C.InstanceID, Resolver: a.Spec.Resolver, - ResolverProperties: a.Spec.ResolverProperties.AsMap(), + ResolverProperties: props, ProjectDeclared: false, // Alert templates never access project variables (the parser rejects references to them). - Args: map[string]any{ - "priority": alertQueryPriority, - "execution_time": executionTime, - "format": true, - "limit": rowsLimit + 1, // The extra row tells whether more rows matched than the notifications include. - }, - Claims: alertQueryClaims(a, adminMeta, nil), + Args: args, + Claims: claims, }) if err != nil { return nil, alertFailRows{}, fmt.Errorf("failed to resolve alert: %w", err) @@ -867,6 +879,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime // Alerts don't notify without admin metadata. // It's only missing for alerts created from an embed whose owner couldn't be resolved (see executeAll), and the alert is effectively paused. var msg *drivers.AlertStatus + var aiSessionID string if notify && adminMeta != nil { switch current.Result.Status { case runtimev1.AssertionStatus_ASSERTION_STATUS_PASS: @@ -895,12 +908,19 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime } msg = &drivers.AlertStatus{ - DisplayName: a.Spec.DisplayName, - ExecutionTime: executionTime, - Status: current.Result.Status, - FailColumns: failRows.columns, - FailRows: failRows.rows, - FailRowsTruncated: failRows.truncated, + DisplayName: a.Spec.DisplayName, + ExecutionTime: executionTime, + Status: current.Result.Status, + } + if a.Spec.Resolver == "ai" { + // An AI alert's fail row is the analysis's verdict: show its reason instead of the row, and link to the analysis. + failRow := current.Result.FailRow.AsMap() + msg.Reason, _ = failRow["reason"].(string) + aiSessionID, _ = failRow["ai_session_id"].(string) + } else { + msg.FailColumns = failRows.columns + msg.FailRows = failRows.rows + msg.FailRowsTruncated = failRows.truncated } case runtimev1.AssertionStatus_ASSERTION_STATUS_ERROR: if !a.Spec.NotifyOnError { @@ -978,6 +998,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime FailColumns: msg.FailColumns, FailRows: msg.FailRows, FailRowsTruncated: msg.FailRowsTruncated, + Reason: msg.Reason, ExecutionError: msg.ExecutionError, Attachment: attachment, AttachmentTooLarge: attachmentTooLarge, @@ -992,7 +1013,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime opts.UnsubscribeLink = recipientURLs.UnsubscribeURL } else if ok { // Use recipient-specific URLs (with magic token) - openLink, err := addExecutionTime(recipientURLs.OpenURL, executionTime) + openLink, err := alertOpenLink(recipientURLs.OpenURL, executionTime, aiSessionID) if err != nil { return fmt.Errorf("failed to build recipient open url: %w", err) } @@ -1023,7 +1044,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime if !ok { return fmt.Errorf("failed to get recipient URLs for anon user") } - openLink, err := addExecutionTime(urls.OpenURL, executionTime) + openLink, err := alertOpenLink(urls.OpenURL, executionTime, aiSessionID) if err != nil { return fmt.Errorf("failed to build recipient open url: %w", err) } @@ -1113,28 +1134,6 @@ func (r *AlertReconciler) exportAttachment(ctx context.Context, self *runtimev1. return attachment, false, nil } -// computeInheritedWatermark computes the inherited watermark for the alert. -// It returns false if the watermark could not be computed. -func (r *AlertReconciler) computeInheritedWatermark(ctx context.Context, refs []*runtimev1.ResourceName) (time.Time, bool, error) { - var t time.Time - for _, ref := range refs { - q := &queries.ResourceWatermark{ - ResourceKind: ref.Kind, - ResourceName: ref.Name, - } - err := r.C.Runtime.Query(ctx, r.C.InstanceID, q, alertQueryPriority) - if err != nil { - return t, false, fmt.Errorf("failed to resolve watermark for %s/%s: %w", ref.Kind, ref.Name, err) - } - - if q.Result != nil && (t.IsZero() || q.Result.Before(t)) { - t = *q.Result - } - } - - return t, !t.IsZero(), nil -} - // calculateAlertExecutionTimes calculates the execution times for an alert, taking into consideration the alert's intervals configuration and previous executions. // If the alert is not configured to run on intervals, it will return a slice containing only the current watermark. // If the alert should not be executed, it returns a skipError explaining why. @@ -1318,7 +1317,9 @@ func alertQueryForAttributes(a *runtimev1.Alert, adminMeta *drivers.AlertMetadat return nil } -func addExecutionTime(openURL string, executionTime time.Time) (string, error) { +// alertOpenLink builds a notification's open link, which opens the alert's data at the check's execution time. +// An AI alert's link also names the session of its analysis, which the open page redirects to. +func alertOpenLink(openURL string, executionTime time.Time, aiSessionID string) (string, error) { u, err := url.Parse(openURL) if err != nil { return "", err @@ -1328,6 +1329,9 @@ func addExecutionTime(openURL string, executionTime time.Time) (string, error) { return "", err } q.Set("execution_time", executionTime.UTC().Format(time.RFC3339)) + if aiSessionID != "" { + q.Set("session_id", aiSessionID) + } u.RawQuery = q.Encode() return u.String(), nil } diff --git a/runtime/reconcilers/alert_test.go b/runtime/reconcilers/alert_test.go index 63e498f1b6e4..a761342bc3c6 100644 --- a/runtime/reconcilers/alert_test.go +++ b/runtime/reconcilers/alert_test.go @@ -10,6 +10,7 @@ import ( runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1" "github.com/rilldata/rill/runtime" + "github.com/rilldata/rill/runtime/ai" "github.com/rilldata/rill/runtime/drivers" "github.com/rilldata/rill/runtime/parser" "github.com/rilldata/rill/runtime/pkg/email" @@ -1164,10 +1165,98 @@ notify: require.Empty(t, rt.Email.Sender.(*email.TestSender).Emails) } +func TestAIAlert(t *testing.T) { + rt, id := testruntime.NewInstanceWithOptions(t, testruntime.InstanceOptions{ + Files: map[string]string{ + "rill.yaml": `ai_connector: mock`, + // The mock AI echoes the prompt, which is never a valid verdict. + "connectors/mock.yaml": ` +type: connector +driver: mock_ai +`, + "models/orders.sql": ` +SELECT '2026-10-01T00:00:00Z'::TIMESTAMP AS __time, 'VisibleLand' AS country, 100 AS revenue +UNION ALL +SELECT '2026-10-02T00:00:00Z'::TIMESTAMP AS __time, 'HiddenLand' AS country, 900 AS revenue +`, + "metrics/orders_mv.yaml": ` +version: 1 +type: metrics_view +model: orders +timeseries: __time +dimensions: +- column: country +measures: +- name: revenue + expression: SUM(revenue) +security: + access: true + row_filter: country = '{{ .user.country }}' +`, + "explores/orders.yaml": ` +type: explore +metrics_view: orders_mv +`, + "alerts/a1.yaml": ` +type: alert +display_name: Orders from HiddenLand +refresh: + cron: 0 * * * * +watermark: inherit +data: + ai: + prompt: There are orders from HiddenLand + explore: orders +for: + user_id: owner-1 +on_error: true +notify: + email: + recipients: + - somebody@example.com +`, + }, + AdminService: &alertAdmin{queryForAttributes: map[string]any{"country": "VisibleLand"}}, + }) + testruntime.ReconcileParserAndWait(t, rt, id) + + // The check runs at the watermark of the explore's metrics view. + // Without a valid verdict, it ends in an error instead of a pass or fail, and the error is notified. + a1 := testruntime.GetResource(t, rt, id, runtime.ResourceKindAlert, "a1").GetAlert() + require.Len(t, a1.State.ExecutionHistory, 1) + require.Equal(t, time.Date(2026, 10, 2, 0, 0, 1, 0, time.UTC), a1.State.ExecutionHistory[0].ExecutionTime.AsTime()) + res := a1.State.ExecutionHistory[0].Result + require.Equal(t, runtimev1.AssertionStatus_ASSERTION_STATUS_ERROR, res.Status) + require.Contains(t, res.ErrorMessage, "verdict") + emails := rt.Email.Sender.(*email.TestSender).Emails + require.Len(t, emails, 1) + require.Contains(t, emails[0].Body, "verdict") + + // The analysis ran in a session owned by the alert's "for" user, and only saw that user's rows + catalog, release, err := rt.Catalog(t.Context(), id) + require.NoError(t, err) + defer release() + sessions, err := catalog.FindAISessions(t.Context(), "owner-1", "") + require.NoError(t, err) + require.Len(t, sessions, 1) + messages, err := catalog.FindAIMessages(t.Context(), sessions[0].ID) + require.NoError(t, err) + var summary string + for _, m := range messages { + if m.Tool == ai.QueryMetricsViewSummaryName && m.Type == string(ai.MessageTypeResult) { + summary = m.Content + } + } + require.Contains(t, summary, "VisibleLand") + require.NotContains(t, summary, "HiddenLand") +} + // alertAdmin is an admin service that returns alert metadata the way the admin service does for alerts that aren't created from an embed: // email recipients get an open and an unsubscribe link, and anonymous recipients (e.g. Slack) get an open and an edit link. +// The alert's "for" user resolves to queryForAttributes. type alertAdmin struct { drivers.AdminService // Not implemented; calls to methods that are not overridden panic + queryForAttributes map[string]any } func (a *alertAdmin) GetConfig(ctx context.Context) (*drivers.Config, error) { @@ -1182,5 +1271,5 @@ func (a *alertAdmin) GetAlertMetadata(ctx context.Context, alertName, ownerID st if anonRecipients { urls[""] = drivers.AlertURLs{OpenURL: "https://example.com/open", EditURL: "https://example.com/edit"} } - return &drivers.AlertMetadata{RecipientURLs: urls}, nil + return &drivers.AlertMetadata{RecipientURLs: urls, QueryForAttributes: a.queryForAttributes}, nil } diff --git a/runtime/reconcilers/report.go b/runtime/reconcilers/report.go index 3c2b4e39fde9..9a33663369f4 100644 --- a/runtime/reconcilers/report.go +++ b/runtime/reconcilers/report.go @@ -16,7 +16,6 @@ import ( "github.com/rilldata/rill/runtime/pkg/embedopen" "github.com/rilldata/rill/runtime/pkg/observability" "github.com/rilldata/rill/runtime/pkg/pbutil" - "github.com/rilldata/rill/runtime/queries" "go.opentelemetry.io/otel/attribute" "go.uber.org/zap" "golang.org/x/exp/slices" @@ -422,7 +421,7 @@ func (r *ReportReconciler) executeAllWrapped(ctx context.Context, self *runtimev // Evaluate watermark unless refs check failed. watermark := triggerTime if rep.Spec.WatermarkInherit { - t, ok, err := r.computeInheritedWatermark(ctx, self.Meta.Refs) + t, ok, err := computeInheritedWatermark(ctx, r.C, self.Meta.Refs, reportQueryPriority) if err != nil { return false, err } @@ -997,42 +996,6 @@ func resolverProperties(spec *runtimev1.ReportSpec) map[string]any { return props } -// computeInheritedWatermark computes the inherited watermark for the report. -// It returns false if the watermark could not be computed. -func (r *ReportReconciler) computeInheritedWatermark(ctx context.Context, refs []*runtimev1.ResourceName) (time.Time, bool, error) { - var t time.Time - for _, ref := range refs { - // Explores (referenced by AI reports) inherit the watermark of their metrics view. - // Resolving the metrics view here instead of in the watermark query keeps the query's cache keyed on the metrics view's data. - if ref.Kind == runtime.ResourceKindExplore { - res, err := r.C.Get(ctx, ref, false) - if err != nil { - return t, false, fmt.Errorf("failed to get explore %q: %w", ref.Name, err) - } - spec := res.GetExplore().State.ValidSpec - if spec == nil { - return t, false, fmt.Errorf("explore %q is not valid", ref.Name) - } - ref = &runtimev1.ResourceName{Kind: runtime.ResourceKindMetricsView, Name: spec.MetricsView} - } - - q := &queries.ResourceWatermark{ - ResourceKind: ref.Kind, - ResourceName: ref.Name, - } - err := r.C.Runtime.Query(ctx, r.C.InstanceID, q, reportQueryPriority) - if err != nil { - return t, false, fmt.Errorf("failed to resolve watermark for %s/%s: %w", ref.Kind, ref.Name, err) - } - - if q.Result != nil && (t.IsZero() || q.Result.Before(t)) { - t = *q.Result - } - } - - return t, !t.IsZero(), nil -} - // calculateReportExecutionTimes calculates the execution times for a report, taking into consideration the report's intervals configuration and previous executions. // If the report is not configured to run on intervals, it will return a slice containing only the current watermark. // If the alert should not be executed, it returns a skipError explaining why. diff --git a/runtime/reconcilers/util.go b/runtime/reconcilers/util.go index 9a3681b70cd4..7d3f977a1f3a 100644 --- a/runtime/reconcilers/util.go +++ b/runtime/reconcilers/util.go @@ -12,6 +12,7 @@ import ( "github.com/rilldata/rill/runtime" "github.com/rilldata/rill/runtime/drivers" "github.com/rilldata/rill/runtime/parser" + "github.com/rilldata/rill/runtime/queries" "github.com/robfig/cron/v3" ) @@ -144,6 +145,41 @@ func nextRefreshTime(t time.Time, schedule *runtimev1.Schedule) (time.Time, erro return t2, nil } +// computeInheritedWatermark returns the earliest watermark of the refs of an alert or report, and false if none of them has one. +// Explores, which AI alerts and reports reference, inherit the watermark of their metrics view. +func computeInheritedWatermark(ctx context.Context, c *runtime.Controller, refs []*runtimev1.ResourceName, priority int) (time.Time, bool, error) { + var t time.Time + for _, ref := range refs { + // Resolving the explore's metrics view here instead of in the watermark query keeps the query's cache keyed on the metrics view's data. + if ref.Kind == runtime.ResourceKindExplore { + res, err := c.Get(ctx, ref, false) + if err != nil { + return t, false, fmt.Errorf("failed to get explore %q: %w", ref.Name, err) + } + spec := res.GetExplore().State.ValidSpec + if spec == nil { + return t, false, fmt.Errorf("explore %q is not valid", ref.Name) + } + ref = &runtimev1.ResourceName{Kind: runtime.ResourceKindMetricsView, Name: spec.MetricsView} + } + + q := &queries.ResourceWatermark{ + ResourceKind: ref.Kind, + ResourceName: ref.Name, + } + err := c.Runtime.Query(ctx, c.InstanceID, q, priority) + if err != nil { + return t, false, fmt.Errorf("failed to resolve watermark for %s/%s: %w", ref.Kind, ref.Name, err) + } + + if q.Result != nil && (t.IsZero() || q.Result.Before(t)) { + t = *q.Result + } + } + + return t, !t.IsZero(), nil +} + // exploreNameFromAnnotations extracts the explore name from resource annotations. // It checks the "explore" annotation first, then falls back to parsing the "web_open_path" annotation. // If neither is found, it returns fallback. diff --git a/runtime/reconcilers/util_test.go b/runtime/reconcilers/util_test.go index 25d1c8f6b023..ac18973c6b15 100644 --- a/runtime/reconcilers/util_test.go +++ b/runtime/reconcilers/util_test.go @@ -2,6 +2,7 @@ package reconcilers import ( "testing" + "time" "github.com/stretchr/testify/require" ) @@ -75,3 +76,32 @@ func TestExploreNameFromAnnotations(t *testing.T) { }) } } + +func TestAlertOpenLink(t *testing.T) { + executionTime := time.Date(2026, 10, 2, 9, 30, 0, 0, time.FixedZone("CEST", 2*60*60)) + tests := []struct { + name string + openURL string + aiSessionID string + want string + }{ + { + name: "criteria alert", + openURL: "https://ui.rilldata.com/org/project/-/alerts/a1/open?token=abc", + want: "https://ui.rilldata.com/org/project/-/alerts/a1/open?execution_time=2026-10-02T07%3A30%3A00Z&token=abc", + }, + { + name: "AI alert", + openURL: "https://ui.rilldata.com/org/project/-/alerts/a1/open?token=abc", + aiSessionID: "session-1", + want: "https://ui.rilldata.com/org/project/-/alerts/a1/open?execution_time=2026-10-02T07%3A30%3A00Z&session_id=session-1&token=abc", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := alertOpenLink(tt.openURL, executionTime, tt.aiSessionID) + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} diff --git a/runtime/resolvers/ai.go b/runtime/resolvers/ai.go index 944da521312b..ae64a86d24e0 100644 --- a/runtime/resolvers/ai.go +++ b/runtime/resolvers/ai.go @@ -36,7 +36,10 @@ type aiProps struct { Measures []string `mapstructure:"measures"` Where map[string]any `mapstructure:"where"` // IsReport indicates if the AI resolver is used for an automated report. - IsReport bool `mapstructure:"is_report"` + IsReport bool `mapstructure:"is_report"` + // IsAlert indicates if the AI resolver checks an AI alert's condition, which is the prompt. + // It then returns a row with the analysis's summary if the condition holds, and no rows if it doesn't. + IsAlert bool `mapstructure:"is_alert"` UnusedFields map[string]any `mapstructure:",remain"` } @@ -224,6 +227,7 @@ func (r *aiResolver) ResolveInteractive(ctx context.Context) (runtime.ResolverRe ComparisonTimeEnd: r.props.ComparisonTimeRange.End, DisableCharts: r.args.CreateSharedSession, // Disable charts if creating shared session IsReport: r.props.IsReport, + IsAlert: r.props.IsAlert, } routerArgs := &ai.RouterAgentArgs{ @@ -256,6 +260,29 @@ func (r *aiResolver) ResolveInteractive(ctx context.Context) (runtime.ResolverRe } } + // An AI alert returns a row if its condition holds, which the alert reconciler notifies like any alert's rows. + // The row's reason is the analysis's summary, whose numbers the analyst checked against its query results. + if r.props.IsAlert { + reason := alertReason(result.Response) + var rows []map[string]any + switch result.AlertOutcome { + case ai.AlertOutcomeMet: + rows = append(rows, map[string]any{"reason": reason, "ai_session_id": session.ID()}) + case ai.AlertOutcomeNotMet: + case ai.AlertOutcomeCannotDetermine: + return nil, fmt.Errorf("the AI analysis could not determine whether the condition holds: %s", reason) + default: + return nil, fmt.Errorf("the AI analysis returned no verdict on the condition") + } + schema := &runtimev1.StructType{ + Fields: []*runtimev1.StructType_Field{ + {Name: "reason", Type: &runtimev1.Type{Code: runtimev1.Type_CODE_STRING}}, + {Name: "ai_session_id", Type: &runtimev1.Type{Code: runtimev1.Type_CODE_STRING}}, + }, + } + return runtime.NewMapsResolverResult(rows, schema), nil + } + // Extract summary from the response (from tag or fallback to truncation) summary := extractSummary(result.Response) @@ -357,6 +384,8 @@ func (r *aiResolver) generateTitle() string { title := "AI Session" if r.props.IsReport { title = "Report" + } else if r.props.IsAlert { + title = "Alert" } title = fmt.Sprintf("%s - %s", title, r.args.ExecutionTime.Format(time.RFC822)) if r.props.Explore != "" { @@ -404,6 +433,22 @@ func lookupMetricsView(ctx context.Context, rt *runtime.Runtime, instanceID, nam return res, mv.State, nil } +// alertReasonMaxRunes is the length an AI alert's reason is cut to when the analysis has no summary, like an AI report's summary in its notification. +const alertReasonMaxRunes = 500 + +// alertReason returns the reason an AI alert gives for its outcome: the analysis's summary, +// or the start of the analysis if the model left out the tag. +func alertReason(response string) string { + if summary := extractSummary(response); summary != "" { + return summary + } + reason := []rune(strings.TrimSpace(response)) + if len(reason) > alertReasonMaxRunes { + return string(reason[:alertReasonMaxRunes-3]) + "..." + } + return string(reason) +} + // extractSummary extracts the summary from the tag in the AI response. // If no summary tag is found, it returns an empty string. func extractSummary(response string) string { diff --git a/runtime/resolvers/ai_test.go b/runtime/resolvers/ai_test.go new file mode 100644 index 000000000000..e3cff2b87bb3 --- /dev/null +++ b/runtime/resolvers/ai_test.go @@ -0,0 +1,21 @@ +package resolvers + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAlertReason(t *testing.T) { + // The summary is the reason + require.Equal(t, "Revenue dropped 40%.", alertReason("Revenue dropped 40%.\n\nIn detail, ...")) + + // Without a summary, a short analysis is the reason as is + require.Equal(t, "Revenue dropped 40%.", alertReason("\nRevenue dropped 40%.\n")) + + // and a long one is cut, without splitting a character + reason := alertReason(strings.Repeat("é", 600)) + require.Equal(t, strings.Repeat("é", alertReasonMaxRunes-3)+"...", reason) + require.Len(t, []rune(reason), alertReasonMaxRunes) +} diff --git a/web-admin/src/features/alerts/AlertDialogTest.svelte b/web-admin/src/features/alerts/AlertDialogTest.svelte new file mode 100644 index 000000000000..25dd74e48fe0 --- /dev/null +++ b/web-admin/src/features/alerts/AlertDialogTest.svelte @@ -0,0 +1,27 @@ + + + + + + + {}} + onCancel={() => {}} + /> + + + diff --git a/web-admin/src/features/alerts/alert-dialog.component.spec.ts b/web-admin/src/features/alerts/alert-dialog.component.spec.ts new file mode 100644 index 000000000000..ba31cce0cd8b --- /dev/null +++ b/web-admin/src/features/alerts/alert-dialog.component.spec.ts @@ -0,0 +1,313 @@ +import "@testing-library/jest-dom/vitest"; +import AlertDialogTest from "@rilldata/web-admin/features/alerts/AlertDialogTest.svelte"; +import { + getFilterChip, + mockPointerEventsForComponentTesting, + mockResizeObserverForComponentTesting, + useDashboardFetchMocksForComponentTests, + waitForBodyScrollCleanup, +} from "@rilldata/web-common/features/dashboards/filters/test/filter-test-utils"; +import { + type HoistedPageForComponentTests, + PageMockForComponentTests, +} from "@rilldata/web-common/features/dashboards/state-managers/loaders/test/PageMockForComponentTests.ts"; +import { + createAndExpression, + createInExpression, +} from "@rilldata/web-common/features/dashboards/stores/filter-utils"; +import { + AD_BIDS_EXPLORE_INIT, + AD_BIDS_EXPLORE_NAME, + AD_BIDS_IMPRESSIONS_MEASURE, + AD_BIDS_METRICS_INIT_WITH_TIME, + AD_BIDS_METRICS_NAME, + AD_BIDS_PUBLISHER_DIMENSION, + AD_BIDS_TIME_RANGE_SUMMARY, +} from "@rilldata/web-common/features/dashboards/stores/test-data/data"; +import { getRangeLabel } from "@rilldata/web-common/features/dashboards/time-controls/new-time-controls"; +import { m } from "@rilldata/web-common/lib/i18n/gen/messages"; +import { queryClient } from "@rilldata/web-common/lib/svelte-query/globalQueryClient"; +import { mockAnimationsForComponentTesting } from "@rilldata/web-common/lib/test/mock-animations"; +import { + V1ExportFormat, + type V1AlertSpec, + type V1MetricsViewAggregationRequest, + V1Operation, +} from "@rilldata/web-common/runtime-client"; +import { + RUNTIME_CONTEXT_KEY, + RuntimeClient, +} from "@rilldata/web-common/runtime-client/v2"; +import type { ActionResult } from "@sveltejs/kit"; +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/svelte"; +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +// jsdom has no matchMedia, which the dashboard components read when they are imported; web-common's test setup stubs it the same way. +vi.hoisted(() => { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: (query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }), + }); +}); + +// The SvelteKit mocks have to be declared in the spec file, since `vi.mock` is hoisted per file. +const hoistedPage: HoistedPageForComponentTests = vi.hoisted(() => ({}) as any); +const editAlert = vi.hoisted(() => + vi.fn< + (request: { + data: { + options: { + resolver?: string; + resolverProperties?: Record; + queryName?: string; + queryArgsJson?: string; + metricsViewName?: string; + refreshCron?: string; + exportAttach?: boolean; + }; + }; + }) => Promise + >(), +); + +vi.stubEnv("TZ", "UTC"); + +vi.mock("$app/navigation", () => { + return { + goto: (url, opts) => hoistedPage.goto(url, opts), + afterNavigate: (cb) => hoistedPage.afterNavigate(cb), + onNavigate: () => {}, + // superforms registers a navigation guard for tainted forms as soon as it is created. + beforeNavigate: () => {}, + }; +}); +vi.mock("$app/forms", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + // superforms reads its validation result back from the page, so hand it to the page mock. + applyAction: (result: ActionResult) => { + hoistedPage.applyAction(result); + return Promise.resolve(); + }, + }; +}); +vi.mock("$app/state", async () => { + return { + page: ( + await import( + "@rilldata/web-common/features/dashboards/state-managers/loaders/test/page-state.mock.svelte" + ) + ).pageStateMock, + }; +}); +vi.mock("$app/stores", () => { + return { + page: hoistedPage, + navigating: { + subscribe: (run: (value: null) => void) => { + run(null); + return () => {}; + }, + }, + }; +}); +// The dialog saves through the admin API, which component tests cannot reach. +vi.mock("@rilldata/web-admin/client", async () => { + const { readable } = await import("svelte/store"); + return { + getAdminServiceListBookmarksQueryOptions: () => ({}), + createAdminServiceGetCurrentUser: () => + readable({ data: { user: { email: "user@rilldata.com" } } }), + createAdminServiceSearchProjectUsers: () => readable({ data: undefined }), + createAdminServiceCreateAlert: () => + readable({ mutateAsync: vi.fn(), error: null }), + createAdminServiceEditAlert: () => + readable({ mutateAsync: editAlert, error: null }), + createAdminServiceDeleteAlert: () => + readable({ mutateAsync: vi.fn(), error: null }), + }; +}); + +const AIConditionText = "Impressions dropped against the previous weeks"; + +/** A criteria alert created in the dialog, checked whenever its data refreshes. */ +function getCriteriaAlertSpec() { + const queryArgs: V1MetricsViewAggregationRequest = { + metricsView: AD_BIDS_METRICS_NAME, + measures: [{ name: AD_BIDS_IMPRESSIONS_MEASURE }], + dimensions: [], + where: createAndExpression([ + createInExpression(AD_BIDS_PUBLISHER_DIMENSION, ["Facebook"]), + ]), + timeRange: { isoDuration: "P7D", timeZone: "UTC" }, + having: createAndExpression([ + { + cond: { + op: V1Operation.OPERATION_GT, + exprs: [{ ident: AD_BIDS_IMPRESSIONS_MEASURE }, { val: 10 }], + }, + }, + ]), + }; + return { + displayName: "Impressions alert", + resolver: "legacy_metrics", + resolverProperties: { + query_name: "MetricsViewAggregation", + query_args_json: JSON.stringify(queryArgs), + }, + notifiers: [ + { connector: "email", properties: { recipients: ["user@rilldata.com"] } }, + ], + exportAttach: true, + exportFormat: V1ExportFormat.EXPORT_FORMAT_CSV, + annotations: { + admin_owner_user_id: "owner-1", + web_open_path: `/explore/${AD_BIDS_EXPLORE_NAME}`, + }, + } satisfies V1AlertSpec; +} + +/** The resolver properties the dialog writes for the criteria alert's data and the AI condition. */ +const AIAlertResolverProperties = { + prompt: AIConditionText, + explore: AD_BIDS_EXPLORE_NAME, + measures: [AD_BIDS_IMPRESSIONS_MEASURE], + where: { + cond: { + op: "and", + exprs: [ + { + cond: { + op: "in", + exprs: [{ name: AD_BIDS_PUBLISHER_DIMENSION }, { val: "Facebook" }], + }, + }, + ], + }, + }, + time_range: { expression: "P7D" }, + time_zone: "UTC", +}; + +async function openEditDialog(alertSpec: V1AlertSpec) { + render(AlertDialogTest, { + props: { alertSpec }, + context: new Map([ + ["$$_queryClient", queryClient], + [ + RUNTIME_CONTEXT_KEY, + new RuntimeClient({ host: "http://localhost", instanceId: "test" }), + ], + ]), + }); + // The filters and the time range are applied once the metrics view loads. + await waitFor(() => { + expect(getFilterChip(AD_BIDS_PUBLISHER_DIMENSION)).toBeVisible(); + expect( + screen.getByLabelText(m.dashboard_select_time_range()), + ).toHaveTextContent(getRangeLabel("P7D")); + }); +} + +async function clickButton(name: string) { + await act(() => screen.getByRole("button", { name }).click()); +} + +async function getSavedOptions() { + await waitFor(() => expect(editAlert).toHaveBeenCalledOnce()); + return editAlert.mock.calls[0][0].data.options; +} + +describe("the alert dialog", () => { + mockAnimationsForComponentTesting(); + mockPointerEventsForComponentTesting(); + mockResizeObserverForComponentTesting(); + const mocks = useDashboardFetchMocksForComponentTests(); + + // jsdom runs a `requestSubmit()` from inside a submit handler, which browsers ignore (see ScheduledReportDialog.spec.ts). + beforeAll(() => { + vi.spyOn(HTMLFormElement.prototype, "requestSubmit").mockImplementation( + () => {}, + ); + }); + + beforeEach(() => { + new PageMockForComponentTests(hoistedPage); + editAlert.mockReset(); + editAlert.mockResolvedValue({}); + + mocks.mockMetricsView(AD_BIDS_METRICS_NAME, AD_BIDS_METRICS_INIT_WITH_TIME); + mocks.mockMetricsExplore( + AD_BIDS_EXPLORE_NAME, + AD_BIDS_METRICS_INIT_WITH_TIME, + AD_BIDS_EXPLORE_INIT, + ); + mocks.mockTimeRangeSummary( + AD_BIDS_METRICS_NAME, + AD_BIDS_TIME_RANGE_SUMMARY.timeRangeSummary!, + ); + mocks.mockResolvedRillTimes(AD_BIDS_METRICS_NAME, { + P7D: { start: "2022-03-24T00:00:00Z", end: "2022-03-31T00:00:00Z" }, + }); + + localStorage.clear(); + sessionStorage.clear(); + queryClient.clear(); + }); + + afterAll(waitForBodyScrollCleanup); + + it("turns a criteria alert into an AI alert over the same data, checked on a schedule", async () => { + await openEditDialog(getCriteriaAlertSpec()); + + await clickButton(m.alert_form_condition_type_ai()); + await clickButton(m.alert_form_next()); + await fireEvent.input( + screen.getByPlaceholderText(m.alert_form_ai_condition_placeholder()), + { target: { value: AIConditionText } }, + ); + await clickButton(m.alert_form_next()); + // AI alerts can't be checked whenever their data refreshes, and have no rows to attach. + expect( + screen.getByRole("button", { name: m.alert_form_trigger_data_refresh() }), + ).toBeDisabled(); + expect(screen.queryByLabelText(m.alert_form_attach_rows())).toBeNull(); + await clickButton(m.alert_form_update()); + + const options = await getSavedOptions(); + expect(options).toMatchObject({ + resolver: "ai", + resolverProperties: AIAlertResolverProperties, + metricsViewName: AD_BIDS_METRICS_NAME, + exportAttach: false, + }); + expect(options.queryName).toBeUndefined(); + expect(options.queryArgsJson).toBeUndefined(); + expect(options.refreshCron).toMatch(/^\d+ \d+ \* \* \d$/); + }); +}); diff --git a/web-admin/src/features/alerts/history/AlertHistoryTableCompositeCell.svelte b/web-admin/src/features/alerts/history/AlertHistoryTableCompositeCell.svelte index 2fe7ef8158b2..be4c0353834d 100644 --- a/web-admin/src/features/alerts/history/AlertHistoryTableCompositeCell.svelte +++ b/web-admin/src/features/alerts/history/AlertHistoryTableCompositeCell.svelte @@ -12,6 +12,13 @@ export let timeZone: string; export let currentExecution: V1AlertExecution | null; export let result: V1AssertionResult; + + // The fail row of an AI alert's check is the AI's verdict: its reason and the conversation behind it. + $: reason = + result.status === V1AssertionStatus.ASSERTION_STATUS_FAIL && + result.failRow?.ai_session_id + ? String(result.failRow.reason ?? "") + : "";
@@ -22,5 +29,7 @@ {#if result.status === V1AssertionStatus.ASSERTION_STATUS_ERROR} {result.errorMessage} + {:else if reason} + {reason} {/if}
diff --git a/web-admin/src/features/alerts/metadata/AlertMetadata.svelte b/web-admin/src/features/alerts/metadata/AlertMetadata.svelte index 9fbd08626af9..22f737b611b1 100644 --- a/web-admin/src/features/alerts/metadata/AlertMetadata.svelte +++ b/web-admin/src/features/alerts/metadata/AlertMetadata.svelte @@ -22,6 +22,11 @@ formatRefreshSchedule, } from "@rilldata/web-admin/features/scheduled-reports/metadata/utils.ts"; import { IconButton } from "@rilldata/web-common/components/button"; + import { + type AIAlertResolverProps, + getAlertAggregationRequest, + isAIAlertSpec, + } from "@rilldata/web-common/features/alerts/ai-alert-utils"; import { AlertNotifyRowsLimitDefault } from "@rilldata/web-common/features/alerts/form-utils"; import * as DropdownMenu from "@rilldata/web-common/components/dropdown-menu"; import ThreeDot from "@rilldata/web-common/components/icons/ThreeDot.svelte"; @@ -30,7 +35,6 @@ import { getRuntimeServiceListResourcesQueryKey, V1ExportFormat, - type V1MetricsViewAggregationRequest, } from "@rilldata/web-common/runtime-client"; import { useRuntimeClient } from "@rilldata/web-common/runtime-client/v2"; import { createQuery, useQueryClient } from "@tanstack/svelte-query"; @@ -41,7 +45,10 @@ import { convertStateParamToUrlParams } from "@rilldata/web-common/features/dashboards/url-state/augment-url-params.ts"; import { convertFilterParamToExpression } from "@rilldata/web-common/features/dashboards/url-state/filters/converters.ts"; import { ExploreStateURLParams } from "@rilldata/web-common/features/dashboards/url-state/url-params.ts"; - import { getMappedExploreUrlQueryOptions } from "@rilldata/web-common/features/explore-mappers/url-mappers/get-mapped-url.ts"; + import { + getMappedExploreUrlQueryOptions, + type MappedExploreUrlSource, + } from "@rilldata/web-common/features/explore-mappers/url-mappers/get-mapped-url.ts"; import { getDashboardPath } from "@rilldata/web-common/features/explore-mappers/utils"; export let organization: string; @@ -83,9 +90,11 @@ $: queryName = alertSpec?.queryName || (alertSpec?.resolverProperties?.query_name as string); - $: metricsViewAggregationRequest = JSON.parse( - queryArgsJson, - ) as V1MetricsViewAggregationRequest; + // An AI alert's resolver properties narrow its data the way a criteria alert's query does, and its condition replaces the criteria. + $: isAIAlert = !!alertSpec && isAIAlertSpec(alertSpec); + $: metricsViewAggregationRequest = alertSpec + ? getAlertAggregationRequest(alertSpec, metricsViewName ?? "") + : undefined; $: snoozeLabel = humaniseAlertSnoozeOption(alertSpec); @@ -111,19 +120,29 @@ } } + // AI alerts link to the explore they analyze, with the alert's resolver properties applied. + $: exploreUrlSource = ( + isAIAlert + ? { + type: "ai", + exploreName: $exploreName.data ?? "", + props: alertSpec?.resolverProperties as AIAlertResolverProps, + } + : { + type: "query", + request: { + exploreName: $exploreName.data ?? "", + queryName, + queryArgsJson, + }, + options: { + exploreProtoState: alertSpec?.annotations?.web_open_state, + }, + } + ) as MappedExploreUrlSource; $: exploreUrlQueryOptions = getMappedExploreUrlQueryOptions( runtimeClient, - { - type: "query", - request: { - exploreName: $exploreName.data ?? "", - queryName, - queryArgsJson, - }, - options: { - exploreProtoState: alertSpec?.annotations?.web_open_state, - }, - }, + exploreUrlSource, { organization, project, embedded }, ); // Until the explore name loads, the url would fall back to the metrics view's name. @@ -246,8 +265,8 @@ - - {#if metricsViewAggregationRequest?.dimensions?.length} + + {#if metricsViewAggregationRequest?.dimensions?.length && !isAIAlert}
{m.alert_rows_in_notifications()} @@ -295,11 +314,20 @@ comparisonTimeRange={metricsViewAggregationRequest?.comparisonTimeRange} /> - - + + {#if isAIAlert} +
+ {m.alert_condition()} + + {alertSpec.resolverProperties?.prompt} + +
+ {:else} + + {/if} {#if slackNotifier} diff --git a/web-admin/src/features/alerts/selectors.ts b/web-admin/src/features/alerts/selectors.ts index db5e6ce7805b..cabc0fb39e14 100644 --- a/web-admin/src/features/alerts/selectors.ts +++ b/web-admin/src/features/alerts/selectors.ts @@ -1,4 +1,8 @@ import { createAdminServiceSearchProjectUsers } from "@rilldata/web-admin/client"; +import { + type AIAlertResolverProps, + isAIAlertSpec, +} from "@rilldata/web-common/features/alerts/ai-alert-utils"; import { ResourceKind } from "@rilldata/web-common/features/entity-management/resource-selectors"; import { getExploreName } from "@rilldata/web-common/features/explore-mappers/utils"; import { @@ -54,6 +58,10 @@ export function getAlertDashboardName(alertSpec: V1AlertSpec): string { if (alertSpec.annotations.web_open_path) return getExploreName(alertSpec.annotations.web_open_path); + // AI alerts name the explore the AI looks at in the resolver's properties. + if (isAIAlertSpec(alertSpec)) + return (alertSpec.resolverProperties as AIAlertResolverProps).explore ?? ""; + const queryArgsJson = JSON.parse( (alertSpec.resolverProperties.query_args_json as string) || alertSpec.queryArgsJson || diff --git a/web-admin/src/routes/[organization]/[project]/-/alerts/[alert]/open/+page.ts b/web-admin/src/routes/[organization]/[project]/-/alerts/[alert]/open/+page.ts index d04d6f537f38..ca1ef2ae1e33 100644 --- a/web-admin/src/routes/[organization]/[project]/-/alerts/[alert]/open/+page.ts +++ b/web-admin/src/routes/[organization]/[project]/-/alerts/[alert]/open/+page.ts @@ -1,15 +1,29 @@ import { getOpenExploreName } from "@rilldata/web-admin/features/scheduled-reports/open/open-urls"; +import { redirect } from "@sveltejs/kit"; export async function load({ parent, url, params }) { const { alert } = await parent(); const alertSpec = alert?.alert?.spec ?? {}; + const token = url.searchParams.get("token"); + + // AI alerts open the AI conversation behind the check that fired, as AI reports do. + // The runtime adds the session ID to the open link, so the link opens the conversation whatever the alert's condition is now. + // Links without one open the dashboard, or the alert's page if the alert has no query (see AlertOpen). + // In creator mode the link also carries a magic token, which grants read access to the shared conversation and must be forwarded. + const sessionId = url.searchParams.get("session_id"); + if (sessionId) { + const path = `/${params.organization}/${params.project}/-/ai/${sessionId}`; + const search = token ? new URLSearchParams({ token }).toString() : ""; + redirect(307, search ? `${path}?${search}` : path); + } + return { organization: params.organization, project: params.project, alertId: params.alert, alertSpec, executionTime: url.searchParams.get("execution_time"), - token: url.searchParams.get("token"), + token, exploreName: getOpenExploreName(alertSpec), }; } diff --git a/web-common/src/features/alerts/AlertForm.svelte b/web-common/src/features/alerts/AlertForm.svelte index c6aa0b8bcd81..ef1a9abc861e 100644 --- a/web-common/src/features/alerts/AlertForm.svelte +++ b/web-common/src/features/alerts/AlertForm.svelte @@ -17,6 +17,12 @@ import { getAlertDashboardName } from "@rilldata/web-admin/features/alerts/selectors.ts"; import { DialogTitle } from "@rilldata/web-common/components/dialog"; import * as DialogTabs from "@rilldata/web-common/components/dialog/tabs"; + import { + AIConditionType, + generateAIAlertName, + getAIAlertResolverProps, + getAlertAggregationRequest, + } from "@rilldata/web-common/features/alerts/ai-alert-utils.ts"; import { getNewAlertInitialFormValues } from "@rilldata/web-common/features/alerts/create-alert-utils.ts"; import AlertDialogCriteriaTab from "@rilldata/web-common/features/alerts/criteria-tab/AlertDialogCriteriaTab.svelte"; import AlertDialogDataTab from "@rilldata/web-common/features/alerts/data-tab/AlertDialogDataTab.svelte"; @@ -67,13 +73,12 @@ export let showEmbedOwnerEmail: boolean; const isEmbedded = EmbedStore.isEmbedded(); - // Alerts created from an embed run as the creator, and can't be sent to Slack, + // Alerts created from an embed run as the creator, can't be sent to Slack and can't use an AI condition, // including when an admin edits one outside of the embed. - const slackAllowed = - !isEmbedded && - !( - props.mode === "edit" && props.alertSpec.annotations?.admin_embed_owner_id - ); + const isCreatedFromEmbed = + isEmbedded || + (props.mode === "edit" && + !!props.alertSpec.annotations?.admin_embed_owner_id); const runtimeClient = useRuntimeClient(); @@ -109,12 +114,9 @@ props.mode === "create" ? get(page).url.searchParams : getFilterParamsFromAggregationRequest( - JSON.parse( - props.alertSpec.queryArgsJson || - (props.alertSpec.resolverProperties?.query_args_json as - | string - | undefined) || - "{}", + getAlertAggregationRequest( + props.alertSpec, + initialValues.metricsViewName, ), ), ); @@ -166,6 +168,13 @@ values.dayOfMonth, ); + const isAIAlert = values.conditionType === AIConditionType; + // Keyed by the metrics view's resource name, which can differ in casing from the explore's reference. + const where = + expressionFilterManager.topLevelJoiner.expr[ + expressionFilterManager.metricsViewsProvider.metricsViewNames[0] + ]; + await $mutation.mutateAsync({ org: provider.organization, project: provider.project, @@ -173,17 +182,25 @@ data: { options: { displayName: values.name, - queryName: "MetricsViewAggregation", - queryArgsJson: JSON.stringify( - getAlertQueryArgsFromFormValues( - values, - // Keyed by the metrics view's resource name, which can differ in casing from the explore's reference. - expressionFilterManager.topLevelJoiner.expr[ - expressionFilterManager.metricsViewsProvider.metricsViewNames[0] - ], - timeFilterManager, - ), - ), + ...(isAIAlert + ? { + resolver: "ai", + resolverProperties: getAIAlertResolverProps( + values, + where, + timeFilterManager, + ), + } + : { + queryName: "MetricsViewAggregation", + queryArgsJson: JSON.stringify( + getAlertQueryArgsFromFormValues( + values, + where, + timeFilterManager, + ), + ), + }), metricsViewName: values.metricsViewName, notifyRowsLimit: getNotifyRowsLimitFromFormValues(values), slackChannels: values.enableSlackNotification @@ -201,8 +218,11 @@ isEmbedded && showEmbedOwnerEmail ? values.embedOwnerEmail.trim() : undefined, - // Attachments are only sent with emails, and the export options only apply to attachments - ...(values.enableEmailNotification && values.exportAttach + // Attachments are only sent with emails, and the export options only apply to attachments. + // An AI alert has no rows to attach. + ...(values.enableEmailNotification && + values.exportAttach && + !isAIAlert ? { exportAttach: true, exportFormat: values.exportFormat, @@ -210,7 +230,9 @@ exportIncludeHeader: values.exportIncludeHeader, } : { exportAttach: false }), - refreshCron: !values.refreshWhenDataRefreshes ? refreshCron : "", // for testing: "* * * * *" + // An AI alert is always checked on a schedule (see AlertDialogDeliveryTab). + refreshCron: + isAIAlert || !values.refreshWhenDataRefreshes ? refreshCron : "", // for testing: "* * * * *" refreshTimeZone: values.timeZone, renotify: !!values.snooze, renotifyAfterSeconds: values.snooze ? Number(values.snooze) : 0, @@ -292,13 +314,16 @@ return; } // if the user came to the delivery tab and name was not changed then auto generate it - const name = generateAlertName( - $form, - timeFilterManager.showComparison - ? timeFilterManager.comparisonTimeRange - : undefined, - metricsViewSpec, - ); + const name = + $form.conditionType === AIConditionType + ? generateAIAlertName($form.aiCondition) + : generateAlertName( + $form, + timeFilterManager.showComparison + ? timeFilterManager.comparisonTimeRange + : undefined, + metricsViewSpec, + ); if (!name) return; $form.name = name; } @@ -341,6 +366,7 @@ {expressionFilterManager} {timeFilterManager} {dashboardConfigProvider} + aiConditionAllowed={!isCreatedFromEmbed} /> @@ -356,7 +382,7 @@ {exploreName} {provider} {showEmbedOwnerEmail} - {slackAllowed} + slackAllowed={!isCreatedFromEmbed} />
diff --git a/web-common/src/features/alerts/AlertFormDataWrapper.svelte b/web-common/src/features/alerts/AlertFormDataWrapper.svelte index fab2159cf40b..c1639b68a74c 100644 --- a/web-common/src/features/alerts/AlertFormDataWrapper.svelte +++ b/web-common/src/features/alerts/AlertFormDataWrapper.svelte @@ -77,12 +77,16 @@ hasSavedEmbedOwnerEmail || (isEmbedded && !!$embedOpenUrlQuery.data), ); + // The form reads its initial values once, so it waits for the explore's metrics view: + // an AI alert's resolver properties don't name it, and the alert's YAML refs it. + // A criteria alert waits too: without its explore, the form can't load the alert's filters, and saving would drop them. const initialValues = $derived.by(() => { const exploreState = $exploreStateStore; if ( provider.isLoading || (isEmbedded && $embedOpenUrlQuery.isPending) || - !exploreState + !exploreState || + !metricsViewName ) { return undefined; } diff --git a/web-common/src/features/alerts/ai-alert-utils.spec.ts b/web-common/src/features/alerts/ai-alert-utils.spec.ts new file mode 100644 index 000000000000..654df3621c39 --- /dev/null +++ b/web-common/src/features/alerts/ai-alert-utils.spec.ts @@ -0,0 +1,103 @@ +import { + generateAIAlertName, + getAIAlertResolverProps, + getAlertAggregationRequest, +} from "@rilldata/web-common/features/alerts/ai-alert-utils"; +import type { AlertFormValues } from "@rilldata/web-common/features/alerts/form-utils"; +import { + createAndExpression, + createInExpression, +} from "@rilldata/web-common/features/dashboards/stores/filter-utils"; +import type { TimeFilterManager } from "@rilldata/web-common/features/dashboards/time-controls/TimeFilterManager.svelte.ts"; +import { describe, expect, it } from "vitest"; + +const Condition = "Revenue dropped unusually against the previous weeks"; + +function getFormValues(overrides: Partial): AlertFormValues { + return { + aiCondition: ` ${Condition} `, + exploreName: "orders", + measure: "", + splitByDimension: "", + ...overrides, + } as AlertFormValues; +} + +function getTimeFilterManager( + overrides: Partial, +): TimeFilterManager { + return { + requestedTimeRange: undefined, + timeDimension: undefined, + timeZone: "UTC", + ...overrides, + } as TimeFilterManager; +} + +describe("getAIAlertResolverProps", () => { + it("writes the condition and the data it is narrowed to, which the alert reads back", () => { + const where = createAndExpression([createInExpression("country", ["ES"])]); + const props = getAIAlertResolverProps( + getFormValues({ measure: "revenue", splitByDimension: "country" }), + where, + getTimeFilterManager({ + requestedTimeRange: "4W as of watermark/D+1D", + timeDimension: "ordered_at", + timeZone: "Europe/Madrid", + }), + ); + expect(props).toEqual({ + prompt: Condition, + explore: "orders", + measures: ["revenue"], + dimensions: ["country"], + where: { + cond: { + op: "and", + exprs: [ + { cond: { op: "in", exprs: [{ name: "country" }, { val: "ES" }] } }, + ], + }, + }, + // The analyst queries the primary time dimension, so a secondary one the filter holds is left out. + time_range: { expression: "4W as of watermark/D+1D" }, + time_zone: "Europe/Madrid", + }); + + expect( + getAlertAggregationRequest( + { resolver: "ai", resolverProperties: props }, + "orders_mv", + ), + ).toEqual({ + metricsView: "orders_mv", + measures: [{ name: "revenue" }], + dimensions: [{ name: "country" }], + where, + timeRange: { + expression: "4W as of watermark/D+1D", + timeZone: "Europe/Madrid", + }, + }); + }); + + it("leaves out the data that does not narrow anything", () => { + expect( + getAIAlertResolverProps( + getFormValues({}), + createAndExpression([]), + getTimeFilterManager({}), + ), + ).toEqual({ prompt: Condition, explore: "orders" }); + }); +}); + +describe("generateAIAlertName", () => { + it("shortens a long condition to a single line", () => { + const name = generateAIAlertName(`${Condition},\n ${Condition}`); + expect(name).toHaveLength(60); + expect(name).toBe( + "Revenue dropped unusually against the previous weeks, Reven…", + ); + }); +}); diff --git a/web-common/src/features/alerts/ai-alert-utils.ts b/web-common/src/features/alerts/ai-alert-utils.ts new file mode 100644 index 000000000000..362370f60111 --- /dev/null +++ b/web-common/src/features/alerts/ai-alert-utils.ts @@ -0,0 +1,100 @@ +import type { AlertFormValues } from "@rilldata/web-common/features/alerts/form-utils"; +import { convertV1ExpressionToMapstructure } from "@rilldata/web-common/features/components/charts/custom/expression-utils"; +import { sanitiseExpression } from "@rilldata/web-common/features/dashboards/stores/filter-utils"; +import type { TimeFilterManager } from "@rilldata/web-common/features/dashboards/time-controls/TimeFilterManager.svelte.ts"; +import type { AIResolverProps } from "@rilldata/web-common/features/explore-mappers/map-ai-resolver-props-to-metrics-resolver-query"; +import { mapResolverExpressionToV1Expression } from "@rilldata/web-common/features/explore-mappers/map-resolver-expression-to-v1-expression"; +import { + convertRequestKeysToCamelCase, + getSpecQuery, +} from "@rilldata/web-common/features/explore-mappers/utils"; +import type { + V1AlertSpec, + V1Expression, + V1MetricsViewAggregationRequest, +} from "@rilldata/web-common/runtime-client"; +import type { Expression } from "@rilldata/web-common/runtime-client/gen/resolvers/metrics/schema.ts"; + +// An alert fires on criteria over a measure, or when the AI analyst judges that a condition written in words holds (an AI alert). +export const CriteriaConditionType = "criteria"; +export const AIConditionType = "ai"; +export type AlertConditionType = + | typeof CriteriaConditionType + | typeof AIConditionType; + +// The properties of the `ai` resolver that an AI alert runs; the prompt is its condition. +export type AIAlertResolverProps = AIResolverProps & { prompt: string }; + +// AI alerts run the `ai` resolver, which judges the condition instead of evaluating criteria. +export function isAIAlertSpec(alertSpec: V1AlertSpec): boolean { + return alertSpec.resolver === "ai"; +} + +/** + * Maps the alert dialog's values to the properties of the `ai` resolver. + * The data tab's measure, dimension, filters and time range narrow what the AI looks at; empty ones are left out. + */ +export function getAIAlertResolverProps( + values: AlertFormValues, + where: V1Expression | undefined, + timeFilterManager: TimeFilterManager, +): AIAlertResolverProps { + const props: AIAlertResolverProps = { + prompt: values.aiCondition.trim(), + explore: values.exploreName, + }; + if (values.measure) props.measures = [values.measure]; + if (values.splitByDimension) props.dimensions = [values.splitByDimension]; + + const sanitisedWhere = sanitiseExpression(where); + if (sanitisedWhere) { + props.where = convertV1ExpressionToMapstructure( + sanitisedWhere, + ) as Expression; + } + + // The resolver evaluates the time filter's range with rill time, + // which also reads the legacy presets the filter can hold, such as P7D or rill-PDC. + // It leaves out the time dimension, since the analyst only gets the range's start and end and queries the primary time dimension. + const { requestedTimeRange, timeZone } = timeFilterManager; + if (requestedTimeRange) { + props.time_range = { expression: requestedTimeRange }; + props.time_zone = timeZone; + } + + return props; +} + +/** + * Returns the aggregation request that the alert dialog and the alert page read an alert's data from: + * a criteria alert's query, or the request that an AI alert's resolver properties narrow the data to. + */ +export function getAlertAggregationRequest( + alertSpec: V1AlertSpec, + metricsViewName: string, +): V1MetricsViewAggregationRequest { + if (!isAIAlertSpec(alertSpec)) { + return JSON.parse(getSpecQuery(alertSpec).queryArgsJson || "{}"); + } + + const props = (alertSpec.resolverProperties ?? {}) as AIAlertResolverProps; + return { + metricsView: metricsViewName, + measures: props.measures?.map((name) => ({ name })) ?? [], + dimensions: props.dimensions?.map((name) => ({ name })) ?? [], + where: mapResolverExpressionToV1Expression(props.where), + timeRange: props.time_range && { + ...convertRequestKeysToCamelCase(props.time_range), + timeZone: props.time_zone, + }, + }; +} + +const AIAlertNameMaxLength = 60; + +// An AI alert's default name is its condition, shortened. +export function generateAIAlertName(condition: string): string { + const name = condition.trim().replace(/\s+/g, " "); + if (name.length <= AIAlertNameMaxLength) return name; + return name.slice(0, AIAlertNameMaxLength - 1).trimEnd() + "…"; +} diff --git a/web-common/src/features/alerts/create-alert-utils.ts b/web-common/src/features/alerts/create-alert-utils.ts index 4af6acb22966..fd44a57df458 100644 --- a/web-common/src/features/alerts/create-alert-utils.ts +++ b/web-common/src/features/alerts/create-alert-utils.ts @@ -1,3 +1,4 @@ +import { CriteriaConditionType } from "@rilldata/web-common/features/alerts/ai-alert-utils.ts"; import { getSnoozeOptions } from "@rilldata/web-common/features/alerts/delivery-tab/snooze.ts"; import { AlertNotifyRowsLimitDefault, @@ -36,6 +37,8 @@ export function getNewAlertInitialFormValues( return { name: "", + conditionType: CriteriaConditionType, + aiCondition: "", measure, splitByDimension: dimension, notifyRowsLimit: String(AlertNotifyRowsLimitDefault), diff --git a/web-common/src/features/alerts/criteria-tab/AlertDialogCriteriaTab.svelte b/web-common/src/features/alerts/criteria-tab/AlertDialogCriteriaTab.svelte index d2d33dcc44bb..9487d0e4baba 100644 --- a/web-common/src/features/alerts/criteria-tab/AlertDialogCriteriaTab.svelte +++ b/web-common/src/features/alerts/criteria-tab/AlertDialogCriteriaTab.svelte @@ -1,5 +1,7 @@
- - - - - - + {#if $form["conditionType"] === AIConditionType} + +