Skip to content
Merged
1 change: 1 addition & 0 deletions .nextchanges/air/final-log-links.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Repeat the Jobs run link after live log streaming ends. ([#7571](https://github.com/databricks/cli/pull/7571))
17 changes: 17 additions & 0 deletions cmd/air/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/cmdctx"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/flags"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/apierr"
Expand Down Expand Up @@ -195,6 +196,14 @@ func runLogs(ctx context.Context, cmd *cobra.Command, req logRequest) error {
}

out := cmd.OutOrStdout()
if !req.jsonOutput && !req.staticView && !status.terminal() {

@caroline-db caroline-db Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add test coverage for the final links?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TestLogsCommandPrintsGuidanceWhenStreamingIsInterrupted already sets up a live stream. Adding a runs/get-output handler would let it cover both the normal end and Ctrl-C.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added regression coverage in d1bc4f6: the fixture now transitions from RUNNING to a terminal state, and the command tests check the final Jobs link after both successful and failed streams, unchanged JSON output, and the link on interruption. Existing completed-run and past-retry checks still pass. Also restored .nextchanges/air/final-log-links.md as requested in your review. Focused command tests, Go vet, and changelog validation passed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pardis-beikzadeh-db Normal completion (success/failure, text/JSON) and Ctrl-C are covered in d1bc4f6 and 3ff3882. The final footer contains only the Jobs run URL, so it does not call runs/get-output. The AIR changelog entry was also restored in d1bc4f6. Full go test ./cmd/air -count=1, Go vet, and changelog validation pass.

runURL := req.runURL
if runURL == "" {
workspaceID, _ := strconv.ParseInt(w.Config.WorkspaceID, 10, 64)
runURL = dashboardURL(w.Config.Host, req.runID, workspaceID)
}
defer printJobRunLink(ctx, out, runURL)
}
success, err := fetchLogs(ctx, w, out, req, status)
if err != nil {
if errors.Is(err, apierr.ErrResourceDoesNotExist) {
Expand Down Expand Up @@ -248,3 +257,11 @@ func fetchLogs(ctx context.Context, w *databricks.WorkspaceClient, out io.Writer
}
return success, err
}

// printJobRunLink leaves the run link below the streamed output, including on failure.
func printJobRunLink(ctx context.Context, out io.Writer, runURL string) {
renderer, colorOn := cmdio.NewRenderer(ctx, out)
p := newPalette(renderer)
fmt.Fprintln(out)
fmt.Fprintln(out, "View job run at: "+link(colorOn, p.blue, runURL, runURL))
}
46 changes: 45 additions & 1 deletion cmd/air/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ func TestLogsCommandPrintsGuidanceWhenStreamingIsInterrupted(t *testing.T) {
var buf bytes.Buffer
client := newTestWorkspaceClient(t, srv.URL)
client.Config.Profile = "team profile"
client.Config.WorkspaceID = "42"
ctx = cmdio.InContext(ctx, cmdio.NewIO(ctx, flags.OutputText, nil, &buf, &buf, "", ""))
ctx = cmdctx.SetWorkspaceClient(ctx, client)
cmd := withOutput(newLogsCommand(), flags.OutputText)
Expand All @@ -398,7 +399,7 @@ func TestLogsCommandPrintsGuidanceWhenStreamingIsInterrupted(t *testing.T) {

err := cmd.RunE(cmd, []string{"5"})
require.ErrorIs(t, err, root.ErrAlreadyPrinted)
assert.Contains(t, buf.String(), "Streaming logs interrupted.")
assert.Contains(t, buf.String(), "View job run at: "+srv.URL+"/jobs/runs/5?o=42\n\nStreaming logs interrupted.")
assert.Contains(t, buf.String(), "To check status:\ndatabricks air get 5 -p 'team profile'")
assert.Contains(t, buf.String(), "To resume streaming logs:\ndatabricks air logs 5 -p 'team profile'")
}
Expand Down Expand Up @@ -452,3 +453,46 @@ func TestLogsPastRetryOfActiveRunIsStatic(t *testing.T) {
// streamer must not re-poll (that is the loop this test guards against).
assert.Equal(t, 1, getRunHits)
}

func TestLogsCommandRepeatsRunLinkAfterStreaming(t *testing.T) {
for _, result := range []string{"SUCCESS", "FAILED"} {
for _, output := range []flags.Output{flags.OutputText, flags.OutputJSON} {
t.Run(result+"/"+string(output), func(t *testing.T) {
srv := watchServer(t, result)
var buf bytes.Buffer
ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), output, nil, &buf, &buf, "", ""))
ctx = cmdctx.SetWorkspaceClient(ctx, newTestWorkspaceClient(t, srv.URL))
cmd := withOutput(newLogsCommand(), output)
cmd.SetContext(ctx)
cmd.SetOut(&buf)

err := cmd.RunE(cmd, []string{"777"})
if result == "FAILED" {
require.ErrorIs(t, err, root.ErrAlreadyPrinted)
} else {
require.NoError(t, err)
}
if output == flags.OutputJSON {
assert.Contains(t, buf.String(), `"line":"step 2"`)
assert.NotContains(t, buf.String(), "View job run at:")
} else {
assert.Equal(t, "step 1\nstep 2\n\nView job run at: "+srv.URL+"/jobs/runs/777\n", buf.String())
}
})
}
}
}

func TestRunLogsPreservesSubmittedRunURL(t *testing.T) {
srv := watchServer(t, "SUCCESS")
var buf bytes.Buffer
ctx := cmdctx.SetWorkspaceClient(cmdio.MockDiscard(t.Context()), newTestWorkspaceClient(t, srv.URL))
cmd := withOutput(&cobra.Command{}, flags.OutputText)
cmd.SetContext(ctx)
cmd.SetOut(&buf)
runURL := srv.URL + "/jobs/runs/777?o=42"

err := runLogs(ctx, cmd, logRequest{runID: 777, runURL: runURL, attempt: -1, tailLines: -1})
require.NoError(t, err)
assert.True(t, strings.HasSuffix(buf.String(), "\n\nView job run at: "+runURL+"\n"), buf.String())
}
2 changes: 2 additions & 0 deletions cmd/air/logstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ var errBricklensFeatureDisabled = errors.New("bricklens logs unavailable; fallin
// same flags. windowMinutes and tailLines are mutually exclusive.
type logRequest struct {
runID int64
// runURL preserves the URL already shown by air run --watch.
runURL string
// node is the node index to fetch; node 0 always exists.
node int
// nodeSet distinguishes an explicit --node 0 from the default, so a download
Expand Down
1 change: 1 addition & 0 deletions cmd/air/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ field, pass its path to -h as a separate argument:
maxRetries := cfg.maxRetries()
req := logRequest{
runID: runID,
runURL: dashboardURL,
attempt: -1,
tailLines: -1,
jsonOutput: jsonOut,
Expand Down
40 changes: 30 additions & 10 deletions cmd/air/run_watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/cmdctx"
Expand All @@ -18,11 +20,15 @@ import (
"github.com/stretchr/testify/require"
)

// watchServer serves submit, the auth probe, a terminal runs/get, and a single
// page of Bricklens logs — everything `air run --watch` touches after submit.
// watchServer serves submit, the auth probe, a RUNNING-to-terminal transition,
// and a page of Bricklens logs.
// resultState is the terminal result the run reports (e.g. SUCCESS, FAILED).
func watchServer(t *testing.T, resultState string) *httptest.Server {
t.Helper()
oldPollInterval := bricklensPollInterval
bricklensPollInterval = time.Millisecond
t.Cleanup(func() { bricklensPollInterval = oldPollInterval })
var runGets atomic.Int32
runGet := `{
"run_id": 777,
"start_time": 1700000000000,
Expand All @@ -35,12 +41,18 @@ func watchServer(t *testing.T, resultState string) *httptest.Server {
case strings.HasSuffix(r.URL.Path, "/jobs/runs/submit"):
_, _ = w.Write([]byte(`{"run_id": 777}`))
case r.URL.Path == "/api/2.2/jobs/runs/get":
if runGets.Add(1) == 1 {
_, _ = w.Write([]byte(`{"run_id":777,"start_time":1700000000000,"state":{"life_cycle_state":"RUNNING"},"tasks":[{"run_id":778,"attempt_number":0}]}`))
return
}
_, _ = w.Write([]byte(runGet))
case strings.HasPrefix(r.URL.Path, "/api/2.0/ai-training/workflows/by-run-id/"):
_, _ = w.Write([]byte(`{"log_records": [
{"time_unix_nano": 1700000002000000000, "body": "step 2", "node_index": 0},
{"time_unix_nano": 1700000001000000000, "body": "step 1", "node_index": 0}
]}`))
first := `{"time_unix_nano":1700000001000000000,"body":"step 1","node_index":0}`
second := `{"time_unix_nano":1700000002000000000,"body":"step 2","node_index":0}`
if r.URL.Query().Get("ascending") == "false" {
first, second = second, first
}
_, _ = fmt.Fprintf(w, `{"log_records":[%s,%s]}`, first, second)
default:
// Me() probe, workspace-id, SDK config discovery.
_, _ = w.Write([]byte(`{"userName": "u@example.com", "workspace_id": 1}`))
Expand Down Expand Up @@ -101,7 +113,9 @@ func runWatchCmdWithConfig(t *testing.T, out flags.Output, buf *bytes.Buffer, sr
require.NoError(t, cmd.Flags().Set("watch", "true"))

ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), out, nil, buf, buf, "", ""))
ctx = cmdctx.SetWorkspaceClient(ctx, newTestWorkspaceClient(t, srvURL))
client := newTestWorkspaceClient(t, srvURL)
client.Config.WorkspaceID = "42"
ctx = cmdctx.SetWorkspaceClient(ctx, client)
cmd.SetContext(ctx)
cmd.SetOut(buf)
return cmd.RunE(cmd, nil)
Expand All @@ -122,12 +136,13 @@ compute:

func TestRunWatchStreamsLogs(t *testing.T) {
var buf bytes.Buffer
err := runWatchCmd(t, flags.OutputText, &buf, watchServer(t, "SUCCESS").URL)
srv := watchServer(t, "SUCCESS")
err := runWatchCmd(t, flags.OutputText, &buf, srv.URL)
require.NoError(t, err)

out := buf.String()
assert.Contains(t, out, "Submitted workload with Job Run ID: 777")
assert.Contains(t, out, "View job run at: ")
assert.Equal(t, 2, strings.Count(out, "View job run at: "+srv.URL+"/jobs/runs/777?o=42\n"))
assert.Contains(t, out, "Monitoring run and streaming logs...")
// Retries are announced only when one happens, so a healthy run doesn't look like it failed.
assert.NotContains(t, out, "retried")
Expand All @@ -137,6 +152,7 @@ func TestRunWatchStreamsLogs(t *testing.T) {
assert.Contains(t, out, "───")
// The submitted run's logs stream through, oldest-first.
assert.Contains(t, out, "step 1\nstep 2")
assert.True(t, strings.HasSuffix(out, "\n\nView job run at: "+srv.URL+"/jobs/runs/777?o=42\n"), out)
}

func TestRunWatchMultinodeIdentifiesStreamedNode(t *testing.T) {
Expand All @@ -162,6 +178,7 @@ func TestRunWatchJSONEmitsSubmittedThenLogs(t *testing.T) {
assert.Contains(t, all, `"type":"LOG"`)
assert.Contains(t, all, `"line":"step 1"`)
assert.NotContains(t, all, "Monitoring run and streaming logs")
assert.NotContains(t, all, "View job run at:")
// The last line is the closing terminal-status envelope carrying SUCCESS.
assert.Contains(t, lines[len(lines)-1], `"status":"SUCCESS"`)
assert.Contains(t, lines[len(lines)-1], `"run_id":"777"`)
Expand All @@ -175,15 +192,18 @@ func TestRunWatchJSONFailedRunTerminalEnvelope(t *testing.T) {
require.ErrorIs(t, err, root.ErrAlreadyPrinted)
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
assert.Contains(t, lines[len(lines)-1], `"status":"FAILED"`)
assert.NotContains(t, buf.String(), "View job run at:")
}

func TestRunWatchFailedRunExitsNonZero(t *testing.T) {
var buf bytes.Buffer
// A run that ends FAILED streams its logs but exits non-zero, surfaced as
// ErrAlreadyPrinted (the output was already written).
err := runWatchCmd(t, flags.OutputText, &buf, watchServer(t, "FAILED").URL)
srv := watchServer(t, "FAILED")
err := runWatchCmd(t, flags.OutputText, &buf, srv.URL)
require.ErrorIs(t, err, root.ErrAlreadyPrinted)
assert.Contains(t, buf.String(), "step 1\nstep 2")
assert.True(t, strings.HasSuffix(buf.String(), "\n\nView job run at: "+srv.URL+"/jobs/runs/777?o=42\n"), buf.String())
}

func TestHandleWatchResultPrintsProfileAwareResumeCommand(t *testing.T) {
Expand Down
Loading