From fbe5ea108fa736a7a2e5ef73c24e88cbe2dfaf81 Mon Sep 17 00:00:00 2001 From: dfliess Date: Sat, 7 Nov 2026 12:59:12 +0100 Subject: [PATCH 1/8] fix(admin): write resolver properties of alerts and reports as plain YAML Alerts and reports created through the API with a resolver serialized its properties as the protobuf Struct's internals (fields/kind/stringvalue), so the runtime parsed different properties than it was given. --- admin/server/alerts.go | 4 +-- admin/server/reports.go | 4 +-- admin/server/resolver_yaml_test.go | 57 ++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 admin/server/resolver_yaml_test.go diff --git a/admin/server/alerts.go b/admin/server/alerts.go index aa9e29f9dbca..e748707e9ca5 100644 --- a/admin/server/alerts.go +++ b/admin/server/alerts.go @@ -535,7 +535,7 @@ func (s *Server) yamlForManagedAlert(opts *adminv1.AlertOptions, ownerUserID str res.Intervals.Duration = opts.IntervalDuration if opts.Resolver != "" { res.Data = map[string]any{ - opts.Resolver: opts.ResolverProperties, + opts.Resolver: opts.ResolverProperties.AsMap(), } } res.Query.Name = opts.QueryName @@ -585,7 +585,7 @@ func (s *Server) yamlForCommittedAlert(opts *adminv1.AlertOptions) ([]byte, erro res.Intervals.Duration = opts.IntervalDuration if opts.Resolver != "" { res.Data = map[string]any{ - opts.Resolver: opts.ResolverProperties, + opts.Resolver: opts.ResolverProperties.AsMap(), } } res.Query.Name = opts.QueryName diff --git a/admin/server/reports.go b/admin/server/reports.go index 14bcea245313..159c2d116dec 100644 --- a/admin/server/reports.go +++ b/admin/server/reports.go @@ -779,7 +779,7 @@ func (s *Server) yamlForManagedReport(opts *adminv1.ReportOptions, ownerUserID, if opts.Resolver != "" { res.Data = map[string]any{ - opts.Resolver: opts.ResolverProperties, + opts.Resolver: opts.ResolverProperties.AsMap(), } } res.Query.Name = opts.QueryName // nolint:staticcheck // backwards compatibility @@ -889,7 +889,7 @@ func (s *Server) yamlForCommittedReport(opts *adminv1.ReportOptions) ([]byte, er res.Intervals.Duration = opts.IntervalDuration if opts.Resolver != "" { res.Data = map[string]any{ - opts.Resolver: opts.ResolverProperties, + opts.Resolver: opts.ResolverProperties.AsMap(), } } if opts.ExportFormat == runtimev1.ExportFormat_EXPORT_FORMAT_PDF { diff --git a/admin/server/resolver_yaml_test.go b/admin/server/resolver_yaml_test.go new file mode 100644 index 000000000000..13e9b96b58aa --- /dev/null +++ b/admin/server/resolver_yaml_test.go @@ -0,0 +1,57 @@ +package server + +import ( + "testing" + + adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/structpb" + "gopkg.in/yaml.v3" +) + +// TestYAMLForResolverProperties checks that alerts and reports written with a resolver keep its properties as plain YAML, +// so the runtime parses the same properties it was given. +func TestYAMLForResolverProperties(t *testing.T) { + s := &Server{} + props, err := structpb.NewStruct(map[string]any{ + "sql": "SELECT 1 FROM mv1", + "limit": 10, + }) + require.NoError(t, err) + want := map[string]any{"metrics_sql": map[string]any{"sql": "SELECT 1 FROM mv1", "limit": 10}} + + alert := &adminv1.AlertOptions{ + DisplayName: "Alert", + MetricsViewName: "mv1", + Resolver: "metrics_sql", + ResolverProperties: props, + EmailRecipients: []string{"user_1@example.com"}, + } + report := &adminv1.ReportOptions{ + DisplayName: "Report", + RefreshCron: "0 9 * * 1", + Resolver: "metrics_sql", + ResolverProperties: props, + EmailRecipients: []string{"user_1@example.com"}, + Explore: "e1", + WebOpenMode: string(WebOpenModeRecipient), + } + + generators := map[string]func() ([]byte, error){ + "managed alert": func() ([]byte, error) { return s.yamlForManagedAlert(alert, "owner") }, + "committed alert": func() ([]byte, error) { return s.yamlForCommittedAlert(alert) }, + "managed report": func() ([]byte, error) { return s.yamlForManagedReport(report, "owner", "", "", nil) }, + "committed report": func() ([]byte, error) { return s.yamlForCommittedReport(report) }, + } + for name, generate := range generators { + t.Run(name, func(t *testing.T) { + data, err := generate() + require.NoError(t, err) + var res struct { + Data map[string]any `yaml:"data"` + } + require.NoError(t, yaml.Unmarshal(data, &res)) + require.Equal(t, want, res.Data) + }) + } +} From 587d2c354f21f040c3537ae0a6a305b901c3f468 Mon Sep 17 00:00:00 2001 From: dfliess Date: Sat, 7 Nov 2026 12:59:12 +0100 Subject: [PATCH 2/8] feat(runtime): evaluate AI alerts with the analyst agent An alert with the ai resolver has its prompt judged as a condition by the analyst agent, which ends with a structured verdict. A met condition returns one row with the verdict's reason and the conversation, so the alert fires; a malformed verdict or an exhausted tool budget is an evaluation error. The check runs with the alert's own claims, and notifications show the reason and link to the conversation. --- runtime/ai/ai.go | 6 + runtime/ai/analyst_agent.go | 65 +++++++- runtime/ai/analyst_alert_test.go | 139 ++++++++++++++++++ runtime/ai/router_agent.go | 4 +- runtime/drivers/notifier.go | 12 +- runtime/drivers/slack/notifier.go | 2 + runtime/drivers/slack/notifier_test.go | 47 ++++++ .../slack/templates/slack/alert_fail.slack | 8 +- runtime/pkg/email/email.go | 3 + runtime/pkg/email/email_test.go | 24 +++ runtime/pkg/email/templates/alert_fail.mjml | 8 +- .../pkg/email/templates/gen/alert_fail.html | 10 +- runtime/reconcilers/alert.go | 83 +++++++++-- runtime/reconcilers/alert_test.go | 101 +++++++++++++ runtime/resolvers/ai.go | 41 +++++- runtime/resolvers/ai_test.go | 34 +++++ 16 files changed, 557 insertions(+), 30 deletions(-) create mode 100644 runtime/ai/analyst_alert_test.go create mode 100644 runtime/drivers/slack/notifier_test.go create mode 100644 runtime/resolvers/ai_test.go diff --git a/runtime/ai/ai.go b/runtime/ai/ai.go index 84d3e7ccf31e..373bf333b30e 100644 --- a/runtime/ai/ai.go +++ b/runtime/ai/ai.go @@ -1337,6 +1337,9 @@ type CompleteOptions struct { // In some cases, it's desirable to capture these intermediate messages in the parent call's context, in other cases it's better to isolate them and only expose the final result to the parent context. // When UnwrapCall is true, we run the completion loop within the current call, otherwise we wrap the complete loop in a new call to isolate internal messages. UnwrapCall bool + // FailOnIterationLimit makes the loop return an error when the model is still calling tools after MaxIterations-1 turns, + // instead of taking a final turn without tools that forces it to answer with what it has. + FailOnIterationLimit bool } // Complete runs LLM completions. @@ -1503,6 +1506,9 @@ func (s *Session) Complete(ctx context.Context, name string, out any, opts *Comp for i := range opts.MaxIterations { // Disable tool calls in the last iteration final := i+1 == opts.MaxIterations + if final && i != 0 && opts.FailOnIterationLimit { + return nil, fmt.Errorf("reached the limit of %d iterations without a final response", opts.MaxIterations) + } if final { tools = nil if i != 0 { diff --git a/runtime/ai/analyst_agent.go b/runtime/ai/analyst_agent.go index 86325c3eee2f..5ddfd5c3c9f0 100644 --- a/runtime/ai/analyst_agent.go +++ b/runtime/ai/analyst_agent.go @@ -2,6 +2,7 @@ package ai import ( "context" + "encoding/json" "errors" "fmt" "strings" @@ -43,6 +44,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 judges an AI alert's condition. The prompt is the condition, and the agent ends with a verdict."` } func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock { @@ -55,6 +57,35 @@ func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock { type AnalystAgentResult struct { Response string `json:"response"` + // Verdict is set when the agent judged an AI alert's condition (see AnalystAgentArgs.IsAlert). + Verdict *AlertVerdict `json:"verdict,omitempty"` +} + +// AlertVerdict is the analyst's verdict on an AI alert's condition. +type AlertVerdict struct { + Met bool `json:"met" jsonschema:"True only if the data shows that the condition holds."` + Reason string `json:"reason" jsonschema:"One to three plain sentences explaining the verdict with the figures it rests on."` +} + +// UnmarshalJSON rejects a verdict with a missing or empty field. +// A malformed verdict must surface as an error, not decode silently to "not met". +func (v *AlertVerdict) UnmarshalJSON(data []byte) error { + var raw struct { + Met *bool `json:"met"` + Reason *string `json:"reason"` + } + if err := json.Unmarshal(data, &raw); err != nil { + return fmt.Errorf("malformed alert verdict: %w", err) + } + if raw.Met == nil { + return errors.New(`malformed alert verdict: missing "met"`) + } + if raw.Reason == nil || strings.TrimSpace(*raw.Reason) == "" { + return errors.New(`malformed alert verdict: missing "reason"`) + } + v.Met = *raw.Met + v.Reason = *raw.Reason + return nil } func (r *AnalystAgentResult) ToLLM() *aiv1.ContentBlock { @@ -195,7 +226,9 @@ func (t *AnalystAgent) Handler(ctx context.Context, args *AnalystAgentArgs) (*An tools = append(tools, ListMetricsViewsName, GetMetricsViewName, GetCanvasName) } tools = append(tools, QueryMetricsViewSummaryName, QueryMetricsViewName, ClickUIName) - if !args.DisableCharts { + // Judging an AI alert offers no charts: a verdict cannot show one, + // and Gemini rejects a request that pairs the verdict's output schema with both query_metrics_view and create_chart. + if !args.DisableCharts && !args.IsAlert { tools = append(tools, CreateChartName) } if len(skills) > 0 { @@ -238,6 +271,23 @@ func (t *AnalystAgent) Handler(ctx context.Context, args *AnalystAgentArgs) (*An } ctx = WithDashboardFilters(ctx, dashboardFilters) + // Judging an AI alert ends with a structured verdict instead of a free-form answer. + // The loop fails rather than force a verdict after the tool budget runs out, since that verdict would not rest on the data. + if args.IsAlert { + verdict := &AlertVerdict{} + err = s.Complete(ctx, "Analyst loop", verdict, &CompleteOptions{ + Messages: messages, + Tools: tools, + MaxIterations: 20, + UnwrapCall: true, + FailOnIterationLimit: true, + }) + if err != nil { + return nil, fmt.Errorf("failed to reach a verdict on the alert's condition: %w", err) + } + return &AnalystAgentResult{Response: verdict.Reason, Verdict: verdict}, nil + } + // Run an LLM tool call loop var response string err = s.Complete(ctx, "Analyst loop", &response, &CompleteOptions{ @@ -304,6 +354,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"), @@ -346,9 +397,17 @@ 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 operating as the judge of an automated alert, without additional user input. +The alert's condition is given at the end of this message: a statement about the data that either holds or does not. +Query the data to decide whether the condition holds. Do not ask questions, since nobody will answer them. +Your final response is a verdict: "met" is true only if the data shows that the condition holds, and "reason" explains the verdict in one to three plain sentences with the figures it rests on, without citation links. +{{ if (and .time_start .time_end) }}Relative expressions in the condition, such as "this month", "this week", "today", "yesterday" or "compared with the previous period", refer to the time range start={{.time_start}}, end={{.time_end}}, not to today's date.{{ else }}Relative expressions in the condition, such as "this month", "this week", "today", "yesterday" or "compared with the previous period", refer to the latest data available, not to today's date.{{ end }} +{{ 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: @@ -443,7 +502,7 @@ If a memory conflicts with the user's current request, follow the current reques {{ end }} {{ if .is_prompt }} -The user's request: +{{ if .is_alert }}The alert's condition:{{ else }}The user's request:{{ end }} {{ .prompt }} {{ end }} `, data) diff --git a/runtime/ai/analyst_alert_test.go b/runtime/ai/analyst_alert_test.go new file mode 100644 index 000000000000..82aa15453b28 --- /dev/null +++ b/runtime/ai/analyst_alert_test.go @@ -0,0 +1,139 @@ +package ai_test + +import ( + "encoding/json" + "slices" + "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 TestAlertVerdictUnmarshal(t *testing.T) { + var v ai.AlertVerdict + err := json.Unmarshal([]byte(`{"met": false, "reason": "Revenue is within its usual range."}`), &v) + require.NoError(t, err) + require.Equal(t, ai.AlertVerdict{Met: false, Reason: "Revenue is within its usual range."}, v) + + // A malformed verdict is an error, not a verdict that the condition is not met + for _, in := range []string{ + `The condition holds.`, + `{"reason": "Revenue fell."}`, + `{"met": null, "reason": "Revenue fell."}`, + `{"met": "yes", "reason": "Revenue fell."}`, + `{"met": true}`, + `{"met": true, "reason": " "}`, + } { + err := json.Unmarshal([]byte(in), &v) + require.Error(t, err, in) + } +} + +func TestAnalystAlert(t *testing.T) { + alertArgs := &ai.RouterAgentArgs{ + Prompt: "There are orders from Denmark", + Agent: ai.AnalystAgentName, + AnalystAgentArgs: &ai.AnalystAgentArgs{IsAlert: true}, + } + + t.Run("verdict", func(t *testing.T) { + var outputSchema *jsonschema.Schema + script := &scriptedAIService{turns: []turnFunc{func(opts *drivers.CompleteOptions) *aiv1.CompletionMessage { + outputSchema = opts.OutputSchema + return textTurn(`{"met": true, "reason": "Denmark has orders."}`)(opts) + }}} + s := newSkillReferencesSession(t, script) + + var res *ai.RouterAgentResult + _, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, &res, alertArgs) + require.NoError(t, err) + require.Equal(t, &ai.AlertVerdict{Met: true, Reason: "Denmark has orders."}, res.Verdict) + + // The verdict is requested through the output schema + require.NotNil(t, outputSchema) + require.Contains(t, outputSchema.Properties, "met") + require.Contains(t, outputSchema.Properties, "reason") + + // A verdict can't show charts + require.Contains(t, script.tools[0], ai.QueryMetricsViewName) + require.NotContains(t, script.tools[0], ai.CreateChartName) + }) + + t.Run("malformed verdict", func(t *testing.T) { + s := newSkillReferencesSession(t, &scriptedAIService{turns: []turnFunc{textTurn(`The condition holds.`)}}) + _, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, nil, alertArgs) + require.Error(t, err) + }) + + t.Run("iteration limit", func(t *testing.T) { + // Outside of alerts, the loop forces a final answer without tools after the last iteration. + // For an alert, that would be a verdict that doesn't rest on the data, so it fails instead. + turns := slices.Repeat([]turnFunc{toolCallTurn(ai.ListMetricsViewsName, map[string]any{})}, 20) + s := newSkillReferencesSession(t, &scriptedAIService{turns: turns}) + _, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, nil, alertArgs) + require.ErrorContains(t, err, "iterations") + }) +} + +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 + met bool + }{ + {"Revenue in Spain dropped sharply in the last week compared with the previous weeks", true}, + {"Spain is the country with the lowest revenue in the last week", true}, + {"Revenue in France dropped sharply in the last week compared with the previous weeks", false}, + {"There are orders from Italy", false}, + } + 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.NotNil(t, res.Verdict) + require.Equal(t, tc.met, res.Verdict.Met, res.Verdict.Reason) + }) + } +} diff --git a/runtime/ai/router_agent.go b/runtime/ai/router_agent.go index c213942462fc..8c361825273f 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"` + // Verdict is the analyst's verdict when it judged an AI alert's condition. + Verdict *AlertVerdict `json:"verdict,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, Verdict: res.Verdict}, nil case DeveloperAgentName: developerAgentArgs := args.DeveloperAgentArgs diff --git a/runtime/drivers/notifier.go b/runtime/drivers/notifier.go index 321e565e9496..6e3f0aeae94c 100644 --- a/runtime/drivers/notifier.go +++ b/runtime/drivers/notifier.go @@ -13,11 +13,13 @@ type Notifier interface { } type AlertStatus struct { - DisplayName string - ExecutionTime time.Time - Status runtimev1.AssertionStatus - IsRecover bool - FailRow map[string]any + DisplayName string + ExecutionTime time.Time + Status runtimev1.AssertionStatus + IsRecover bool + FailRow map[string]any + // Reason is the AI analysis's reason when an AI alert fires; it is shown instead of the fail row. + Reason string ExecutionError string OpenLink string EditLink string diff --git a/runtime/drivers/slack/notifier.go b/runtime/drivers/slack/notifier.go index ad5ae0abac2b..b29c7f029114 100644 --- a/runtime/drivers/slack/notifier.go +++ b/runtime/drivers/slack/notifier.go @@ -125,6 +125,7 @@ func (n *notifier) SendAlertStatus(s *drivers.AlertStatus) error { DisplayName: s.DisplayName, ExecutionTimeString: s.ExecutionTime.Format(time.RFC1123), FailRow: s.FailRow, + Reason: s.Reason, OpenLink: htemplate.URL(s.OpenLink), EditLink: htemplate.URL(s.EditLink), }) @@ -281,6 +282,7 @@ type AlertFailData struct { DisplayName string ExecutionTimeString string // Will be inferred from ExecutionTime FailRow map[string]any + Reason string // The AI analysis's reason when an AI alert fires, shown instead of the fail row OpenLink htemplate.URL EditLink htemplate.URL } diff --git a/runtime/drivers/slack/notifier_test.go b/runtime/drivers/slack/notifier_test.go new file mode 100644 index 000000000000..903ae9581953 --- /dev/null +++ b/runtime/drivers/slack/notifier_test.go @@ -0,0 +1,47 @@ +package slack + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1" + "github.com/rilldata/rill/runtime/drivers" + "github.com/stretchr/testify/require" +) + +func TestAIAlertFail(t *testing.T) { + var text string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + var msg struct { + Text string `json:"text"` + } + require.NoError(t, json.Unmarshal(body, &msg)) + text = msg.Text + })) + defer srv.Close() + + n, err := newNotifier("", EncodeProps(nil, nil, []string{srv.URL})) + require.NoError(t, err) + err = n.SendAlertStatus(&drivers.AlertStatus{ + DisplayName: "Revenue drop", + ExecutionTime: time.Date(2026, 10, 27, 7, 0, 0, 0, time.UTC), + Status: runtimev1.AssertionStatus_ASSERTION_STATUS_FAIL, + FailRow: map[string]any{"reason": "Revenue fell 40% against the previous four weeks.", "ai_session_id": "s1"}, + Reason: "Revenue fell 40% against the previous four weeks.", + OpenLink: "https://example.com/alerts/a1/open?session_id=s1", + EditLink: "https://example.com/alerts/a1", + }) + require.NoError(t, err) + + // The message shows the reason instead of the fail row's fields + require.Contains(t, text, "Revenue fell 40% against the previous four weeks.") + require.Contains(t, text, "https://example.com/alerts/a1/open?session_id=s1") + require.NotContains(t, text, "first row") + require.NotContains(t, text, "ai_session_id") +} diff --git a/runtime/drivers/slack/templates/slack/alert_fail.slack b/runtime/drivers/slack/templates/slack/alert_fail.slack index 66c3825fae96..b77b55478280 100644 --- a/runtime/drivers/slack/templates/slack/alert_fail.slack +++ b/runtime/drivers/slack/templates/slack/alert_fail.slack @@ -1,7 +1,13 @@ *{{ .DisplayName }}* Your alert triggered for {{ .ExecutionTimeString }}. +{{ if .Reason }} +The AI analysis found that the condition holds: +{{ .Reason }} + +<{{ .OpenLink }}|View full analysis> +{{ else }} The first row that matched your alert criteria is: {{ range $key, $value := .FailRow }} @@ -9,5 +15,5 @@ The first row that matched your alert criteria is: {{ end }} <{{ .OpenLink }}|Open in browser> - +{{ end }} To edit or unsubscribe from this alert, <{{ .EditLink }}|click here>. diff --git a/runtime/pkg/email/email.go b/runtime/pkg/email/email.go index cd853c197f9c..503607127beb 100644 --- a/runtime/pkg/email/email.go +++ b/runtime/pkg/email/email.go @@ -102,6 +102,7 @@ type AlertStatus struct { Status runtimev1.AssertionStatus IsRecover bool FailRow map[string]any + Reason string // The AI analysis's reason when an AI alert fires, shown instead of the fail row ExecutionError string OpenLink string EditLink string @@ -127,6 +128,7 @@ func (c *Client) SendAlertStatus(opts *AlertStatus) error { DisplayName: opts.DisplayName, ExecutionTimeString: opts.ExecutionTime.Format(time.RFC1123), FailRow: opts.FailRow, + Reason: opts.Reason, OpenLink: template.URL(opts.OpenLink), EditLink: template.URL(opts.EditLink), UnsubscribeLink: template.URL(opts.UnsubscribeLink), @@ -152,6 +154,7 @@ type alertFailData struct { DisplayName string ExecutionTimeString string // Will be inferred from ExecutionTime FailRow map[string]any + 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 61d431217ba1..932ffd4d2eaf 100644 --- a/runtime/pkg/email/email_test.go +++ b/runtime/pkg/email/email_test.go @@ -130,6 +130,30 @@ func TestAlertFail(t *testing.T) { require.Empty(t, mock.attachments) } +func TestAIAlertFail(t *testing.T) { + mock := &mockSender{} + client := New(mock) + + opts := &AlertStatus{ + ToEmail: uuid.New().String(), + DisplayName: "Foobar", + ExecutionTime: time.Date(2024, 01, 27, 0, 0, 0, 0, time.UTC), + Status: runtimev1.AssertionStatus_ASSERTION_STATUS_FAIL, + FailRow: map[string]any{"reason": "Revenue fell 40% against the previous four weeks.", "ai_session_id": "s1"}, + Reason: "Revenue fell 40% against the previous four weeks.", + OpenLink: "https://example.com", + EditLink: "https://example.com", + } + err := client.SendAlertStatus(opts) + require.NoError(t, err) + + // The email shows the reason instead of the fail row's fields + require.Contains(t, mock.body, opts.Reason) + require.Contains(t, mock.body, "View full analysis") + require.NotContains(t, mock.body, "ai_session_id") + require.NotContains(t, mock.body, "The first row") +} + func TestAlertRecover(t *testing.T) { mock := &mockSender{} client := New(mock) diff --git a/runtime/pkg/email/templates/alert_fail.mjml b/runtime/pkg/email/templates/alert_fail.mjml index adb2622186e9..5d70877f51be 100644 --- a/runtime/pkg/email/templates/alert_fail.mjml +++ b/runtime/pkg/email/templates/alert_fail.mjml @@ -21,13 +21,13 @@ - Your alert triggered for {{ .ExecutionTimeString }}. The first row that matched your alert criteria is: + Your alert triggered for {{ .ExecutionTimeString }}. {{ if .Reason }}The AI analysis found that the condition holds:{{ else }}The first row that matched your alert criteria is:{{ end }} - {{ range $key, $value := .FailRow }} + {{ if .Reason }}{{ .Reason }}{{ else }}{{ range $key, $value := .FailRow }} • {{ $key }}: {{ $value }}
- {{ end }} + {{ end }}{{ end }}
{{ if .Attached }} @@ -43,7 +43,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 590d6fc1be6c..2d5772f15668 100644 --- a/runtime/pkg/email/templates/gen/alert_fail.html +++ b/runtime/pkg/email/templates/gen/alert_fail.html @@ -126,13 +126,13 @@ -
Your alert triggered for {{ .ExecutionTimeString }}. The first row that matched your alert criteria is:
+
Your alert triggered for {{ .ExecutionTimeString }}. {{ if .Reason }}The AI analysis found that the condition holds:{{ else }}The first row that matched your alert criteria is:{{ end }}
-
{{ range $key, $value := .FailRow }} • {{ $key }}: {{ $value }}
- {{ end }} +
{{ if .Reason }}{{ .Reason }}{{ else }}{{ range $key, $value := .FailRow }} • {{ $key }}: {{ $value }}
+ {{ end }}{{ end }}
@@ -160,7 +160,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 08a2834b0cb0..e5703e14dbed 100644 --- a/runtime/reconcilers/alert.go +++ b/runtime/reconcilers/alert.go @@ -284,7 +284,7 @@ func (r *AlertReconciler) ResolveTransitiveAccess(ctx context.Context, claims *r resolver, err := initializer(ctx, &runtime.ResolverOptions{ Runtime: r.C.Runtime, InstanceID: r.C.InstanceID, - Properties: spec.ResolverProperties.AsMap(), + Properties: alertResolverProperties(spec), ProjectDeclared: false, // Alert templates never access project variables (the parser rejects references to them). Claims: claims, ForExport: false, @@ -700,18 +700,24 @@ 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) + args := map[string]any{ + "priority": alertQueryPriority, + "execution_time": executionTime, + "format": true, + "limit": 1, + } + if a.Spec.Resolver == "ai" { + // Share the analyst's conversation so every recipient's link can open it, like an AI report in creator mode. + args["create_shared_session"] = true + } + res, info, err := r.C.Runtime.Resolve(ctx, &runtime.ResolveOptions{ InstanceID: r.C.InstanceID, Resolver: a.Spec.Resolver, - ResolverProperties: a.Spec.ResolverProperties.AsMap(), + ResolverProperties: alertResolverProperties(a.Spec), 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": 1, - }, - Claims: &runtime.SecurityClaims{UserAttributes: alertQueryForAttributes(a, adminMeta)}, + Args: args, + Claims: alertResolverClaims(a.Spec, alertQueryForAttributes(a, adminMeta)), }) if err != nil { return nil, fmt.Errorf("failed to resolve alert: %w", err) @@ -822,6 +828,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime // Generate the notification message to send (if any) var msg *drivers.AlertStatus + var aiSessionID string if notify { switch current.Result.Status { case runtimev1.AssertionStatus_ASSERTION_STATUS_PASS: @@ -855,6 +862,11 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime Status: current.Result.Status, FailRow: current.Result.FailRow.AsMap(), } + if a.Spec.Resolver == "ai" { + // An AI alert's fail row is the AI's verdict: show its reason and link to the conversation behind it. + msg.Reason, _ = msg.FailRow["reason"].(string) + aiSessionID, _ = msg.FailRow["ai_session_id"].(string) + } case runtimev1.AssertionStatus_ASSERTION_STATUS_ERROR: if !a.Spec.NotifyOnError { break @@ -909,6 +921,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime Status: msg.Status, IsRecover: msg.IsRecover, FailRow: msg.FailRow, + Reason: msg.Reason, ExecutionError: msg.ExecutionError, Attachment: attachment, AttachmentTooLarge: attachmentTooLarge, @@ -919,7 +932,7 @@ func (r *AlertReconciler) popCurrentExecution(ctx context.Context, self *runtime if adminMeta != nil && adminMeta.RecipientURLs != nil { if recipientURLs, ok := adminMeta.RecipientURLs[recipient]; 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) } @@ -955,7 +968,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) } @@ -1054,6 +1067,20 @@ func (r *AlertReconciler) exportAttachment(ctx context.Context, self *runtimev1. func (r *AlertReconciler) computeInheritedWatermark(ctx context.Context, refs []*runtimev1.ResourceName) (time.Time, bool, error) { var t time.Time for _, ref := range refs { + // Explores (referenced by AI alerts) inherit the watermark of their metrics view, as in the report reconciler. + // 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, @@ -1167,6 +1194,40 @@ func alertQueryForAttributes(a *runtimev1.Alert, adminMeta *drivers.AlertMetadat return nil } +// alertResolverProperties returns the alert's resolver properties as they should be passed to the resolver. +// For AI alerts, it marks the properties as belonging to an alert, which makes the ai resolver judge the prompt as the alert's condition. +func alertResolverProperties(spec *runtimev1.AlertSpec) map[string]any { + props := spec.ResolverProperties.AsMap() + if spec.Resolver == "ai" { + props["is_alert"] = true + } + return props +} + +// alertResolverClaims returns the claims the alert's resolver runs with: the attributes of the user the alert queries for. +// An AI alert's analyst also gets a user to own its conversation (the "for" user, or else the alert's owner) +// and the permissions its tools check, which an AI report gets too. It never skips security checks. +func alertResolverClaims(spec *runtimev1.AlertSpec, queryForAttrs map[string]any) *runtime.SecurityClaims { + claims := &runtime.SecurityClaims{UserAttributes: queryForAttrs} + if spec.Resolver == "ai" { + claims.UserID = spec.GetQueryForUserId() + if claims.UserID == "" { + claims.UserID = spec.Annotations["admin_owner_user_id"] + } + claims.Permissions = []runtime.Permission{runtime.ReadObjects, runtime.ReadMetrics, runtime.UseAI} + } + return claims +} + +// alertOpenLink builds a notification's open link. An AI alert's link also names the analyst's conversation, which the open page redirects to. +func alertOpenLink(openURL string, executionTime time.Time, aiSessionID string) (string, error) { + link, err := addExecutionTime(openURL, executionTime) + if err != nil || aiSessionID == "" { + return link, err + } + return buildAISessionURL(link, aiSessionID) +} + func addExecutionTime(openURL string, executionTime time.Time) (string, error) { u, err := url.Parse(openURL) if err != nil { diff --git a/runtime/reconcilers/alert_test.go b/runtime/reconcilers/alert_test.go index 6f84394f5d08..37378dce52bf 100644 --- a/runtime/reconcilers/alert_test.go +++ b/runtime/reconcilers/alert_test.go @@ -1,6 +1,7 @@ package reconcilers_test import ( + "context" "fmt" "slices" "strings" @@ -9,6 +10,8 @@ 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" "github.com/rilldata/rill/runtime/testruntime" @@ -876,3 +879,101 @@ notify: require.Contains(t, emails[0].Body, "too large to attach to this email") require.Empty(t, emails[0].Attachments) } + +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 +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: &aiAlertAdmin{queryForAttributes: map[string]any{"country": "VisibleLand"}}, + }) + testruntime.ReconcileParserAndWait(t, rt, id) + + // The check runs at the watermark of the explore's metrics view. + // 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 analyst 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") +} + +// aiAlertAdmin is an admin service that resolves an alert's "for" user to fixed attributes. +type aiAlertAdmin struct { + drivers.AdminService // Not implemented; calls to methods that are not overridden panic + queryForAttributes map[string]any +} + +func (a *aiAlertAdmin) GetConfig(ctx context.Context) (*drivers.Config, error) { + return &drivers.Config{}, nil +} + +func (a *aiAlertAdmin) GetAlertMetadata(ctx context.Context, alertName, ownerID string, emailRecipients []string, anonRecipients bool, annotations map[string]string, queryForUserID, queryForUserEmail string) (*drivers.AlertMetadata, error) { + return &drivers.AlertMetadata{QueryForAttributes: a.queryForAttributes}, nil +} diff --git a/runtime/resolvers/ai.go b/runtime/resolvers/ai.go index 944da521312b..29039f5c7711 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 judges an AI alert's condition, which is the prompt. + // It then returns one row with the verdict's reason if the condition is met, and no rows if it is not. + IsAlert bool `mapstructure:"is_alert"` UnusedFields map[string]any `mapstructure:",remain"` } @@ -176,6 +179,12 @@ func (r *aiResolver) Validate(ctx context.Context) error { // ResolveInteractive implements runtime.Resolver. func (r *aiResolver) ResolveInteractive(ctx context.Context) (runtime.ResolverResult, error) { + // An AI alert queries the data with the alert's own claims (its owner or "for" attributes). + // Claims that skip security checks would let the condition be judged on rows the alert's owner can't see. + if r.props.IsAlert && r.claims.SkipChecks { + return nil, errors.New("AI alerts must run with the alert's own claims, not claims that skip security checks") + } + // Resolve time ranges if provided err := r.resolveTimeRange(ctx, r.props.TimeRange, r.props.TimeZone) if err != nil { @@ -224,6 +233,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 +266,21 @@ func (r *aiResolver) ResolveInteractive(ctx context.Context) (runtime.ResolverRe } } + // An AI alert returns the verdict as rows, which the alert reconciler reads like any alert's rows. + if r.props.IsAlert { + rows, err := aiAlertRows(result.Verdict, session.ID()) + if err != nil { + return nil, err + } + 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 +382,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 +431,18 @@ func lookupMetricsView(ctx context.Context, rt *runtime.Runtime, instanceID, nam return res, mv.State, nil } +// aiAlertRows maps an AI alert's verdict to the resolver's rows: one row with the reason and the conversation when the condition is met, none when it is not. +// The alert reconciler fires when the resolver returns a row, so the verdict fits its rule unchanged. +func aiAlertRows(verdict *ai.AlertVerdict, sessionID string) ([]map[string]any, error) { + if verdict == nil { + return nil, errors.New("the analyst did not return a verdict for the alert's condition") + } + if !verdict.Met { + return nil, nil + } + return []map[string]any{{"reason": verdict.Reason, "ai_session_id": sessionID}}, nil +} + // 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..b79b917b802b --- /dev/null +++ b/runtime/resolvers/ai_test.go @@ -0,0 +1,34 @@ +package resolvers + +import ( + "testing" + + "github.com/rilldata/rill/runtime" + "github.com/rilldata/rill/runtime/ai" + "github.com/stretchr/testify/require" +) + +func TestAIAlert(t *testing.T) { + // A met condition returns a row with the reason, which makes the alert fire + rows, err := aiAlertRows(&ai.AlertVerdict{Met: true, Reason: "Revenue fell 40%."}, "s1") + require.NoError(t, err) + require.Equal(t, []map[string]any{{"reason": "Revenue fell 40%.", "ai_session_id": "s1"}}, rows) + + // A condition that is not met returns no rows + rows, err = aiAlertRows(&ai.AlertVerdict{Met: false, Reason: "Revenue is stable."}, "s1") + require.NoError(t, err) + require.Empty(t, rows) + + // A missing verdict is an error + _, err = aiAlertRows(nil, "s1") + require.Error(t, err) + + // The condition is never judged with claims that skip security checks + r := &aiResolver{ + props: &aiProps{Prompt: "Revenue dropped", IsAlert: true}, + args: &aiArgs{}, + claims: &runtime.SecurityClaims{SkipChecks: true}, + } + _, err = r.ResolveInteractive(t.Context()) + require.ErrorContains(t, err, "security checks") +} From 012f126c55b690b55bec65ded8586e626cc7a1f1 Mon Sep 17 00:00:00 2001 From: dfliess Date: Sat, 7 Nov 2026 12:59:12 +0100 Subject: [PATCH 3/8] feat(alerts): add an AI condition to the alert dialog The data tab switches between criteria and an AI condition written as a sentence. AI alerts load into and save from the dialog however they were created, and the alert page and history show the condition and the reason an AI alert triggered. --- .../features/alerts/AlertDialogTest.svelte | 27 ++ .../alerts/alert-dialog.component.spec.ts | 381 ++++++++++++++++++ .../AlertHistoryTableCompositeCell.svelte | 9 + .../alerts/metadata/AlertMetadata.svelte | 34 +- web-admin/src/features/alerts/selectors.ts | 5 + .../[project]/-/alerts/[alert]/open/+page.ts | 14 + .../src/components/forms/FieldSwitcher.svelte | 2 + .../src/features/alerts/AlertForm.svelte | 119 ++++-- .../alerts/AlertFormDataWrapper.svelte | 29 +- .../features/alerts/ai-alert-utils.spec.ts | 195 +++++++++ .../src/features/alerts/ai-alert-utils.ts | 200 +++++++++ .../src/features/alerts/create-alert-utils.ts | 3 + .../AlertDialogCriteriaTab.svelte | 37 +- .../alerts/data-tab/AlertDialogDataTab.svelte | 41 +- .../AlertDialogDeliveryTab.svelte | 48 ++- .../alerts/extract-alert-form-values.ts | 32 +- web-common/src/features/alerts/form-utils.ts | 141 +++++-- .../charts/custom/expression-utils.ts | 39 ++ web-common/src/lib/i18n/messages/en.json | 7 + web-common/src/lib/i18n/messages/es.json | 7 + web-common/src/lib/i18n/messages/ko.json | 7 + 21 files changed, 1256 insertions(+), 121 deletions(-) create mode 100644 web-admin/src/features/alerts/AlertDialogTest.svelte create mode 100644 web-admin/src/features/alerts/alert-dialog.component.spec.ts create mode 100644 web-common/src/features/alerts/ai-alert-utils.spec.ts create mode 100644 web-common/src/features/alerts/ai-alert-utils.ts 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..75ee77564778 --- /dev/null +++ b/web-admin/src/features/alerts/alert-dialog.component.spec.ts @@ -0,0 +1,381 @@ +import "@testing-library/jest-dom/vitest"; +import AlertDialogTest from "@rilldata/web-admin/features/alerts/AlertDialogTest.svelte"; +import { + mockPointerEventsForComponentTesting, + mockResizeObserverForComponentTesting, + useDashboardFetchMocksForComponentTests, + waitForBodyScrollCleanup, +} from "@rilldata/web-common/features/dashboards/filters/test/filter-test-utils"; +import { getProtoFromDashboardState } from "@rilldata/web-common/features/dashboards/proto-state/toProto"; +import { + type HoistedPageForComponentTests, + PageMockForComponentTests, +} from "@rilldata/web-common/features/dashboards/state-managers/loaders/test/PageMockForComponentTests.ts"; +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_TIME_RANGE_SUMMARY, +} from "@rilldata/web-common/features/dashboards/stores/test-data/data"; +import { getInitExploreStateForTest } from "@rilldata/web-common/features/dashboards/stores/test-data/helpers"; +import { queryClient } from "@rilldata/web-common/lib/svelte-query/globalQueryClient"; +import { mockAnimationsForComponentTesting } from "@rilldata/web-common/lib/test/mock-animations"; +import { + 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; + }; + }; + }) => 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 web-common unit 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 }), + }; +}); + +// The properties the ai resolver accepts (aiProps in runtime/resolvers/ai.go). +const AIResolverProperties = [ + "agent", + "prompt", + "time_range", + "comparison_time_range", + "time_zone", + "explore", + "dimensions", + "measures", + "where", +]; + +/** A formula alert created in the dialog, as the parser stores it: the legacy metrics resolver over the dialog's query. */ +function getFormulaAlertSpec(): V1AlertSpec { + const queryArgs: V1MetricsViewAggregationRequest = { + metricsView: AD_BIDS_METRICS_NAME, + measures: [{ name: AD_BIDS_IMPRESSIONS_MEASURE }], + dimensions: [], + timeRange: { isoDuration: "P7D", timeZone: "UTC" }, + having: { + cond: { + op: V1Operation.OPERATION_AND, + exprs: [ + { + cond: { + op: V1Operation.OPERATION_GT, + exprs: [{ ident: AD_BIDS_IMPRESSIONS_MEASURE }, { val: 10 }], + }, + }, + ], + }, + }, + }; + const exploreState = getInitExploreStateForTest( + AD_BIDS_METRICS_INIT_WITH_TIME, + AD_BIDS_EXPLORE_INIT, + AD_BIDS_TIME_RANGE_SUMMARY, + ); + 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"] } }, + ], + annotations: { + admin_owner_user_id: "owner-1", + web_open_path: `/explore/${AD_BIDS_EXPLORE_NAME}`, + web_open_state: getProtoFromDashboardState( + exploreState, + AD_BIDS_EXPLORE_INIT, + ), + }, + }; +} + +/** An AI alert created through the API: the ai resolver's properties, and no captured dashboard state. */ +function getAPIAIAlertSpec(): V1AlertSpec { + return { + displayName: "Impressions drop", + resolver: "ai", + resolverProperties: { + prompt: "Impressions dropped against the previous weeks", + explore: AD_BIDS_EXPLORE_NAME, + }, + notifiers: [ + { connector: "email", properties: { recipients: ["user@rilldata.com"] } }, + ], + annotations: { admin_owner_user_id: "owner-1" }, + }; +} + +async function openEditDialog(alertSpec: V1AlertSpec) { + render(AlertDialogTest, { + props: { alertSpec }, + context: new Map([ + ["$$_queryClient", queryClient], + [ + RUNTIME_CONTEXT_KEY, + new RuntimeClient({ host: "http://localhost", instanceId: "test" }), + ], + ]), + }); + await waitFor(() => + expect(screen.getByRole("button", { name: "Next" })).toBeTruthy(), + ); +} + +async function typeCondition(text: string) { + const condition = await waitFor(() => + screen.getByPlaceholderText( + "Revenue dropped unusually against the previous weeks", + ), + ); + await fireEvent.input(condition, { target: { value: text } }); +} + +async function getSavedOptions() { + await waitFor(() => expect(editAlert).toHaveBeenCalledOnce()); + return editAlert.mock.calls[0][0].data.options; +} + +async function clickButton(name: string) { + await act(() => screen.getByRole("button", { name }).click()); +} + +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!, + ); + + localStorage.clear(); + sessionStorage.clear(); + queryClient.clear(); + }); + + afterAll(waitForBodyScrollCleanup); + + it("converts a formula alert to an AI condition without carrying the formula's properties", async () => { + await openEditDialog(getFormulaAlertSpec()); + + // The mode is chosen on the data tab, since it changes which data fields are needed. + await clickButton("AI condition"); + await clickButton("Next"); + await typeCondition("Impressions dropped against the previous weeks"); + await clickButton("Next"); + await clickButton("Update"); + + const options = await getSavedOptions(); + expect(options.resolver).toBe("ai"); + expect(options.queryName).toBeUndefined(); + expect(options.queryArgsJson).toBeUndefined(); + // Only the ai resolver's own properties: the formula's query_name and query_args_json would fail under strict resolver properties. + const props = options.resolverProperties ?? {}; + expect(props).toMatchObject({ + prompt: "Impressions dropped against the previous weeks", + explore: AD_BIDS_EXPLORE_NAME, + }); + for (const key of Object.keys(props)) { + expect(AIResolverProperties).toContain(key); + } + // The formula's measure was not chosen for the AI, so it does not narrow what the AI looks at. + expect(props).not.toHaveProperty("measures"); + }); + + it("restores the formula's measure after leaving the data tab in AI mode", async () => { + await openEditDialog(getFormulaAlertSpec()); + + // The data tab unmounts while another tab is shown, so what it remembers must outlive it. + await clickButton("AI condition"); + await clickButton("Next"); + await clickButton("Back"); + await clickButton("Criteria"); + await clickButton("Next"); + await clickButton("Next"); + await clickButton("Update"); + + const options = await getSavedOptions(); + expect(options.resolver).toBeUndefined(); + const queryArgs = JSON.parse( + options.queryArgsJson ?? "{}", + ) as V1MetricsViewAggregationRequest; + expect(queryArgs.measures?.[0]?.name).toBe(AD_BIDS_IMPRESSIONS_MEASURE); + }); + + it("waits for the explore before editing an AI alert created through the API", async () => { + // Such an alert has no captured dashboard state. Hold the explore response until after the current user's, + // which is when the dialog would otherwise start without knowing the alert's metrics view. + let releaseExplore = () => {}; + const exploreGate = new Promise((resolve) => { + releaseExplore = resolve; + }); + const mockedFetch = globalThis.fetch; + vi.stubGlobal("fetch", async (url: string, init: RequestInit) => { + if (String(url).endsWith("/GetExplore")) await exploreGate; + return mockedFetch(url, init); + }); + try { + render(AlertDialogTest, { + props: { alertSpec: getAPIAIAlertSpec() }, + context: new Map([ + ["$$_queryClient", queryClient], + [ + RUNTIME_CONTEXT_KEY, + new RuntimeClient({ host: "http://localhost", instanceId: "test" }), + ], + ]), + }); + await new Promise((r) => setTimeout(r, 50)); + releaseExplore(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Next" })).toBeTruthy(), + ); + + await clickButton("Next"); + await clickButton("Next"); + await clickButton("Update"); + + const options = await getSavedOptions(); + // The managed alert's YAML refs MetricsView/, so it must not be empty. + expect(options.metricsViewName).toBe(AD_BIDS_METRICS_NAME); + expect(options.resolverProperties).toMatchObject({ + prompt: "Impressions dropped against the previous weeks", + explore: AD_BIDS_EXPLORE_NAME, + }); + } finally { + vi.stubGlobal("fetch", mockedFetch); + } + }); +}); 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 948b748aa823..0f30c648e4d0 100644 --- a/web-admin/src/features/alerts/metadata/AlertMetadata.svelte +++ b/web-admin/src/features/alerts/metadata/AlertMetadata.svelte @@ -23,6 +23,10 @@ formatRefreshSchedule, } from "@rilldata/web-admin/features/scheduled-reports/metadata/utils.ts"; import { IconButton } from "@rilldata/web-common/components/button"; + import { + getAggregationRequestFromAIAlertProperties, + isAIAlertSpec, + } from "@rilldata/web-common/features/alerts/ai-alert-utils"; import * as DropdownMenu from "@rilldata/web-common/components/dropdown-menu"; import CancelCircle from "@rilldata/web-common/components/icons/CancelCircle.svelte"; import ThreeDot from "@rilldata/web-common/components/icons/ThreeDot.svelte"; @@ -77,9 +81,14 @@ $: queryName = alertSpec?.queryName || (alertSpec?.resolverProperties?.query_name as string); - $: metricsViewAggregationRequest = JSON.parse( - queryArgsJson, - ) as V1MetricsViewAggregationRequest; + // An AI alert keeps its data context in the ai resolver's properties, and its Condition replaces the criteria. + $: isAIAlert = isAIAlertSpec(alertSpec); + $: metricsViewAggregationRequest = isAIAlert + ? getAggregationRequestFromAIAlertProperties( + alertSpec?.resolverProperties ?? {}, + metricsViewName ?? "", + ) + : (JSON.parse(queryArgsJson) as V1MetricsViewAggregationRequest); $: dashboardState = useAlertDashboardState(runtimeClient, alertSpec); @@ -254,11 +263,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 8311ada89bf3..5aece8d86b54 100644 --- a/web-admin/src/features/alerts/selectors.ts +++ b/web-admin/src/features/alerts/selectors.ts @@ -1,4 +1,5 @@ import { createAdminServiceSearchProjectUsers } from "@rilldata/web-admin/client"; +import { isAIAlertSpec } from "@rilldata/web-common/features/alerts/ai-alert-utils"; import { getDashboardStateFromUrl } from "@rilldata/web-common/features/dashboards/proto-state/fromProto"; import type { ExploreState } from "@rilldata/web-common/features/dashboards/stores/explore-state"; import { ResourceKind } from "@rilldata/web-common/features/entity-management/resource-selectors"; @@ -60,6 +61,10 @@ export function getAlertDashboardName(alertSpec: V1AlertSpec): string { if (alertSpec.annotations.web_open_path) return getExploreName(alertSpec.annotations.web_open_path); + // An AI alert names the explore the AI looks at in the ai resolver's properties. + if (isAIAlertSpec(alertSpec)) + return (alertSpec.resolverProperties?.explore as string | undefined) ?? ""; + 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 e506b01658f2..f5bd48a0a4af 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,4 +1,6 @@ import { getExploreName } from "@rilldata/web-common/features/explore-mappers/utils"; +import { isAIAlertSpec } from "@rilldata/web-common/features/alerts/ai-alert-utils"; +import { redirect } from "@sveltejs/kit"; export async function load({ parent, url, params }) { const { alert } = await parent(); @@ -11,6 +13,18 @@ export async function load({ parent, url, params }) { alert.alert.spec.annotations["explore"] ?? getExploreName(alert.alert.spec.annotations?.web_open_path); // backwards compatibility + // AI alerts open the AI conversation behind the check that triggered. + // The runtime adds the session ID to the open link, which keeps opening the conversation even if the alert was switched to criteria since. + // 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 || isAIAlertSpec(alert.alert.spec)) { + const path = sessionId + ? `/${organization}/${project}/-/ai/${sessionId}` + : `/${organization}/${project}/-/ai`; + const search = token ? new URLSearchParams({ token }).toString() : ""; + redirect(307, search ? `${path}?${search}` : path); + } + return { organization, project, diff --git a/web-common/src/components/forms/FieldSwitcher.svelte b/web-common/src/components/forms/FieldSwitcher.svelte index 72fd8c5ffb71..990d858f4eed 100644 --- a/web-common/src/components/forms/FieldSwitcher.svelte +++ b/web-common/src/components/forms/FieldSwitcher.svelte @@ -8,7 +8,9 @@
{#each fields as field, i (field)} +