Skip to content
Merged
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
24 changes: 17 additions & 7 deletions cmd/root/telemetry_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
// 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
// Matches the upload's own default timeout. A command can set a shorter one
// with TelemetryAuth.Budget. A run waits only once its command
// asks for it (TelemetryAuth.WaitAtExit).
var TelemetryAuthBudget = 3 * time.Second

Expand All @@ -30,23 +31,32 @@ type TelemetryAuth struct {
pending *PendingAuth

// WaitAtExit is whether the end of the run waits for an unfinished
// resolution (within TelemetryAuthBudget). False by default: the
// resolution (within the budget). 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

// Budget is the wait budget of this command, or TelemetryAuthBudget when
// zero. It counts from PreRunE, where the resolution starts, not from the
// end of the run. Set it before the command runs.
Budget time.Duration
Comment thread
simonfaltum marked this conversation as resolved.
Resolved
}

// 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
// its budget (TelemetryAuth.Budget, else 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)
budget := TelemetryAuthBudget
if auth.Budget > 0 {
budget = auth.Budget
}
auth.pending = startTelemetryAuth(cmd, args, budget)
return nil
}
runE := cmd.RunE
Expand All @@ -72,7 +82,7 @@ type PendingAuth struct {
// 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 {
func startTelemetryAuth(cmd *cobra.Command, args []string, budget time.Duration) *PendingAuth {
ctx := cmd.Context()
if telemetry.Disabled(ctx) {
return nil
Expand All @@ -82,7 +92,7 @@ func startTelemetryAuth(cmd *cobra.Command, args []string) *PendingAuth {
shadow.Flags().AddFlagSet(cmd.Flags())
shadow.SetContext(SkipTokenRefresh(SkipLoadBundle(SkipPrompt(sctx))))

p := &PendingAuth{Done: make(chan struct{}), Deadline: time.Now().Add(TelemetryAuthBudget)}
p := &PendingAuth{Done: make(chan struct{}), Deadline: time.Now().Add(budget)}
resolve := TelemetryAuthResolver
go func() {
defer close(p.Done)
Expand Down Expand Up @@ -119,7 +129,7 @@ func (p *PendingAuth) apply(cmd *cobra.Command, wait bool) {
return
}
if wait && !p.Wait() {
log.Debugf(cmd.Context(), "auth for telemetry not resolved within %s; not uploading telemetry", TelemetryAuthBudget)
log.Debugf(cmd.Context(), "auth for telemetry not resolved by %s; not uploading telemetry", p.Deadline.Format(time.RFC3339Nano))
return
}
if p.Cfg != nil {
Expand Down
34 changes: 32 additions & 2 deletions cmd/root/telemetry_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func TestTelemetryAuthFinishedResolutionSurvivesAnExpiredBudget(t *testing.T) {
})
for range 50 {
cmd, _ := authTestCmd(t)
p := startTelemetryAuth(cmd, nil)
p := startTelemetryAuth(cmd, nil, TelemetryAuthBudget)
<-p.Done
telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}})
p.apply(cmd, true)
Expand All @@ -68,10 +68,40 @@ func TestTelemetryAuthNoWaitUsesFinishedResolution(t *testing.T) {
})
for range 50 {
cmd, _ := authTestCmd(t)
p := startTelemetryAuth(cmd, nil)
p := startTelemetryAuth(cmd, nil, TelemetryAuthBudget)
<-p.Done
telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}})
p.apply(cmd, false)
require.True(t, cmdctx.HasConfigUsed(cmd.Context()))
}
}

// A command's own Budget bounds its wait instead of the global one, and a resolution that outlasts it is dropped.
func TestTelemetryAuthCommandBudgetBoundsTheWait(t *testing.T) {
release := make(chan struct{})
defer close(release)
setTelemetryAuth(t, time.Minute, func(cmd *cobra.Command, args []string) error {
<-release
return nil
})
cmd := &cobra.Command{
Use: "test",
RunE: func(cmd *cobra.Command, args []string) error {
telemetry.Log(cmd.Context(), protos.DatabricksCliLog{AitoolsInstallEvent: &protos.AitoolsInstallEvent{}})
return nil
},
}
cmd.Flags().String("profile", "", "")
auth := WithTelemetryAuth(cmd)
auth.WaitAtExit = true
auth.Budget = 100 * time.Millisecond
cmd.SetContext(env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", ""))
start := time.Now()
require.NoError(t, cmd.PreRunE(cmd, nil))

require.NoError(t, cmd.RunE(cmd, nil))
elapsed := time.Since(start)
require.GreaterOrEqual(t, elapsed, auth.Budget)
require.Less(t, elapsed, 5*time.Second)
require.False(t, cmdctx.HasConfigUsed(cmd.Context()))
}
8 changes: 8 additions & 0 deletions cmd/skills/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"io/fs"
"time"

"github.com/databricks/cli/libs/aitools/agents"

Expand All @@ -15,6 +16,12 @@ import (
"golang.org/x/mod/semver"
)

// telemetryAuthBudget favors prompt skills calls over telemetry from slow auth.
// Cold host-metadata lookups or credential helpers that exceed it lose their
// event; a canceled lookup also leaves the metadata cache cold for the next run.
// It bounds only auth, not the subsequent telemetry upload.
const telemetryAuthBudget = 500 * time.Millisecond
Comment thread
simonfaltum marked this conversation as resolved.
Resolved

// 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) {
Expand All @@ -37,6 +44,7 @@ func recordRuns(group *cobra.Command) {
}
// Wrapped last, so its wrapper runs outside ours and sees WaitAtExit after the run.
auth = root.WithTelemetryAuth(c)
auth.Budget = telemetryAuthBudget
}
}

Expand Down
36 changes: 36 additions & 0 deletions cmd/skills/telemetry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"fmt"
"io/fs"
"testing"
"time"

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/env"
libskills "github.com/databricks/cli/libs/skills"
"github.com/databricks/cli/libs/telemetry"
Expand Down Expand Up @@ -111,3 +113,37 @@ func TestRecordRunsDisabledLogsNothing(t *testing.T) {
assert.NoError(t, group.ExecuteContext(ctx))
assert.Empty(t, telemetry.BufferedEvents(ctx))
}

// A run whose source resolved waits for a stuck auth resolution only up to telemetryAuthBudget, not the shared budget.
func TestSkillsRunWaitsAtMostTelemetryAuthBudget(t *testing.T) {
release := make(chan struct{})
defer close(release)
origResolver, origBudget := root.TelemetryAuthResolver, root.TelemetryAuthBudget
t.Cleanup(func() { root.TelemetryAuthResolver, root.TelemetryAuthBudget = origResolver, origBudget })
root.TelemetryAuthBudget = time.Minute
root.TelemetryAuthResolver = func(*cobra.Command, []string) error {
<-release
return nil
}

group := &cobra.Command{Use: "skills"}
group.AddCommand(&cobra.Command{
Use: "list",
RunE: func(cmd *cobra.Command, args []string) error {
_, err := libskills.Resolve(cmd.Context())
return err
},
})
recordRuns(group)
cmd := group.Commands()[0]
cmd.Flags().String("profile", "", "")
ctx := env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", "")
cmd.SetContext(env.Set(ctx, "DATABRICKS_SKILLS_DIR", "../../libs/skills/testdata/release"))

start := time.Now()
require.NoError(t, cmd.PreRunE(cmd, nil))
require.NoError(t, cmd.RunE(cmd, nil))
elapsed := time.Since(start)
assert.GreaterOrEqual(t, elapsed, telemetryAuthBudget)
assert.Less(t, elapsed, 10*time.Second)
}
Loading