diff --git a/acceptance/cmd/skills/telemetry/out.test.toml b/acceptance/cmd/skills/telemetry/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/telemetry/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/telemetry/output.txt b/acceptance/cmd/skills/telemetry/output.txt new file mode 100644 index 00000000000..1d03588eeaa --- /dev/null +++ b/acceptance/cmd/skills/telemetry/output.txt @@ -0,0 +1,31 @@ + +=== skills list under a coding agent: the event and the calling agent are uploaded + +>>> [CLI] skills list +Databricks skills are not installed. To work with Databricks reliably, first run: databricks aitools install + +>>> print_skills +{"calling_agent":"CLAUDE_CODE","command":"LIST","catalog_release_version":"0.0.1","source":"FOLDER","outcome":"SUCCEEDED"} + +=== skills read from a folder: the name is not sent, the release version and the source are + +>>> [CLI] skills read guide-skill + +>>> print_skills +{"calling_agent":null,"command":"READ","catalog_release_version":"0.0.1","source":"FOLDER","outcome":"SUCCEEDED"} + +=== a failed read sends the error category and the version + +>>> [CLI] skills read no-such-skill +Error: unknown skill "no-such-skill": run "databricks skills list" to see the available skills + +>>> print_skills +{"calling_agent":null,"command":"READ","catalog_release_version":"0.0.1","source":"FOLDER","outcome":"FAILED","error_category":"SKILL_NOT_FOUND"} + +=== with telemetry disabled, nothing is uploaded + +>>> [CLI] skills read guide-skill + +>>> print_skills + +=== output is the same with telemetry on and off diff --git a/acceptance/cmd/skills/telemetry/script b/acceptance/cmd/skills/telemetry/script new file mode 100644 index 00000000000..f2576c15648 --- /dev/null +++ b/acceptance/cmd/skills/telemetry/script @@ -0,0 +1,36 @@ +# The skills come from the shared release fixture, a local folder, so no skill name is ever sent. +export DATABRICKS_SKILLS_DIR=$TESTROOT/cmd/skills/release +unset DATABRICKS_CLI_DISABLE_TELEMETRY DATABRICKS_CLI_TELEMETRY_TIMEOUT + +# print_skills prints the skills events uploaded since its last call; print_requests.py clears them. +print_skills() { + if [ -f "$OUT_REQUESTS" ]; then + print_requests.py --oneline //telemetry-ext | jq -c '.body.protoLogs[] | fromjson + | .entry.databricks_cli_log + | select(.skills_command_event != null) + | {calling_agent: .execution_context.calling_agent} + .skills_command_event' + fi +} + +title "skills list under a coding agent: the event and the calling agent are uploaded" +export CLAUDECODE=1 +trace $CLI skills list > LOG.list +trace print_skills +unset CLAUDECODE + +title "skills read from a folder: the name is not sent, the release version and the source are" +trace $CLI skills read guide-skill > LOG.read +trace print_skills + +title "a failed read sends the error category and the version" +musterr trace $CLI skills read no-such-skill +trace print_skills + +title "with telemetry disabled, nothing is uploaded" +DATABRICKS_CLI_DISABLE_TELEMETRY=1 trace $CLI skills read guide-skill > LOG.disabled +trace print_skills + +title "output is the same with telemetry on and off" +$CLI skills list > LOG.on +DATABRICKS_CLI_DISABLE_TELEMETRY=1 $CLI skills list > LOG.off +diff LOG.on LOG.off diff --git a/acceptance/cmd/skills/telemetry/test.toml b/acceptance/cmd/skills/telemetry/test.toml new file mode 100644 index 00000000000..159efe02696 --- /dev/null +++ b/acceptance/cmd/skills/telemetry/test.toml @@ -0,0 +1 @@ +RecordRequests = true diff --git a/cmd/aitools/autoinstall_run.go b/cmd/aitools/autoinstall_run.go index a71a0c7a1d5..0552d7bf097 100644 --- a/cmd/aitools/autoinstall_run.go +++ b/cmd/aitools/autoinstall_run.go @@ -680,7 +680,7 @@ func (t toolsPlan) install(ctx context.Context) (installResult, error) { func updateTools(ctx context.Context, globalDir string, before *installer.InstallState) (installResult, error) { uctx := telemetry.WithNewLogger(ctx) uctx = context.WithValue(uctx, funnelKey{}, &commandFunnel{command: protos.AitoolsCommandUpdate}) - uctx = context.WithValue(uctx, telemetryAuthKey{}, &telemetryAuth{}) + uctx = context.WithValue(uctx, telemetryAuthKey{}, &TelemetryAuth{}) updateErr := runUpdate(uctx, updateFlags{scope: installer.ScopeGlobal, keepModified: true}) // The update refuses the raw skills after it updated the plugins, so a // refusal still reports the plugins it changed. diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index ea43c89606e..26083ffdae3 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -164,7 +164,7 @@ func newInstallCmd(recordSkillsOnly bool) *cobra.Command { var skillsFlag, agentsFlag, scopeFlag, pathFlag string var includeExperimental, skillsOnly bool var projectFlag, globalFlag bool - var auth *telemetryAuth + var auth *TelemetryAuth cmd := &cobra.Command{ Use: "install", @@ -379,7 +379,7 @@ Supported agents: ` + strings.Join(agents.SupportedNames(), ", "), // so it stays instant. The funnel therefore under-counts the fastest // early exits (which usually end before auth resolves), and their // STARTED events, relative to slower ones such as a cancelled prompt. - auth.waitAtExit = true + auth.WaitAtExit = true var outcomes []agentOutcome var runErr error @@ -449,7 +449,7 @@ Supported agents: ` + strings.Join(agents.SupportedNames(), ", "), cmd.Flags().BoolVar(&globalFlag, "global", false, "Install globally (default)") markScopeBoolsDeprecated(cmd) // Resolve auth best-effort and time-bounded so telemetry can upload. - auth = withTelemetryAuth(cmd) + auth = WithTelemetryAuth(cmd) return cmd } diff --git a/cmd/aitools/mcp_telemetry.go b/cmd/aitools/mcp_telemetry.go index 9c240c8b6da..0cd27611fd7 100644 --- a/cmd/aitools/mcp_telemetry.go +++ b/cmd/aitools/mcp_telemetry.go @@ -109,6 +109,12 @@ func mcpServiceType(fullName string) protos.AitoolsMcpService { return protos.AitoolsMcpServiceOtherSystem } +// CallingAgentType returns the agent that drives the CLI, Unspecified when none is detected. The skills commands +// report it as their calling agent too. +func CallingAgentType() protos.AitoolsAgentType { + return callingAgentType() +} + // callingAgentType returns the agent that drives the CLI, Unspecified when none is detected. func callingAgentType() protos.AitoolsAgentType { a := agents.CallingAgent() diff --git a/cmd/aitools/telemetry.go b/cmd/aitools/telemetry.go index 9bf5bbdc1ed..81b0dff24e6 100644 --- a/cmd/aitools/telemetry.go +++ b/cmd/aitools/telemetry.go @@ -23,7 +23,7 @@ import ( // background auth resolution its telemetry upload needs. A resolution still // unfinished when the run ends and the budget has passed drops the events. // Matches the upload's own default timeout. A run waits only once its command -// asks for it (telemetryAuth.waitAtExit). +// asks for it (TelemetryAuth.WaitAtExit). var telemetryAuthBudget = 3 * time.Second // resolveTelemetryAuthFn resolves auth onto cmd's context. A seam for tests. @@ -32,26 +32,26 @@ var resolveTelemetryAuthFn = func(cmd *cobra.Command, args []string) error { return err } -// telemetryAuth is the best-effort auth resolution of one command run. -type telemetryAuth struct { +// TelemetryAuth is the best-effort auth resolution of one command run. +type TelemetryAuth struct { pending *pendingAuth - // waitAtExit is whether the end of the run waits for an unfinished + // WaitAtExit is whether the end of the run waits for an unfinished // resolution (within telemetryAuthBudget). False by default: the // telemetry uploads only if the resolution has already finished, so a run // that ends early stays instant. RunE sets it once the run has gone far // enough to be worth the wait. - waitAtExit bool + WaitAtExit bool } -// withTelemetryAuth makes cmd resolve auth best-effort so its telemetry can +// WithTelemetryAuth makes cmd resolve auth best-effort so its telemetry can // upload at exit: PreRunE starts the resolution in the background, and RunE's // wrapper uses it if it has finished, or waits for it within -// telemetryAuthBudget once RunE sets waitAtExit on the returned value. Nothing +// telemetryAuthBudget once RunE sets WaitAtExit on the returned value. Nothing // is resolved when telemetry is disabled. The command never fails or prompts // because of it. -func withTelemetryAuth(cmd *cobra.Command) *telemetryAuth { - auth := &telemetryAuth{} +func WithTelemetryAuth(cmd *cobra.Command) *TelemetryAuth { + auth := &TelemetryAuth{} cmd.PreRunE = func(cmd *cobra.Command, args []string) error { auth.pending = startTelemetryAuth(cmd, args) return nil @@ -59,7 +59,7 @@ func withTelemetryAuth(cmd *cobra.Command) *telemetryAuth { runE := cmd.RunE cmd.RunE = func(cmd *cobra.Command, args []string) error { err := runE(cmd, args) - auth.pending.apply(cmd, auth.waitAtExit) + auth.pending.apply(cmd, auth.WaitAtExit) return err } return auth @@ -292,12 +292,12 @@ func scopeType(scope string) protos.AitoolsInstallScope { // waitForTelemetryAuth, once the run gets past its cheap early exits. func instrumentCommand(cmd *cobra.Command, command protos.AitoolsCommand) *cobra.Command { runE := withCommandFunnel(command, cmd.RunE) - var auth *telemetryAuth + var auth *TelemetryAuth cmd.RunE = func(cmd *cobra.Command, args []string) error { cmd.SetContext(context.WithValue(cmd.Context(), telemetryAuthKey{}, auth)) return runE(cmd, args) } - auth = withTelemetryAuth(cmd) + auth = WithTelemetryAuth(cmd) return cmd } @@ -308,5 +308,5 @@ type telemetryAuthKey struct{} // confirmation. Only the RunE of a command wrapped by instrumentCommand calls // it. func waitForTelemetryAuth(ctx context.Context) { - ctx.Value(telemetryAuthKey{}).(*telemetryAuth).waitAtExit = true + ctx.Value(telemetryAuthKey{}).(*TelemetryAuth).WaitAtExit = true } diff --git a/cmd/aitools/telemetry_auth_test.go b/cmd/aitools/telemetry_auth_test.go index 82e54f09ce6..e68fd897d42 100644 --- a/cmd/aitools/telemetry_auth_test.go +++ b/cmd/aitools/telemetry_auth_test.go @@ -39,7 +39,7 @@ func noTelemetryAuth(t *testing.T) { setTelemetryAuth(t, time.Second, func(*cobra.Command, []string) error { return nil }) } -// authTestCmd returns a command wired with withTelemetryAuth whose RunE +// authTestCmd returns a command wired with WithTelemetryAuth whose RunE // records that it ran and logs a telemetry event, plus a --profile flag like // root's. Telemetry is enabled on its context whatever the outer environment // says. @@ -62,7 +62,7 @@ func authTestCmdLogging(t *testing.T, logEvent bool) (*cobra.Command, *bool) { cmd.Flags().String("profile", "", "") // These tests exercise the wait, so the command asks for it, as install // does once the plan is confirmed. - withTelemetryAuth(cmd).waitAtExit = true + WithTelemetryAuth(cmd).WaitAtExit = true ctx := telemetry.WithNewLogger(t.Context()) cmd.SetContext(env.Set(ctx, "DATABRICKS_CLI_DISABLE_TELEMETRY", "")) return cmd, &ran diff --git a/cmd/root/root.go b/cmd/root/root.go index d51d031aff0..397f8f03f0d 100644 --- a/cmd/root/root.go +++ b/cmd/root/root.go @@ -289,6 +289,7 @@ func TelemetryExecutionContext(cmd *cobra.Command, start time.Time, exitCode int return protos.ExecutionContext{ CmdExecID: cmdctx.ExecId(ctx), StateLineageHash: telemetry.StateLineageHash(ctx), + CallingAgent: telemetry.CallingAgent(ctx), Version: build.GetInfo().Version, Command: commandString(cmd), OperatingSystem: runtime.GOOS, diff --git a/cmd/skills/skills.go b/cmd/skills/skills.go index 25185cdbc54..07d692e7393 100644 --- a/cmd/skills/skills.go +++ b/cmd/skills/skills.go @@ -23,4 +23,5 @@ func buildCommand(_ context.Context, cmd *cobra.Command) { cmd.AddCommand(newListFilesCmd()) cmd.AddCommand(newReadFileCmd()) cmd.AddCommand(newSearchCmd()) + recordRuns(cmd) } diff --git a/cmd/skills/telemetry.go b/cmd/skills/telemetry.go new file mode 100644 index 00000000000..1ae420d87ca --- /dev/null +++ b/cmd/skills/telemetry.go @@ -0,0 +1,114 @@ +package skills + +import ( + "encoding/json" + "errors" + "io/fs" + "strings" + + "github.com/databricks/cli/cmd/aitools" + libskills "github.com/databricks/cli/libs/skills" + "github.com/databricks/cli/libs/telemetry" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/spf13/cobra" +) + +// recordRuns logs one SkillsCommandEvent per run of each command in the group, and resolves the upload's auth in the +// background, as aitools does. It is best effort: it never fails, prompts or changes output or exit codes. +func recordRuns(group *cobra.Command) { + for _, c := range group.Commands() { + command := commandType(c.Name()) + run := c.RunE + c.RunE = func(cmd *cobra.Command, args []string) error { + if telemetry.Disabled(cmd.Context()) { + return run(cmd, args) + } + ctx, rec := libskills.WithRecord(cmd.Context()) + cmd.SetContext(ctx) + err := run(cmd, args) + logEvent(cmd, command, rec, err) + return err + } + // A run that logged its event waits up to the auth budget for the upload's auth, as install does. + aitools.WithTelemetryAuth(c).WaitAtExit = true + } +} + +func commandType(name string) protos.SkillsCommand { + switch name { + case "list": + return protos.SkillsCommandList + case "read": + return protos.SkillsCommandRead + case "list-files": + return protos.SkillsCommandListFiles + case "read-file": + return protos.SkillsCommandReadFile + case "search": + return protos.SkillsCommandSearch + } + return protos.SkillsCommandUnspecified +} + +// logEvent buffers the event of a run for the upload at exit, and sets the calling agent for its execution context. +func logEvent(cmd *cobra.Command, command protos.SkillsCommand, rec *libskills.Record, err error) { + ctx := cmd.Context() + event := skillsEvent(command, rec, err) + telemetry.Log(ctx, protos.DatabricksCliLog{SkillsCommandEvent: &event}) + if agent := aitools.CallingAgentType(); agent != protos.AitoolsAgentTypeUnspecified { + telemetry.SetCallingAgent(ctx, agent) + } +} + +// skillsEvent builds one run's event. A failed run sends no skill name: it may have asked for one the catalog lacks. +func skillsEvent(command protos.SkillsCommand, rec *libskills.Record, err error) protos.SkillsCommandEvent { + event := protos.SkillsCommandEvent{ + Command: command, + CatalogReleaseVersion: releaseVersion(rec.Version), + Source: protos.SkillsSource(rec.Origin), + Outcome: protos.SkillsCommandOutcomeSucceeded, + } + if err != nil { + event.Outcome = protos.SkillsCommandOutcomeFailed + event.ErrorCategory = errorCategory(err) + return event + } + event.SkillName = rec.SkillName + return event +} + +// releaseVersion returns v when it is .. with no leading "v", as the proto requires, else "". +func releaseVersion(v string) string { + parts := strings.Split(v, ".") + if len(parts) != 3 { + return "" + } + for _, p := range parts { + if p == "" || strings.Trim(p, "0123456789") != "" { + return "" + } + } + return v +} + +// errorCategory classifies a failed run by its error kind. The error's text is never sent: it can carry a typed name. +func errorCategory(err error) protos.SkillsErrorCategory { + _, syntax := errors.AsType[*json.SyntaxError](err) + _, typed := errors.AsType[*json.UnmarshalTypeError](err) + _, pathErr := errors.AsType[*fs.PathError](err) + switch { + case errors.Is(err, libskills.ErrUnknownSkill): + return protos.SkillsErrorCategorySkillNotFound + case errors.Is(err, libskills.ErrUnknownFile): + return protos.SkillsErrorCategoryFileNotFound + case errors.Is(err, libskills.ErrNoSource), errors.Is(err, libskills.ErrSourceUnreachable): + return protos.SkillsErrorCategorySourceUnavailable + case errors.Is(err, libskills.ErrUnsafeManifestPath), errors.Is(err, libskills.ErrManifestTooLarge), syntax, typed: + return protos.SkillsErrorCategoryCatalogInvalid + case errors.Is(err, fs.ErrPermission): + return protos.SkillsErrorCategoryPermissionDenied + case pathErr: + return protos.SkillsErrorCategoryFilesystem + } + return protos.SkillsErrorCategoryUncategorized +} diff --git a/cmd/skills/telemetry_test.go b/cmd/skills/telemetry_test.go new file mode 100644 index 00000000000..6afe5652dd5 --- /dev/null +++ b/cmd/skills/telemetry_test.go @@ -0,0 +1,76 @@ +package skills + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "testing" + + "github.com/databricks/cli/libs/env" + libskills "github.com/databricks/cli/libs/skills" + "github.com/databricks/cli/libs/telemetry" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +func TestSkillsEventSuccessfulRead(t *testing.T) { + rec := &libskills.Record{Origin: libskills.OriginLive, Version: "1.4.0", SkillName: "databricks-apps"} + assert.Equal(t, protos.SkillsCommandEvent{ + Command: protos.SkillsCommandRead, + SkillName: "databricks-apps", + CatalogReleaseVersion: "1.4.0", + Source: protos.SkillsSourceLive, + Outcome: protos.SkillsCommandOutcomeSucceeded, + }, skillsEvent(protos.SkillsCommandRead, rec, nil)) +} + +// A failed read never sends the name it was asked for: it may be a typo or private text. +func TestSkillsEventFailedReadSendsNoName(t *testing.T) { + rec := &libskills.Record{Origin: libskills.OriginFolder, Version: "1.2.0", SkillName: "typo"} + err := fmt.Errorf("%w %q", libskills.ErrUnknownSkill, "typo") + event := skillsEvent(protos.SkillsCommandRead, rec, err) + assert.Empty(t, event.SkillName) + assert.Equal(t, protos.SkillsCommandOutcomeFailed, event.Outcome) + assert.Equal(t, protos.SkillsErrorCategorySkillNotFound, event.ErrorCategory) +} + +func TestReleaseVersion(t *testing.T) { + for in, want := range map[string]string{ + "1.4.0": "1.4.0", "10.0.12": "10.0.12", + "v1.4.0": "", "1.4": "", "1.4.0-rc1": "", "1..0": "", "1.4.x": "", "": "", + } { + assert.Equal(t, want, releaseVersion(in), in) + } +} + +func TestErrorCategory(t *testing.T) { + var v map[string]any + tests := map[string]struct { + err error + want protos.SkillsErrorCategory + }{ + "unknown skill": {fmt.Errorf("%w", libskills.ErrUnknownSkill), protos.SkillsErrorCategorySkillNotFound}, + "unknown file": {libskills.ErrUnknownFile, protos.SkillsErrorCategoryFileNotFound}, + "unreachable": {fmt.Errorf("%w: %w", libskills.ErrSourceUnreachable, errors.New("dial")), protos.SkillsErrorCategorySourceUnavailable}, + "manifest syntax": {json.Unmarshal([]byte("{"), &v), protos.SkillsErrorCategoryCatalogInvalid}, + "manifest large": {libskills.ErrManifestTooLarge, protos.SkillsErrorCategoryCatalogInvalid}, + "permission": {fmt.Errorf("read: %w", fs.ErrPermission), protos.SkillsErrorCategoryPermissionDenied}, + "filesystem": {&fs.PathError{Op: "open", Path: "x", Err: errors.New("i/o")}, protos.SkillsErrorCategoryFilesystem}, + "anything else": {errors.New("something else"), protos.SkillsErrorCategoryUncategorized}, + } + for name, tc := range tests { + assert.Equal(t, tc.want, errorCategory(tc.err), name) + } +} + +func TestRecordRunsDisabledLogsNothing(t *testing.T) { + group := &cobra.Command{Use: "skills"} + group.AddCommand(&cobra.Command{Use: "list", RunE: func(*cobra.Command, []string) error { return nil }}) + recordRuns(group) + group.SetArgs([]string{"list"}) + ctx := env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", "1") + assert.NoError(t, group.ExecuteContext(ctx)) + assert.Empty(t, telemetry.BufferedEvents(ctx)) +} diff --git a/libs/skills/record.go b/libs/skills/record.go new file mode 100644 index 00000000000..7e0ea404196 --- /dev/null +++ b/libs/skills/record.go @@ -0,0 +1,110 @@ +package skills + +import ( + "context" + "slices" + + "github.com/databricks/cli/libs/env" +) + +// Origin says which kind of source served a catalog. Its values are the names of the proto's SkillsSource enum. +type Origin string + +const ( + OriginLive Origin = "LIVE" + OriginCache Origin = "CACHE" + OriginBundled Origin = "BUNDLED" + OriginFolder Origin = "FOLDER" +) + +// Record is what a command read from its source, for its telemetry event. WithRecord installs one on a context. +type Record struct { + Origin Origin + + // Version is the release version of the catalog read, empty when none was. + Version string + + // SkillName is the skill a ReadFile read, when the catalog lists it and its names are published. + SkillName string +} + +type recordKey struct{} + +// WithRecord returns ctx with a new Record for one command run, and that Record. +func WithRecord(ctx context.Context) (context.Context, *Record) { + rec := &Record{} + return context.WithValue(ctx, recordKey{}, rec), rec +} + +// record wraps src so that reads through it fill in the Record of ctx. Without a Record, src is returned as it is. +func record(ctx context.Context, src Source, origin Origin) Source { + rec, ok := ctx.Value(recordKey{}).(*Record) + if !ok { + return src + } + rec.Origin = origin + r := &recordingSource{Source: src, rec: rec} + if sizer, ok := src.(FileSizer); ok { + return &recordingSizer{recordingSource: r, sizer: sizer} + } + return r +} + +// recordingSource passes every call to the source it wraps, and records what was read. +type recordingSource struct { + Source + rec *Record + + // catalog is the last catalog read through this source. + catalog *Catalog +} + +func (r *recordingSource) Catalog(ctx context.Context) (*Catalog, error) { + catalog, err := r.Source.Catalog(ctx) + if err != nil { + return nil, err + } + r.catalog = catalog + r.rec.Version = catalog.Version + return catalog, nil +} + +func (r *recordingSource) ReadFile(ctx context.Context, skill, file string) ([]byte, error) { + data, err := r.Source.ReadFile(ctx, skill, file) + if err != nil { + return data, err + } + // The catalog gives the version, and says whether it lists the skill. A failed read asks for neither. + if catalog, cerr := r.catalogOnce(ctx); cerr == nil && r.namesArePublished(ctx) && listsSkill(catalog, skill) { + r.rec.SkillName = skill + } + return data, nil +} + +// namesArePublished reports whether the skill names are published. A folder's, or a ref's or base URL's, are the user's. +func (r *recordingSource) namesArePublished(ctx context.Context) bool { + return r.rec.Origin != OriginFolder && env.Get(ctx, "DATABRICKS_SKILLS_REF") == "" && env.Get(ctx, "DATABRICKS_SKILLS_BASE_URL") == "" +} + +// catalogOnce returns the catalog read through this source, reading it first if no call has made one. A read-file +// does not read the catalog itself, so this is where it is read. +func (r *recordingSource) catalogOnce(ctx context.Context) (*Catalog, error) { + if r.catalog != nil { + return r.catalog, nil + } + return r.Catalog(ctx) +} + +func listsSkill(catalog *Catalog, skill string) bool { + return slices.ContainsFunc(catalog.Skills, func(s Skill) bool { return s.Name == skill }) +} + +// recordingSizer is a recordingSource over a source that sizes its files, so that list-files still finds a FileSizer. +type recordingSizer struct { + *recordingSource + sizer FileSizer +} + +func (r *recordingSizer) FileSize(ctx context.Context, skill, file string) (int64, error) { + return r.sizer.FileSize(ctx, skill, file) +} diff --git a/libs/skills/record_test.go b/libs/skills/record_test.go new file mode 100644 index 00000000000..7015fbe1700 --- /dev/null +++ b/libs/skills/record_test.go @@ -0,0 +1,92 @@ +package skills + +import ( + "context" + "os" + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const recordFixture = "testdata/release" + +// catalogOnly is a source that cannot size its files. +type catalogOnly struct{ Source } + +func TestRecordFolderSendsNoName(t *testing.T) { + ctx, rec := WithRecord(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", recordFixture)) + src, err := Resolve(ctx) + require.NoError(t, err) + + _, err = src.ReadFile(ctx, "alpha", "SKILL.md") + require.NoError(t, err) + assert.Equal(t, Record{Origin: OriginFolder, Version: "1.2.0"}, *rec) +} + +// Only a listed skill of a published source is named, and a ref or base URL the user chose makes the names their own. +func TestRecordSkillName(t *testing.T) { + tests := []struct { + name, key, skill, file, want string + }{ + {name: "listed skill", skill: "alpha", file: "SKILL.md", want: "alpha"}, + {name: "unlisted skill", skill: "missing", file: "SKILL.md"}, + {name: "unlisted file", skill: "alpha", file: "nope.md"}, + {name: "ref set", key: "DATABRICKS_SKILLS_REF", skill: "alpha", file: "SKILL.md"}, + {name: "base URL set", key: "DATABRICKS_SKILLS_BASE_URL", skill: "alpha", file: "SKILL.md"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + if tc.key != "" { + ctx = env.Set(ctx, tc.key, "test-value") + } + ctx, rec := WithRecord(ctx) + src := record(ctx, NewFSSource(os.DirFS(recordFixture), "fixture"), OriginLive) + + _, _ = src.ReadFile(ctx, tc.skill, tc.file) + assert.Equal(t, tc.want, rec.SkillName) + }) + } +} + +func TestRecordKeepsFileSizer(t *testing.T) { + ctx, _ := WithRecord(t.Context()) + _, sized := record(ctx, NewFSSource(os.DirFS(recordFixture), "fixture"), OriginFolder).(FileSizer) + _, plain := record(ctx, catalogOnly{NewFSSource(os.DirFS(recordFixture), "fixture")}, OriginFolder).(FileSizer) + assert.True(t, sized) + assert.False(t, plain) +} + +// countingSource counts the catalog reads made through it. +type countingSource struct { + Source + catalogs int +} + +func (c *countingSource) Catalog(ctx context.Context) (*Catalog, error) { + c.catalogs++ + return c.Source.Catalog(ctx) +} + +// A successful read reads the catalog once, for the version and the listing. A failed read reads neither. +func TestRecordReadFileCatalogCalls(t *testing.T) { + tests := []struct { + name, file string + origin Origin + want int + }{ + {name: "listed skill", file: "SKILL.md", origin: OriginLive, want: 1}, + {name: "failed read", file: "nope.md", origin: OriginLive, want: 0}, + {name: "folder", file: "SKILL.md", origin: OriginFolder, want: 1}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx, _ := WithRecord(t.Context()) + src := &countingSource{Source: NewFSSource(os.DirFS(recordFixture), "fixture")} + _, _ = record(ctx, src, tc.origin).ReadFile(ctx, "alpha", tc.file) + assert.Equal(t, tc.want, src.catalogs) + }) + } +} diff --git a/libs/skills/resolve.go b/libs/skills/resolve.go index a8d8886ca1d..d51f5dfe0c4 100644 --- a/libs/skills/resolve.go +++ b/libs/skills/resolve.go @@ -17,13 +17,14 @@ const dirEnv = "DATABRICKS_SKILLS_DIR" var ErrNoSource = errors.New("no skills source is available in this build") // Resolve returns the source that serves skills. For now that is the folder in -// DATABRICKS_SKILLS_DIR, when it is set. Otherwise no source is available. +// DATABRICKS_SKILLS_DIR, when it is set. Otherwise no source is available. On a +// context from WithRecord, the source records what it reads into the Record. func Resolve(ctx context.Context) (Source, error) { dir := env.Get(ctx, dirEnv) if dir == "" { return nil, ErrNoSource } - return NewFSSource(os.DirFS(dir), filepath.ToSlash(dir)), nil + return record(ctx, NewFSSource(os.DirFS(dir), filepath.ToSlash(dir)), OriginFolder), nil } // LocalCatalog returns the freshest catalog that needs no network call. For now diff --git a/libs/telemetry/logger.go b/libs/telemetry/logger.go index cd8db66468b..82387f7d1a4 100644 --- a/libs/telemetry/logger.go +++ b/libs/telemetry/logger.go @@ -94,6 +94,7 @@ type logger struct { mu sync.Mutex logs []protos.FrontendLog stateLineageHash string + callingAgent protos.AitoolsAgentType // upload is the config Upload authenticates with, as SetUploadConfig set it. Nil leaves cmdctx.ConfigUsed to it. upload *config.Config @@ -122,6 +123,22 @@ func StateLineageHash(ctx context.Context) string { return "" } +// SetCallingAgent records the coding agent that ran the command, so that the command's execution context can report +// it as calling_agent. Like Log, it is a no-op without a logger. +func SetCallingAgent(ctx context.Context, agent protos.AitoolsAgentType) { + if l, ok := loggerFromContext(ctx); ok { + l.callingAgent = agent + } +} + +// CallingAgent returns the value recorded by SetCallingAgent, or "" if none was. +func CallingAgent(ctx context.Context) protos.AitoolsAgentType { + if l, ok := loggerFromContext(ctx); ok { + return l.callingAgent + } + return "" +} + func (l *logger) log(event protos.DatabricksCliLog) { l.mu.Lock() defer l.mu.Unlock() diff --git a/libs/telemetry/protos/databricks_cli_log.go b/libs/telemetry/protos/databricks_cli_log.go index 8c5ec415c28..b97bc653112 100644 --- a/libs/telemetry/protos/databricks_cli_log.go +++ b/libs/telemetry/protos/databricks_cli_log.go @@ -35,6 +35,9 @@ type ExecutionContext struct { // Exit code of the CLI command. // We want to serialize the zero value as well so the omitempty tag is not set. ExitCode int64 `json:"exit_code"` + + // Coding agent that ran this command, detected from the CLI's environment. Unset when none is detected. + CallingAgent AitoolsAgentType `json:"calling_agent,omitempty"` } type CliTestEvent struct { diff --git a/libs/telemetry/protos/frontend_log.go b/libs/telemetry/protos/frontend_log.go index 2341357741c..51a9145864d 100644 --- a/libs/telemetry/protos/frontend_log.go +++ b/libs/telemetry/protos/frontend_log.go @@ -33,4 +33,5 @@ type DatabricksCliLog struct { AitoolsHintEvent *AitoolsHintEvent `json:"aitools_hint_event,omitempty"` AitoolsCommandEvent *AitoolsCommandEvent `json:"aitools_command_event,omitempty"` AitoolsAutoInstallEvent *AitoolsAutoInstallEvent `json:"aitools_auto_install_event,omitempty"` + SkillsCommandEvent *SkillsCommandEvent `json:"skills_command_event,omitempty"` } diff --git a/libs/telemetry/protos/skills_command.go b/libs/telemetry/protos/skills_command.go new file mode 100644 index 00000000000..d0eff78d117 --- /dev/null +++ b/libs/telemetry/protos/skills_command.go @@ -0,0 +1,66 @@ +package protos + +// SkillsCommandEvent mirrors SkillsCommandEvent in the databricks_cli lumberjack proto: one event per +// `databricks skills` command run. The calling agent is ExecutionContext.CallingAgent, not a field here. +type SkillsCommandEvent struct { + Command SkillsCommand `json:"command,omitempty"` + + // SkillName is set only for a successful read or read-file of a published skill. + SkillName string `json:"skill_name,omitempty"` + + // CatalogReleaseVersion is .. with no leading "v", or unset. + CatalogReleaseVersion string `json:"catalog_release_version,omitempty"` + + Source SkillsSource `json:"source,omitempty"` + + Outcome SkillsCommandOutcome `json:"outcome,omitempty"` + + // ErrorCategory is set for a failed outcome only. + ErrorCategory SkillsErrorCategory `json:"error_category,omitempty"` +} + +// SkillsCommand mirrors SkillsCommand.Type. +type SkillsCommand string + +const ( + SkillsCommandUnspecified SkillsCommand = "TYPE_UNSPECIFIED" + SkillsCommandList SkillsCommand = "LIST" + SkillsCommandRead SkillsCommand = "READ" + SkillsCommandListFiles SkillsCommand = "LIST_FILES" + SkillsCommandReadFile SkillsCommand = "READ_FILE" + SkillsCommandSearch SkillsCommand = "SEARCH" +) + +// SkillsSource mirrors SkillsSource.Type. +type SkillsSource string + +const ( + SkillsSourceUnspecified SkillsSource = "TYPE_UNSPECIFIED" + SkillsSourceLive SkillsSource = "LIVE" + SkillsSourceCache SkillsSource = "CACHE" + SkillsSourceBundled SkillsSource = "BUNDLED" + SkillsSourceFolder SkillsSource = "FOLDER" +) + +// SkillsCommandOutcome mirrors SkillsCommandOutcome.Type. +type SkillsCommandOutcome string + +const ( + SkillsCommandOutcomeUnspecified SkillsCommandOutcome = "TYPE_UNSPECIFIED" + SkillsCommandOutcomeSucceeded SkillsCommandOutcome = "SUCCEEDED" + SkillsCommandOutcomeFailed SkillsCommandOutcome = "FAILED" +) + +// SkillsErrorCategory mirrors SkillsErrorCategory.Type. Only the categories the CLI sends are listed here. +type SkillsErrorCategory string + +const ( + SkillsErrorCategoryUnspecified SkillsErrorCategory = "TYPE_UNSPECIFIED" + SkillsErrorCategoryUncategorized SkillsErrorCategory = "UNCATEGORIZED" + SkillsErrorCategorySkillNotFound SkillsErrorCategory = "SKILL_NOT_FOUND" + SkillsErrorCategoryFileNotFound SkillsErrorCategory = "FILE_NOT_FOUND" + SkillsErrorCategoryCatalogInvalid SkillsErrorCategory = "CATALOG_INVALID" + SkillsErrorCategorySourceUnavailable SkillsErrorCategory = "SOURCE_UNAVAILABLE" + SkillsErrorCategoryPermissionDenied SkillsErrorCategory = "PERMISSION_DENIED" + SkillsErrorCategoryFilesystem SkillsErrorCategory = "FILESYSTEM" +)