Skip to content
204 changes: 204 additions & 0 deletions admin/server/ai_alert_tools_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
package server_test

import (
"encoding/json"
"fmt"
"testing"

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/ai"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/pkg/activity"
"github.com/rilldata/rill/runtime/testruntime"
"github.com/stretchr/testify/require"
)

// TestAIAlertTools tests creating, listing and deleting alerts with the AI tools, as the chat does:
// through the admin service, which writes them like the alert dialog, and the runtime, which parses and reconciles them.
func TestAIAlertTools(t *testing.T) {
f := newForUserFixture(t)
ctx := t.Context()

runner := ai.NewRunner(f.fix.Runtime, activity.NewNoopClient())
s, err := runner.Session(ctx, &ai.SessionOptions{
InstanceID: f.instance.ID,
CreateIfNotExists: true,
Claims: &runtime.SecurityClaims{
UserID: f.viewerUser.ID,
UserAttributes: map[string]any{"email": f.viewerUser.Email},
Permissions: []runtime.Permission{runtime.UseAI, runtime.ReadObjects, runtime.ReadMetrics},
},
UserAgent: "rill/test",
})
require.NoError(t, err)

createAlert := func(args *ai.CreateAlertArgs) (*ai.CreatedResource, error) {
var res *ai.CreatedResource
_, err := s.CallTool(ctx, ai.RoleUser, ai.CreateAlertName, &res, args)
return res, err
}

var formulaAlert, aiAlert string
t.Run("creates a formula alert like the dialog", func(t *testing.T) {
res, err := createAlert(&ai.CreateAlertArgs{
DisplayName: "Revenue drop",
Explore: "e1",
Measure: "revenue",
Dimension: "country",
Criteria: []ai.AlertCriterion{{Type: "percent_change", Operator: "lt", Value: -10}},
TimeRange: "7D as of latest/D",
Schedule: &ai.Schedule{Cron: "0 9 * * *", TimeZone: "Europe/Madrid"},
})
require.NoError(t, err)
require.Empty(t, res.ReconcileError)
require.Equal(t, fmt.Sprintf("%s/%s/%s/-/alerts/%s", f.fix.Admin.URLs.Frontend(), f.org, f.project, res.Name), res.URL)
formulaAlert = res.Name

spec := testruntime.GetResource(t, f.fix.Runtime, f.instance.ID, runtime.ResourceKindAlert, res.Name).GetAlert().Spec
require.Equal(t, "0 9 * * *", spec.RefreshSchedule.Cron)
require.Equal(t, "Europe/Madrid", spec.RefreshSchedule.TimeZone)
require.Equal(t, []any{f.viewerUser.Email}, spec.Notifiers[0].Properties.AsMap()["recipients"])
// The query is the one the alert dialog saves for the same alert
var query map[string]any
require.NoError(t, json.Unmarshal([]byte(spec.ResolverProperties.AsMap()["query_args_json"].(string)), &query))
require.JSONEq(t, `{
"metricsView": "mv1",
"measures": [
{"name": "revenue"},
{"name": "revenue_delta", "comparisonDelta": {"measure": "revenue"}},
{"name": "revenue_delta_perc", "comparisonRatio": {"measure": "revenue"}}
],
"dimensions": [{"name": "country"}],
"having": {"cond": {"op": "OPERATION_AND", "exprs": [{"cond": {"op": "OPERATION_LT", "exprs": [{"ident": "revenue_delta_perc"}, {"val": -0.1}]}}]}},
"timeRange": {"expression": "7D as of latest/D", "timeZone": "Europe/Madrid"},
"comparisonTimeRange": {"expression": "7D as of latest/D offset -1P", "timeZone": "Europe/Madrid"},
"sort": [{"name": "revenue", "desc": true}]
}`, mustJSON(t, query))
})

t.Run("creates an AI alert on a schedule the dialog can edit", func(t *testing.T) {
args := &ai.CreateAlertArgs{
DisplayName: "Unusual revenue",
Explore: "Revenue #1",
Condition: "Revenue drops unusually compared to recent weeks",
Schedule: &ai.Schedule{Cron: "0 9 * * 1-5"},
}
res, err := createAlert(args)
require.NoError(t, err)
require.Empty(t, res.ReconcileError)
aiAlert = res.Name
spec := testruntime.GetResource(t, f.fix.Runtime, f.instance.ID, runtime.ResourceKindAlert, res.Name).GetAlert().Spec
require.Equal(t, "ai", spec.Resolver)
require.Equal(t, map[string]any{"prompt": args.Condition, "explore": "Revenue #1"}, spec.ResolverProperties.AsMap())
require.Equal(t, f.viewerUser.ID, spec.GetQueryForUserId())
// The alert's page finds its explore from the open path, like for an alert from the dialog
require.Equal(t, "/explore/Revenue%20%231", spec.Annotations["web_open_path"])

// The dialog would read these as monthly on the 1st and as daily, so saving an edit there would move the schedule
for _, cron := range []string{"0 9 15 * *", "0 * * * *"} {
args.Schedule = &ai.Schedule{Cron: cron}
_, err = createAlert(args)
require.ErrorContains(t, err, "invalid cron expression")
}
args.Schedule = nil
_, err = createAlert(args)
require.ErrorContains(t, err, "needs a schedule")
})

t.Run("checks percent of total criteria like the dialog", func(t *testing.T) {
args := &ai.CreateAlertArgs{
DisplayName: "Small countries",
Explore: "e1",
Measure: "revenue",
Criteria: []ai.AlertCriterion{{Type: "percent_of_total", Operator: "lt", Value: 20}},
TimeRange: "7D as of latest/D",
}
_, err := createAlert(args)
require.ErrorContains(t, err, "need a dimension")
args.Dimension = "country"
args.Criteria[0].Value = 120
_, err = createAlert(args)
require.ErrorContains(t, err, "from 0 to 100")
})

t.Run("only sends to project members, and to Slack when it's configured", func(t *testing.T) {
args := &ai.CreateAlertArgs{
DisplayName: "Revenue drop",
Explore: "e1",
Measure: "revenue",
Criteria: []ai.AlertCriterion{{Operator: "lt", Value: 0}},
TimeRange: "7D as of latest/D",
Recipients: &ai.Recipients{Emails: []string{f.outsiderUser.Email}},
}
_, err := createAlert(args)
require.ErrorContains(t, err, "not a member of the project")

// The project has no Slack connector, so the alert couldn't be sent
args.Recipients = &ai.Recipients{SlackChannels: []string{"sales-ops"}}
_, err = createAlert(args)
require.ErrorContains(t, err, "doesn't have Slack configured")
})

t.Run("lists the explores the user can access when the explore isn't one", func(t *testing.T) {
// In a project-level chat, the analyst may only know the metrics view's name
_, err := createAlert(&ai.CreateAlertArgs{
DisplayName: "Revenue drop",
Explore: "mv1",
Measure: "revenue",
Criteria: []ai.AlertCriterion{{Operator: "lt", Value: 0}},
TimeRange: "7D as of latest/D",
})
require.ErrorContains(t, err, `explore "mv1" not found: pass the name of one of the explores the user can access: Revenue #1 (metrics view mv1), e1 (metrics view mv1)`)
})

t.Run("lists the user's own alerts", func(t *testing.T) {
_, err := f.owner.CreateAlert(ctx, &adminv1.CreateAlertRequest{Org: f.org, Project: f.project, Options: &adminv1.AlertOptions{
DisplayName: "Someone else's alert",
MetricsViewName: "mv1",
QueryName: "MetricsViewAggregation",
QueryArgsJson: `{"metrics_view":"mv1","measures":[{"name":"revenue"}]}`,
WebOpenPath: "/explore/e1",
}})
require.NoError(t, err)

var res *ai.ListAlertsResult
_, err = s.CallTool(ctx, ai.RoleUser, ai.ListAlertsName, &res, &ai.ListAlertsArgs{})
require.NoError(t, err)
require.Len(t, res.Alerts, 2)
byName := map[string]*ai.AlertInfo{}
for _, a := range res.Alerts {
byName[a.Name] = a
}
require.Equal(t, "(revenue_delta_perc < -0.1), compared with 7D as of latest/D offset -1P", byName[formulaAlert].Condition)
require.Equal(t, "Revenue drops unusually compared to recent weeks", byName[aiAlert].Condition)
require.Equal(t, "Revenue #1", byName[aiAlert].Explore)
require.Equal(t, fmt.Sprintf("%s/%s/%s/-/alerts/%s", f.fix.Admin.URLs.Frontend(), f.org, f.project, aiAlert), byName[aiAlert].URL)
})

t.Run("deletes only the user's own alerts", func(t *testing.T) {
deleteAlert := func(name string) (*ai.DeleteResourceResult, error) {
var res *ai.DeleteResourceResult
_, err := s.CallTool(ctx, ai.RoleUser, ai.DeleteAlertName, &res, &ai.DeleteResourceArgs{Name: name})
return res, err
}

res, err := deleteAlert(aiAlert)
require.NoError(t, err)
require.Equal(t, "Unusual revenue", res.DisplayName)
ctrl, err := f.fix.Runtime.Controller(ctx, f.instance.ID)
require.NoError(t, err)
_, err = ctrl.Get(ctx, &runtimev1.ResourceName{Kind: runtime.ResourceKindAlert, Name: aiAlert}, false)
require.ErrorIs(t, err, drivers.ErrResourceNotFound)

_, err = deleteAlert(aiAlert)
require.ErrorContains(t, err, "is not one of the user's own")
})
}

