Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions acceptance/cmd/skills/telemetry/out.test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cloud = false
31 changes: 31 additions & 0 deletions acceptance/cmd/skills/telemetry/output.txt
Original file line number Diff line number Diff line change
@@ -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
36 changes: 36 additions & 0 deletions acceptance/cmd/skills/telemetry/script
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions acceptance/cmd/skills/telemetry/test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
RecordRequests = true
2 changes: 1 addition & 1 deletion cmd/aitools/autoinstall_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions cmd/aitools/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand Down
6 changes: 6 additions & 0 deletions cmd/aitools/mcp_telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
26 changes: 13 additions & 13 deletions cmd/aitools/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -32,34 +32,34 @@ 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
}
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
Expand Down Expand Up @@ -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
}

Expand All @@ -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
}
4 changes: 2 additions & 2 deletions cmd/aitools/telemetry_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions cmd/skills/skills.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ func buildCommand(_ context.Context, cmd *cobra.Command) {
cmd.AddCommand(newListFilesCmd())
cmd.AddCommand(newReadFileCmd())
cmd.AddCommand(newSearchCmd())
recordRuns(cmd)
}
114 changes: 114 additions & 0 deletions cmd/skills/telemetry.go
Original file line number Diff line number Diff line change
@@ -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 <major>.<minor>.<patch> 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
}
Loading
Loading