-
Notifications
You must be signed in to change notification settings - Fork 63
Add pscale insights errors show and anomalies show #1350
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,5 +76,7 @@ func AnomaliesCmd(ch *cmdutil.Helper) *cobra.Command { | |
| }, | ||
| } | ||
|
|
||
| cmd.AddCommand(AnomaliesShowCmd(ch)) | ||
|
|
||
| return cmd | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| package insights | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/planetscale/cli/internal/cmdutil" | ||
| ps "github.com/planetscale/cli/internal/planetscale" | ||
| "github.com/planetscale/cli/internal/printer" | ||
| ) | ||
|
|
||
| // CorrelationRow is a query correlated with an anomaly, for table output. | ||
| type CorrelationRow struct { | ||
| Correlation float64 `header:"correlation" json:"r"` | ||
| Fingerprint string `header:"fingerprint" json:"fingerprint"` | ||
| Keyspace string `header:"keyspace" json:"keyspace"` | ||
| TabletType string `header:"tablet type" json:"tablet_type"` | ||
| Query string `header:"query" json:"normalized_sql"` | ||
| } | ||
|
|
||
| // AnomaliesShowCmd shows an anomaly and the queries correlated with it. | ||
| func AnomaliesShowCmd(ch *cmdutil.Helper) *cobra.Command { | ||
| cmd := &cobra.Command{ | ||
| Use: "show <database> <branch> <anomaly-id>", | ||
| Short: "Show an anomaly and its correlated queries", | ||
| Long: `Show a single anomaly from 'pscale insights anomalies <database> <branch>', | ||
| along with the queries whose activity correlates with it.`, | ||
| Example: ` pscale insights anomalies show mydb main anomaly-id --org myorg`, | ||
| Args: cmdutil.RequiredArgs("database", "branch", "anomaly-id"), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| ctx := cmd.Context() | ||
| database, branch, anomalyID := args[0], args[1], args[2] | ||
|
|
||
| client, err := ch.Client() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| end := ch.Printer.PrintProgress(fmt.Sprintf("Fetching anomaly %s on %s/%s...", | ||
| printer.BoldBlue(anomalyID), printer.BoldBlue(database), printer.BoldBlue(branch))) | ||
| defer end() | ||
|
|
||
| anomaly, err := client.QueryInsights.GetAnomaly(ctx, &ps.GetAnomalyRequest{ | ||
| Organization: ch.Config.Organization, | ||
| Database: database, | ||
| Branch: branch, | ||
| AnomalyID: anomalyID, | ||
| }) | ||
| if err != nil { | ||
| return notFoundError(ch, err, database, branch) | ||
| } | ||
| end() | ||
|
|
||
| if ch.Printer.Format() == printer.JSON { | ||
| return ch.Printer.PrintJSON(anomaly) | ||
| } | ||
|
|
||
| periodEnd := "" | ||
| if !anomaly.PeriodEnd.IsZero() { | ||
| periodEnd = anomaly.PeriodEnd.Format("2006-01-02 15:04") | ||
| } | ||
| if err := ch.Printer.PrintResource([]*AnomalyRow{{ | ||
| ID: anomaly.ID, | ||
| Active: anomaly.Active, | ||
| PeriodStart: anomaly.PeriodStart.Format("2006-01-02 15:04"), | ||
| PeriodEnd: periodEnd, | ||
| MinutesInViolation: anomaly.MinutesInViolation, | ||
| }}); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if ch.Printer.Format() != printer.Human { | ||
| return nil | ||
| } | ||
|
|
||
| if len(anomaly.Correlations) == 0 { | ||
| ch.Printer.Println("\nNo correlated queries for this anomaly.") | ||
| return nil | ||
| } | ||
|
|
||
| ch.Printer.Printf("\n%s\n", printer.Bold("Correlated queries:")) | ||
| rows := make([]*CorrelationRow, 0, len(anomaly.Correlations)) | ||
| for _, c := range anomaly.Correlations { | ||
| rows = append(rows, &CorrelationRow{ | ||
| Correlation: round2(c.R), | ||
| Fingerprint: c.Fingerprint, | ||
| Keyspace: c.Keyspace, | ||
| TabletType: c.TabletType, | ||
| Query: truncate(c.NormalizedSQL, 60), | ||
| }) | ||
| } | ||
| return ch.Printer.PrintResource(rows) | ||
| }, | ||
| } | ||
|
|
||
| return cmd | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| package insights | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/planetscale/cli/internal/mock" | ||
| ps "github.com/planetscale/cli/internal/planetscale" | ||
| "github.com/planetscale/cli/internal/printer" | ||
|
|
||
| qt "github.com/frankban/quicktest" | ||
| ) | ||
|
|
||
| func TestInsights_AnomaliesShowCmd(t *testing.T) { | ||
| c := qt.New(t) | ||
|
|
||
| svc := &mock.QueryInsightsService{ | ||
| GetAnomalyFn: func(ctx context.Context, req *ps.GetAnomalyRequest) (*ps.Anomaly, error) { | ||
| c.Assert(req.Organization, qt.Equals, "planetscale") | ||
| c.Assert(req.Database, qt.Equals, "mydb") | ||
| c.Assert(req.Branch, qt.Equals, "main") | ||
| c.Assert(req.AnomalyID, qt.Equals, "anomaly-123") | ||
| return &ps.Anomaly{ | ||
| ID: "anomaly-123", | ||
| PeriodStart: time.Date(2026, 8, 11, 18, 0, 0, 0, time.UTC), | ||
| MinutesInViolation: 12, | ||
| Correlations: []ps.Correlation{{ | ||
| ID: "corr-1", | ||
| R: 0.94, | ||
| Fingerprint: "b129e8fa", | ||
| Keyspace: "main", | ||
| NormalizedSQL: "select * from users where id = ?", | ||
| TabletType: "primary", | ||
| }}, | ||
| }, nil | ||
| }, | ||
| } | ||
|
|
||
| var buf bytes.Buffer | ||
| ch := testHelper(&buf, printer.JSON, &ps.Client{QueryInsights: svc}) | ||
|
|
||
| cmd := AnomaliesShowCmd(ch) | ||
| cmd.SetArgs([]string{"mydb", "main", "anomaly-123"}) | ||
| err := cmd.Execute() | ||
|
|
||
| c.Assert(err, qt.IsNil) | ||
| c.Assert(svc.GetAnomalyFnInvoked, qt.IsTrue) | ||
|
|
||
| var out map[string]any | ||
| c.Assert(json.Unmarshal(buf.Bytes(), &out), qt.IsNil) | ||
| c.Assert(out["id"], qt.Equals, "anomaly-123") | ||
| c.Assert(out["correlations"], qt.HasLen, 1) | ||
| } | ||
|
|
||
| func TestInsights_AnomaliesShowCmd_NotFound(t *testing.T) { | ||
| c := qt.New(t) | ||
|
|
||
| svc := &mock.QueryInsightsService{ | ||
| GetAnomalyFn: func(ctx context.Context, req *ps.GetAnomalyRequest) (*ps.Anomaly, error) { | ||
| return nil, &ps.Error{Code: ps.ErrNotFound} | ||
| }, | ||
| } | ||
|
|
||
| var buf bytes.Buffer | ||
| ch := testHelper(&buf, printer.JSON, &ps.Client{QueryInsights: svc}) | ||
|
|
||
| cmd := AnomaliesShowCmd(ch) | ||
| cmd.SetArgs([]string{"mydb", "main", "anomaly-123"}) | ||
| err := cmd.Execute() | ||
|
|
||
| c.Assert(err, qt.IsNotNil) | ||
| c.Assert(err.Error(), qt.Contains, "does not exist") | ||
| } | ||
|
|
||
| func TestInsights_AnomaliesCmd_HasShowSubcommand(t *testing.T) { | ||
| c := qt.New(t) | ||
|
|
||
| var buf bytes.Buffer | ||
| ch := testHelper(&buf, printer.JSON, &ps.Client{}) | ||
|
|
||
| cmd, _, err := AnomaliesCmd(ch).Find([]string{"show"}) | ||
| c.Assert(err, qt.IsNil) | ||
| c.Assert(cmd.Name(), qt.Equals, "show") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| package insights | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/planetscale/cli/internal/cmdutil" | ||
| ps "github.com/planetscale/cli/internal/planetscale" | ||
| "github.com/planetscale/cli/internal/printer" | ||
| ) | ||
|
|
||
| // ErrorQueryRow is a failed query execution formatted for table output. | ||
| type ErrorQueryRow struct { | ||
| StartedAt string `header:"started" json:"started_at"` | ||
| DurationMs float64 `header:"duration (ms)" json:"total_duration_millis"` | ||
| Username string `header:"user" json:"username"` | ||
| Keyspace string `header:"keyspace" json:"keyspace"` | ||
| Error string `header:"error" json:"error_message"` | ||
| Query string `header:"query" json:"normalized_sql"` | ||
| } | ||
|
|
||
| // ErrorsShowCmd lists the individual queries behind an error fingerprint. | ||
| func ErrorsShowCmd(ch *cmdutil.Helper) *cobra.Command { | ||
| var flags struct { | ||
| limit int | ||
| period string | ||
| } | ||
|
|
||
| cmd := &cobra.Command{ | ||
| Use: "show <database> <branch> <fingerprint>", | ||
| Short: "Show the queries behind an error fingerprint", | ||
| Long: `Show the individual query executions that failed with an error fingerprint. | ||
|
|
||
| Use the fingerprint column from 'pscale insights errors <database> <branch>' | ||
| (error_fingerprint in JSON), not the truncated id. | ||
|
|
||
| Useful for seeing which users, keyspaces, and statements produced the error.`, | ||
| Example: ` pscale insights errors show mydb main b129e8fa --org myorg | ||
| pscale insights errors show mydb main b129e8fa --org myorg --period 1h --limit 50`, | ||
| Args: cmdutil.RequiredArgs("database", "branch", "fingerprint"), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| ctx := cmd.Context() | ||
| database, branch, fingerprint := args[0], args[1], args[2] | ||
|
|
||
| client, err := ch.Client() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| end := ch.Printer.PrintProgress(fmt.Sprintf("Fetching queries for error fingerprint %s on %s/%s...", | ||
| printer.BoldBlue(fingerprint), printer.BoldBlue(database), printer.BoldBlue(branch))) | ||
| defer end() | ||
|
|
||
| queries, err := client.QueryInsights.ListErrorQueries(ctx, &ps.ListErrorQueriesRequest{ | ||
| Organization: ch.Config.Organization, | ||
| Database: database, | ||
| Branch: branch, | ||
| Fingerprint: fingerprint, | ||
| }, ps.WithPerPage(flags.limit), ps.WithPeriod(flags.period)) | ||
| if err != nil { | ||
| return notFoundError(ch, err, database, branch) | ||
| } | ||
| end() | ||
|
|
||
| if len(queries) == 0 && ch.Printer.Format() == printer.Human { | ||
| ch.Printer.Printf("No queries recorded for error fingerprint %s on %s/%s.\n", | ||
| printer.BoldBlue(fingerprint), printer.BoldBlue(database), printer.BoldBlue(branch)) | ||
| return nil | ||
| } | ||
|
|
||
| if ch.Printer.Format() == printer.JSON { | ||
| return ch.Printer.PrintJSON(queries) | ||
| } | ||
|
|
||
| rows := make([]*ErrorQueryRow, 0, len(queries)) | ||
| for _, q := range queries { | ||
| rows = append(rows, &ErrorQueryRow{ | ||
| StartedAt: q.StartedAt.Format("2006-01-02 15:04:05"), | ||
| DurationMs: round2(q.TotalDurationMillis), | ||
| Username: q.Username, | ||
| Keyspace: q.Keyspace, | ||
| Error: truncate(q.ErrorMessage, 60), | ||
| Query: truncate(q.NormalizedSQL, 60), | ||
| }) | ||
| } | ||
| return ch.Printer.PrintResource(rows) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().IntVar(&flags.limit, "limit", 25, "Number of queries to return") | ||
| cmd.Flags().StringVar(&flags.period, "period", "", "Time period to look back (e.g. 1h, 1d)") | ||
|
|
||
| return cmd | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.