func mustJSON(t *testing.T, v any) string {
data, err := json.Marshal(v)
require.NoError(t, err)
return string(data)
}
23 changes: 15 additions & 8 deletions admin/server/for_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ type forUserFixture struct {

// newForUserFixture creates a project owned by a user, with another user as viewer and a third user outside the project,
// and a runtime instance whose admin service is this admin service, acting as the project's primary deployment.
// The instance has the explore "e1" on the metrics view "mv1", with the measure "revenue" and the dimension "country".
// The instance has the explores "e1" and "Revenue #1" (whose name needs escaping in URLs) on the metrics view "mv1", with the measure "revenue" and the dimension "country".
func newForUserFixture(t *testing.T) *forUserFixture {
fix := testadmin.NewWithOptionalRuntime(t, true)
ctx := t.Context()
Expand Down Expand Up @@ -194,10 +194,11 @@ func newForUserFixture(t *testing.T) *forUserFixture {

repoDir := t.TempDir()
for path, data := range map[string]string{
"rill.yaml": "",
"models/bar.sql": `SELECT '2024-01-01T00:00:00Z'::TIMESTAMP AS __time, 'Denmark' AS country, 1 AS revenue`,
"metrics/mv1.yaml": "version: 1\ntype: metrics_view\nmodel: bar\ntimeseries: __time\ndimensions:\n- column: country\nmeasures:\n- name: revenue\n expression: sum(revenue)\n",
"explores/e1.yaml": "type: explore\nmetrics_view: mv1\n",
"rill.yaml": "",
"models/bar.sql": `SELECT '2024-01-01T00:00:00Z'::TIMESTAMP AS __time, 'Denmark' AS country, 1 AS revenue`,
"metrics/mv1.yaml": "version: 1\ntype: metrics_view\nmodel: bar\ntimeseries: __time\ndimensions:\n- column: country\nmeasures:\n- name: revenue\n expression: sum(revenue)\n",
"explores/e1.yaml": "type: explore\nmetrics_view: mv1\n",
"explores/Revenue #1.yaml": "type: explore\nmetrics_view: mv1\n",
} {
abs := filepath.Join(repoDir, path)
require.NoError(t, os.MkdirAll(filepath.Dir(abs), os.ModePerm))
Expand Down Expand Up @@ -237,15 +238,21 @@ func newForUserFixture(t *testing.T) *forUserFixture {
}
require.NoError(t, fix.Runtime.CreateInstance(ctx, inst))
// Creating the instance applies the deployment's config from the admin service, which restarts its controller, so this waits for the new one.
// A wait on the old controller never ends once it's closed, so each wait is bounded and the next try gets the new one.
require.Eventually(t, func() bool {
ctrl, err := fix.Runtime.Controller(ctx, inst.ID)
if err != nil || ctrl.WaitUntilIdle(ctx, false) != nil {
if err != nil {
return false
}
waitCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
if ctrl.WaitUntilIdle(waitCtx, false) != nil {
return false
}
rs, err := ctrl.List(ctx, "", "", false)
return err == nil && len(rs) == 4
return err == nil && len(rs) == 5
}, 30*time.Second, 100*time.Millisecond)
testruntime.RequireReconcileState(t, fix.Runtime, inst.ID, 4, 0, 0)
testruntime.RequireReconcileState(t, fix.Runtime, inst.ID, 5, 0, 0)
go mirrorVirtualFiles(ctx, fix.Admin.DB, proj.ID, fix.Runtime, inst.ID, repoDir)

adm, release, err := fix.Runtime.Admin(ctx, inst.ID)
Expand Down
3 changes: 3 additions & 0 deletions runtime/ai/ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ func NewRunner(rt *runtime.Runtime, activity *activity.Client) *Runner {
RegisterTool(r, &QueryMetricsView{Runtime: rt})
RegisterTool(r, &CreateChart{Runtime: rt})
RegisterTool(r, &ChartData{Runtime: rt})
RegisterTool(r, &CreateAlert{Runtime: rt})
RegisterTool(r, &ListAlerts{Runtime: rt})
RegisterTool(r, &DeleteAlert{Runtime: rt})
RegisterTool(r, &ListSkills{Runtime: rt})
RegisterTool(r, &LoadSkill{Runtime: rt})
RegisterTool(r, &SearchExternalTools{Runtime: rt})
Expand Down
Loading
Loading