diff --git a/cmd/aitools/autoinstall_run.go b/cmd/aitools/autoinstall_run.go index 0552d7bf097..d2a95e02dd3 100644 --- a/cmd/aitools/autoinstall_run.go +++ b/cmd/aitools/autoinstall_run.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" @@ -680,7 +681,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{}, &root.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 26083ffdae3..bae73d73b48 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 *root.TelemetryAuth cmd := &cobra.Command{ Use: "install", @@ -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 = root.WithTelemetryAuth(cmd) return cmd } diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index d392c6fde69..8f30816a1ff 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -189,7 +189,7 @@ Supported agents: ` + strings.Join(mcpAgentNames(), ", "), } runErr := runMcpAdd(ctx, cmd, f, jsonMode, out) logMcpEvent(ctx, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: root.CallingAgentType(), Operation: protos.AitoolsMcpOperationAdd, Servers: addServerResults(out.Servers), }) diff --git a/cmd/aitools/mcp_login.go b/cmd/aitools/mcp_login.go index 83e94c01466..47276688ef4 100644 --- a/cmd/aitools/mcp_login.go +++ b/cmd/aitools/mcp_login.go @@ -178,7 +178,7 @@ func signInEvent(operation protos.AitoolsMcpOperation, out *mcpSignInOutput, err return signInEventOf(out.Service, out.State, out.alreadySignedIn, err) } return protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: root.CallingAgentType(), Operation: operation, Servers: []protos.AitoolsMcpServerResult{signOutServerResult(out.Service, out.State, err)}, } diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 188d0f584bb..68a0e87b31a 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -152,7 +152,7 @@ func writeRemoveJSON(cmd *cobra.Command, out *removeOutput, runErr error) error // output is written. A run that logged no event touched no server, so it has nothing to upload and sets no config. func logRemoveEvent(ctx context.Context, out *removeOutput) { if !logMcpEvent(ctx, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: root.CallingAgentType(), Operation: protos.AitoolsMcpOperationRemove, Servers: out.results, }) { diff --git a/cmd/aitools/mcp_telemetry.go b/cmd/aitools/mcp_telemetry.go index 0cd27611fd7..d839cb83fac 100644 --- a/cmd/aitools/mcp_telemetry.go +++ b/cmd/aitools/mcp_telemetry.go @@ -4,7 +4,7 @@ import ( "context" "strings" - "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/auth" "github.com/databricks/cli/libs/log" @@ -30,7 +30,7 @@ func setUploadConfig(ctx context.Context, profileName, configFile string, bound return } } - cfg, err := mcp.BoundUploadConfig(ctx, profileName, configFile, telemetryAuthBudget) + cfg, err := mcp.BoundUploadConfig(ctx, profileName, configFile, root.TelemetryAuthBudget) if err != nil { log.Debugf(ctx, "telemetry: cannot resolve profile %s to upload with: %s", profileName, err) telemetry.SkipUpload(ctx) @@ -109,28 +109,13 @@ 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() - if a == nil { - return protos.AitoolsAgentTypeUnspecified - } - return agentType(a.Name) -} - // proxyAgentType returns the agent that started the proxy: the --agent flag when given, else the // detected agent. func proxyAgentType(flag string) protos.AitoolsAgentType { if flag == "" { - return callingAgentType() + return root.CallingAgentType() } - return agentType(flag) + return root.AgentType(flag) } // logMcpEvent buffers an MCP event for the next upload and reports whether it did. An event without server @@ -184,7 +169,7 @@ func addServerResults(servers []addServerOutput) []protos.AitoolsMcpServerResult for _, a := range s.Agents { r := protos.AitoolsMcpServerResult{ Service: mcpServiceType(s.Service), - Agent: agentType(a.Name), + Agent: root.AgentType(a.Name), SignInState: addSignInState(s), } switch a.Status { @@ -205,7 +190,7 @@ func addServerResults(servers []addServerOutput) []protos.AitoolsMcpServerResult // removeServerResult returns the result of removing one server from one agent config. An entry that was deleted, or // pruned (its record dropped), is CHANGED. An entry that was changed outside this CLI is SKIPPED: it is left in place. func removeServerResult(service, agent string, outcome removeOutcome, err error) protos.AitoolsMcpServerResult { - r := protos.AitoolsMcpServerResult{Service: mcpServiceType(service), Agent: agentType(agent)} + r := protos.AitoolsMcpServerResult{Service: mcpServiceType(service), Agent: root.AgentType(agent)} switch { case err != nil: r.Outcome = protos.AitoolsTargetOutcomeFailed @@ -252,7 +237,7 @@ func signInServerResult(service, state string, alreadySignedIn bool, err error) // already signed in is UNCHANGED. func signInEventOf(service, state string, alreadySignedIn bool, err error) protos.AitoolsMcpEvent { return protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: root.CallingAgentType(), Operation: protos.AitoolsMcpOperationSignIn, Servers: []protos.AitoolsMcpServerResult{signInServerResult(service, state, alreadySignedIn, err)}, } diff --git a/cmd/aitools/mcp_telemetry_test.go b/cmd/aitools/mcp_telemetry_test.go index a6e05d331c3..cab1797638e 100644 --- a/cmd/aitools/mcp_telemetry_test.go +++ b/cmd/aitools/mcp_telemetry_test.go @@ -13,6 +13,7 @@ import ( "slices" "testing" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/env" @@ -335,7 +336,7 @@ func TestBoundProfileCount(t *testing.T) { func TestSignInEventOf(t *testing.T) { // An ACTIVE credential that the add found signed in is UNCHANGED, as add --login reports it. assert.Equal(t, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: root.CallingAgentType(), Operation: protos.AitoolsMcpOperationSignIn, Servers: []protos.AitoolsMcpServerResult{{ Service: protos.AitoolsMcpServiceGitHub, diff --git a/cmd/aitools/telemetry.go b/cmd/aitools/telemetry.go index 81b0dff24e6..636e8ca8f38 100644 --- a/cmd/aitools/telemetry.go +++ b/cmd/aitools/telemetry.go @@ -3,164 +3,16 @@ package aitools import ( "cmp" "context" - "log/slog" "slices" - "time" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" - "github.com/databricks/cli/libs/cmdctx" - "github.com/databricks/cli/libs/log" - "github.com/databricks/cli/libs/log/handler" "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" - "github.com/databricks/databricks-sdk-go/config" "github.com/spf13/cobra" ) -// telemetryAuthBudget bounds how long after its start a command waits for the -// 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). -var telemetryAuthBudget = 3 * time.Second - -// resolveTelemetryAuthFn resolves auth onto cmd's context. A seam for tests. -var resolveTelemetryAuthFn = func(cmd *cobra.Command, args []string) error { - _, err := root.MustAnyClient(cmd, args) - return err -} - -// 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 - // 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 -} - -// 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 -// is resolved when telemetry is disabled. The command never fails or prompts -// because of it. -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) - return err - } - return auth -} - -// pendingAuth is a background auth resolution started by startTelemetryAuth. -type pendingAuth struct { - done chan struct{} - deadline time.Time - cfg *config.Config -} - -// startTelemetryAuth resolves auth in the background on a shadow command. The -// shadow shares cmd's flags (for --profile) but not its context, so a -// resolution that outlives the budget never touches cmd's context. It logs at -// Debug only, so its discarded errors do not interleave with the command's -// output and prompts. It never refreshes an OAuth token (root.SkipTokenRefresh), -// as the command may exit before a refresh finishes; an expired cached token -// fails the resolution and drops the events. -func startTelemetryAuth(cmd *cobra.Command, args []string) *pendingAuth { - ctx := cmd.Context() - if telemetry.Disabled(ctx) { - return nil - } - sctx := log.NewContext(ctx, slog.New(handler.DebugOnlyHandler{Handler: log.GetLogger(ctx).Handler()})) - shadow := &cobra.Command{Use: cmd.Use} - shadow.Flags().AddFlagSet(cmd.Flags()) - shadow.SetContext(root.SkipTokenRefresh(root.SkipLoadBundle(root.SkipPrompt(sctx)))) - - p := &pendingAuth{done: make(chan struct{}), deadline: time.Now().Add(telemetryAuthBudget)} - resolve := resolveTelemetryAuthFn - go func() { - defer close(p.done) - defer func() { - if r := recover(); r != nil { - log.Debugf(sctx, "auth for telemetry panicked: %v", r) - } - }() - if err := resolve(shadow, args); err != nil { - log.Debugf(sctx, "auth for telemetry failed: %v", err) - return - } - if resolved := shadow.Context(); cmdctx.HasConfigUsed(resolved) { - p.cfg = cmdctx.ConfigUsed(resolved) - } - }() - return p -} - -// apply puts the resolved config on cmd's context for the upload if the -// resolution has finished, waiting for it until the deadline when wait is set. -// A run that logged no event has nothing to upload, so it does not wait. Only -// the config is copied: the upload needs nothing else, and a workspace client -// on the context would change how root decorates the command's own errors. -func (p *pendingAuth) apply(cmd *cobra.Command, wait bool) { - if p == nil { - return - } - if len(telemetry.BufferedEvents(cmd.Context())) == 0 { - return - } - if !wait && !p.finished() { - log.Debugf(cmd.Context(), "auth for telemetry not resolved yet; not uploading telemetry") - return - } - if wait && !p.wait() { - log.Debugf(cmd.Context(), "auth for telemetry not resolved within %s; not uploading telemetry", telemetryAuthBudget) - return - } - if p.cfg != nil { - cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), p.cfg)) - } -} - -// wait reports whether the resolution finished by the deadline. A resolution -// that finished before the wait starts always counts: once a command outlasts -// the budget, a select on both channels would pick between them at random. -func (p *pendingAuth) wait() bool { - if p.finished() { - return true - } - timer := time.NewTimer(time.Until(p.deadline)) - defer timer.Stop() - select { - case <-p.done: - return true - case <-timer.C: - return false - } -} - -// finished reports whether the resolution has finished, without waiting. -func (p *pendingAuth) finished() bool { - select { - case <-p.done: - return true - default: - return false - } -} - // installOpts is the subset of install options telemetry records, kept narrow // so every field that leaves the machine is visible here. type installOpts struct { @@ -200,7 +52,7 @@ func agentResultsField(outcomes []agentOutcome) []protos.AitoolsAgentResult { continue } out = append(out, protos.AitoolsAgentResult{ - Agent: agentType(o.agent.Name), + Agent: root.AgentType(o.agent.Name), ErrorCategory: o.errorCategory, }) } @@ -231,7 +83,7 @@ func agentTypes(targets []*agents.Agent) []protos.AitoolsAgentType { if a == nil { continue } - t := agentType(a.Name) + t := root.AgentType(a.Name) if _, ok := seen[t]; ok { continue } @@ -242,37 +94,6 @@ func agentTypes(targets []*agents.Agent) []protos.AitoolsAgentType { return out } -// agentType maps a CLI agent registry name to its telemetry enum. Every agent -// in agents.Registry must have a case here; TestAgentTypeCoversRegistry fails -// if one is missing. The default maps genuinely unknown names to Unspecified -// so an older proto never drops an install. -func agentType(name string) protos.AitoolsAgentType { - switch name { - case agents.NameClaudeCode: - return protos.AitoolsAgentTypeClaudeCode - case agents.NameCursor: - return protos.AitoolsAgentTypeCursor - case agents.NameCodex: - return protos.AitoolsAgentTypeCodex - case agents.NameOpenCode: - return protos.AitoolsAgentTypeOpenCode - case agents.NameCopilot: - return protos.AitoolsAgentTypeCopilot - case agents.NameAntigravity: - return protos.AitoolsAgentTypeAntigravity - case agents.NamePi: - return protos.AitoolsAgentTypePi - case agents.NameGemini: - return protos.AitoolsAgentTypeGemini - case agents.NameGoose: - return protos.AitoolsAgentTypeGoose - case agents.NameKiro: - return protos.AitoolsAgentTypeKiro - default: - return protos.AitoolsAgentTypeUnspecified - } -} - // scopeType maps a resolved install scope to its telemetry enum. func scopeType(scope string) protos.AitoolsInstallScope { switch scope { @@ -292,21 +113,21 @@ 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 *root.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 = root.WithTelemetryAuth(cmd) return cmd } type telemetryAuthKey struct{} // waitForTelemetryAuth makes the end of an instrumented run wait for the auth -// resolution within telemetryAuthBudget, as install does past its plan +// resolution within TelemetryAuthBudget, as install does past its plan // 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{}).(*root.TelemetryAuth).WaitAtExit = true } diff --git a/cmd/aitools/telemetry_auth_test.go b/cmd/aitools/telemetry_auth_test.go index e68fd897d42..6d459b660f0 100644 --- a/cmd/aitools/telemetry_auth_test.go +++ b/cmd/aitools/telemetry_auth_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdctx" @@ -27,10 +28,10 @@ import ( // setTelemetryAuth replaces the auth resolver and the wait budget for a test. func setTelemetryAuth(t *testing.T, budget time.Duration, resolve func(cmd *cobra.Command, args []string) error) { - origResolve, origBudget := resolveTelemetryAuthFn, telemetryAuthBudget - t.Cleanup(func() { resolveTelemetryAuthFn, telemetryAuthBudget = origResolve, origBudget }) - resolveTelemetryAuthFn = resolve - telemetryAuthBudget = budget + origResolve, origBudget := root.TelemetryAuthResolver, root.TelemetryAuthBudget + t.Cleanup(func() { root.TelemetryAuthResolver, root.TelemetryAuthBudget = origResolve, origBudget }) + root.TelemetryAuthResolver = resolve + root.TelemetryAuthBudget = budget } // noTelemetryAuth replaces the auth resolver with a no-op, so a test that runs @@ -39,7 +40,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 root.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 +63,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 + root.WithTelemetryAuth(cmd).WaitAtExit = true ctx := telemetry.WithNewLogger(t.Context()) cmd.SetContext(env.Set(ctx, "DATABRICKS_CLI_DISABLE_TELEMETRY", "")) return cmd, &ran @@ -137,24 +138,6 @@ func TestTelemetryAuthNoEventDoesNotWait(t *testing.T) { assert.False(t, cmdctx.HasConfigUsed(cmd.Context())) } -// A command that outlasts the budget still uploads when its resolution -// finished in time. Budget 0 makes every wait start past the deadline; the -// repeats make a coin-flip between "done" and "expired" fail reliably. -func TestTelemetryAuthFinishedResolutionSurvivesAnExpiredBudget(t *testing.T) { - setTelemetryAuth(t, 0, func(cmd *cobra.Command, args []string) error { - cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), &config.Config{Host: "https://ws.test"})) - return nil - }) - for range 50 { - cmd, _ := authTestCmd(t) - p := startTelemetryAuth(cmd, nil) - <-p.done - telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}}) - p.apply(cmd, true) - require.True(t, cmdctx.HasConfigUsed(cmd.Context())) - } -} - func TestTelemetryAuthPanicDoesNotFailTheCommand(t *testing.T) { setTelemetryAuth(t, time.Second, func(cmd *cobra.Command, args []string) error { panic("boom") }) cmd, ran := authTestCmd(t) @@ -233,23 +216,6 @@ func TestTelemetryAuthRunEWithoutPreRun(t *testing.T) { assert.True(t, *ran) } -// Without the wait, a resolution that has already finished still counts. The -// repeats make a race between "done" and "not done" fail reliably. -func TestTelemetryAuthNoWaitUsesFinishedResolution(t *testing.T) { - setTelemetryAuth(t, time.Second, func(cmd *cobra.Command, args []string) error { - cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), &config.Config{Host: "https://ws.test"})) - return nil - }) - for range 50 { - cmd, _ := authTestCmd(t) - p := startTelemetryAuth(cmd, nil) - <-p.done - telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}}) - p.apply(cmd, false) - require.True(t, cmdctx.HasConfigUsed(cmd.Context())) - } -} - // blockTelemetryAuth makes the resolution finish only once the returned func // is called (or the test ends), with a budget long enough that a run that // waits for it is easy to tell apart from one that does not. diff --git a/cmd/aitools/telemetry_test.go b/cmd/aitools/telemetry_test.go index 160bb4fe98e..2caf2f09cb1 100644 --- a/cmd/aitools/telemetry_test.go +++ b/cmd/aitools/telemetry_test.go @@ -68,17 +68,6 @@ func TestAgentsField(t *testing.T) { } } -// TestAgentTypeCoversRegistry fails when an agent is added to agents.Registry -// without a matching telemetry enum in agentType. This is the guard against -// silently logging a new agent as UNSPECIFIED. -func TestAgentTypeCoversRegistry(t *testing.T) { - for _, a := range agents.Registry { - assert.NotEqualf(t, protos.AitoolsAgentTypeUnspecified, agentType(a.Name), - "agent %q has no telemetry enum: add a case to agentType and a value to "+ - "AitoolsAgentType in enum.proto (Universe) + aitools_install.go (CLI)", a.Name) - } -} - func TestScopeType(t *testing.T) { assert.Equal(t, protos.AitoolsInstallScopeGlobal, scopeType(installer.ScopeGlobal)) assert.Equal(t, protos.AitoolsInstallScopeProject, scopeType(installer.ScopeProject)) diff --git a/cmd/root/root.go b/cmd/root/root.go index 397f8f03f0d..1f4522bd4b0 100644 --- a/cmd/root/root.go +++ b/cmd/root/root.go @@ -314,3 +314,44 @@ func ReportUnknownSubcommand(cmd *cobra.Command, args []string) error { } return cmd.Help() } + +// AgentType maps a CLI agent registry name to its telemetry enum. Every agent +// in agents.Registry must have a case here; TestAgentTypeCoversRegistry fails +// if one is missing. The default maps genuinely unknown names to Unspecified +// so an older proto never drops an install. +func AgentType(name string) protos.AitoolsAgentType { + switch name { + case agents.NameClaudeCode: + return protos.AitoolsAgentTypeClaudeCode + case agents.NameCursor: + return protos.AitoolsAgentTypeCursor + case agents.NameCodex: + return protos.AitoolsAgentTypeCodex + case agents.NameOpenCode: + return protos.AitoolsAgentTypeOpenCode + case agents.NameCopilot: + return protos.AitoolsAgentTypeCopilot + case agents.NameAntigravity: + return protos.AitoolsAgentTypeAntigravity + case agents.NamePi: + return protos.AitoolsAgentTypePi + case agents.NameGemini: + return protos.AitoolsAgentTypeGemini + case agents.NameGoose: + return protos.AitoolsAgentTypeGoose + case agents.NameKiro: + return protos.AitoolsAgentTypeKiro + default: + return protos.AitoolsAgentTypeUnspecified + } +} + +// 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 { + a := agents.CallingAgent() + if a == nil { + return protos.AitoolsAgentTypeUnspecified + } + return AgentType(a.Name) +} diff --git a/cmd/root/root_test.go b/cmd/root/root_test.go index 417e505f22d..907c53c7825 100644 --- a/cmd/root/root_test.go +++ b/cmd/root/root_test.go @@ -12,8 +12,10 @@ import ( "strings" "testing" + "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/cmdctx" + "github.com/databricks/cli/libs/telemetry/protos" "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/apierr" "github.com/databricks/databricks-sdk-go/config" @@ -287,3 +289,14 @@ func TestExecuteRaisesTheSignalAutoInstallCaught(t *testing.T) { assert.Equal(t, []os.Signal{os.Interrupt}, raised) assert.Contains(t, logged, "no telemetry logs to upload", "the telemetry upload runs before the CLI ends") } + +// TestAgentTypeCoversRegistry fails when an agent is added to agents.Registry +// without a matching telemetry enum in root.AgentType. This is the guard against +// silently logging a new agent as UNSPECIFIED. +func TestAgentTypeCoversRegistry(t *testing.T) { + for _, a := range agents.Registry { + assert.NotEqualf(t, protos.AitoolsAgentTypeUnspecified, AgentType(a.Name), + "agent %q has no telemetry enum: add a case to root.AgentType and a value to "+ + "AitoolsAgentType in enum.proto (Universe) + aitools_install.go (CLI)", a.Name) + } +} diff --git a/cmd/root/telemetry_auth.go b/cmd/root/telemetry_auth.go new file mode 100644 index 00000000000..753275503a7 --- /dev/null +++ b/cmd/root/telemetry_auth.go @@ -0,0 +1,155 @@ +package root + +import ( + "log/slog" + "time" + + "github.com/databricks/cli/libs/cmdctx" + "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/log/handler" + "github.com/databricks/cli/libs/telemetry" + "github.com/databricks/databricks-sdk-go/config" + "github.com/spf13/cobra" +) + +// TelemetryAuthBudget bounds how long after its start a command waits for the +// 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). +var TelemetryAuthBudget = 3 * time.Second + +// TelemetryAuthResolver resolves auth onto cmd's context. A seam for tests. +var TelemetryAuthResolver = func(cmd *cobra.Command, args []string) error { + _, err := MustAnyClient(cmd, args) + return err +} + +// 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 + // 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 +} + +// 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 +// is resolved when telemetry is disabled. The command never fails or prompts +// because of it. +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) + return err + } + return auth +} + +// pendingAuth is a background auth resolution started by startTelemetryAuth. +type pendingAuth struct { + done chan struct{} + deadline time.Time + cfg *config.Config +} + +// startTelemetryAuth resolves auth in the background on a shadow command. The +// shadow shares cmd's flags (for --profile) but not its context, so a +// resolution that outlives the budget never touches cmd's context. It logs at +// Debug only, so its discarded errors do not interleave with the command's +// output and prompts. It never refreshes an OAuth token (SkipTokenRefresh), +// as the command may exit before a refresh finishes; an expired cached token +// fails the resolution and drops the events. +func startTelemetryAuth(cmd *cobra.Command, args []string) *pendingAuth { + ctx := cmd.Context() + if telemetry.Disabled(ctx) { + return nil + } + sctx := log.NewContext(ctx, slog.New(handler.DebugOnlyHandler{Handler: log.GetLogger(ctx).Handler()})) + shadow := &cobra.Command{Use: cmd.Use} + shadow.Flags().AddFlagSet(cmd.Flags()) + shadow.SetContext(SkipTokenRefresh(SkipLoadBundle(SkipPrompt(sctx)))) + + p := &pendingAuth{done: make(chan struct{}), deadline: time.Now().Add(TelemetryAuthBudget)} + resolve := TelemetryAuthResolver + go func() { + defer close(p.done) + defer func() { + if r := recover(); r != nil { + log.Debugf(sctx, "auth for telemetry panicked: %v", r) + } + }() + if err := resolve(shadow, args); err != nil { + log.Debugf(sctx, "auth for telemetry failed: %v", err) + return + } + if resolved := shadow.Context(); cmdctx.HasConfigUsed(resolved) { + p.cfg = cmdctx.ConfigUsed(resolved) + } + }() + return p +} + +// apply puts the resolved config on cmd's context for the upload if the +// resolution has finished, waiting for it until the deadline when wait is set. +// A run that logged no event has nothing to upload, so it does not wait. Only +// the config is copied: the upload needs nothing else, and a workspace client +// on the context would change how root decorates the command's own errors. +func (p *pendingAuth) apply(cmd *cobra.Command, wait bool) { + if p == nil { + return + } + if len(telemetry.BufferedEvents(cmd.Context())) == 0 { + return + } + if !wait && !p.finished() { + log.Debugf(cmd.Context(), "auth for telemetry not resolved yet; not uploading telemetry") + return + } + if wait && !p.wait() { + log.Debugf(cmd.Context(), "auth for telemetry not resolved within %s; not uploading telemetry", TelemetryAuthBudget) + return + } + if p.cfg != nil { + cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), p.cfg)) + } +} + +// wait reports whether the resolution finished by the deadline. A resolution +// that finished before the wait starts always counts: once a command outlasts +// the budget, a select on both channels would pick between them at random. +func (p *pendingAuth) wait() bool { + if p.finished() { + return true + } + timer := time.NewTimer(time.Until(p.deadline)) + defer timer.Stop() + select { + case <-p.done: + return true + case <-timer.C: + return false + } +} + +// finished reports whether the resolution has finished, without waiting. +func (p *pendingAuth) finished() bool { + select { + case <-p.done: + return true + default: + return false + } +} diff --git a/cmd/root/telemetry_auth_test.go b/cmd/root/telemetry_auth_test.go new file mode 100644 index 00000000000..77b4a678637 --- /dev/null +++ b/cmd/root/telemetry_auth_test.go @@ -0,0 +1,77 @@ +package root + +import ( + "testing" + "time" + + "github.com/databricks/cli/libs/cmdctx" + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/telemetry" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/databricks/databricks-sdk-go/config" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" +) + +// setTelemetryAuth replaces the auth resolver and the wait budget for a test. +func setTelemetryAuth(t *testing.T, budget time.Duration, resolve func(cmd *cobra.Command, args []string) error) { + origResolve, origBudget := TelemetryAuthResolver, TelemetryAuthBudget + t.Cleanup(func() { TelemetryAuthResolver, TelemetryAuthBudget = origResolve, origBudget }) + TelemetryAuthResolver = resolve + TelemetryAuthBudget = budget +} + +// authTestCmd returns a command wired with WithTelemetryAuth whose RunE logs a +// telemetry event, plus a --profile flag like root's. Telemetry is enabled on +// its context whatever the outer environment says. +func authTestCmd(t *testing.T) (*cobra.Command, *bool) { + ran := false + cmd := &cobra.Command{ + Use: "test", + RunE: func(cmd *cobra.Command, args []string) error { + ran = true + telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}}) + return nil + }, + } + cmd.Flags().String("profile", "", "") + WithTelemetryAuth(cmd).WaitAtExit = true + ctx := telemetry.WithNewLogger(t.Context()) + cmd.SetContext(env.Set(ctx, "DATABRICKS_CLI_DISABLE_TELEMETRY", "")) + return cmd, &ran +} + +// A command that outlasts the budget still uploads when its resolution +// finished in time. Budget 0 makes every wait start past the deadline; the +// repeats make a coin-flip between "done" and "expired" fail reliably. +func TestTelemetryAuthFinishedResolutionSurvivesAnExpiredBudget(t *testing.T) { + setTelemetryAuth(t, 0, func(cmd *cobra.Command, args []string) error { + cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), &config.Config{Host: "https://ws.test"})) + return nil + }) + for range 50 { + cmd, _ := authTestCmd(t) + p := startTelemetryAuth(cmd, nil) + <-p.done + telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}}) + p.apply(cmd, true) + require.True(t, cmdctx.HasConfigUsed(cmd.Context())) + } +} + +// Without the wait, a resolution that has already finished still counts. The +// repeats make a race between "done" and "not done" fail reliably. +func TestTelemetryAuthNoWaitUsesFinishedResolution(t *testing.T) { + setTelemetryAuth(t, time.Second, func(cmd *cobra.Command, args []string) error { + cmd.SetContext(cmdctx.SetConfigUsed(cmd.Context(), &config.Config{Host: "https://ws.test"})) + return nil + }) + for range 50 { + cmd, _ := authTestCmd(t) + p := startTelemetryAuth(cmd, nil) + <-p.done + telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}}) + p.apply(cmd, false) + require.True(t, cmdctx.HasConfigUsed(cmd.Context())) + } +} diff --git a/cmd/skills/telemetry.go b/cmd/skills/telemetry.go index 1ae420d87ca..343f04e315f 100644 --- a/cmd/skills/telemetry.go +++ b/cmd/skills/telemetry.go @@ -6,7 +6,7 @@ import ( "io/fs" "strings" - "github.com/databricks/cli/cmd/aitools" + "github.com/databricks/cli/cmd/root" libskills "github.com/databricks/cli/libs/skills" "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" @@ -30,7 +30,7 @@ func recordRuns(group *cobra.Command) { 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 + root.WithTelemetryAuth(c).WaitAtExit = true } } @@ -55,7 +55,7 @@ func logEvent(cmd *cobra.Command, command protos.SkillsCommand, rec *libskills.R ctx := cmd.Context() event := skillsEvent(command, rec, err) telemetry.Log(ctx, protos.DatabricksCliLog{SkillsCommandEvent: &event}) - if agent := aitools.CallingAgentType(); agent != protos.AitoolsAgentTypeUnspecified { + if agent := root.CallingAgentType(); agent != protos.AitoolsAgentTypeUnspecified { telemetry.SetCallingAgent(ctx, agent) } }