Repository navigation
fix(errors): classify constraints and retain bounded report samples #252
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
5 commits
Select commit
Hold shift + click to select a range
93991ad
fix(errors): classify constraints and retain bounded report samples
Cianidos f7604b4
docs(changelog): link error diagnostics fix
Cianidos d62499b
fix(reports): initialize diagnostic redaction before execution
Cianidos 1bc4f28
fix(reports): harden representative error sanitization
Cianidos c247490
Merge main into error diagnostics branch
Cianidos 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
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
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,86 @@ | ||
| package bench | ||
|
|
||
| import ( | ||
| "errors" | ||
| "regexp" | ||
| "strconv" | ||
| "strings" | ||
| "unicode" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/go-sql-driver/mysql" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| ) | ||
|
|
||
| const maxErrorSampleBytes = 512 | ||
|
|
||
| var ( | ||
| errorSampleQuoted = regexp.MustCompile("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|`[^`]*`") | ||
| errorSampleSQL = regexp.MustCompile(`(?is)\b(SELECT\s+|(?:INSERT|REPLACE)\s+INTO\s+|UPDATE\s+\S+\s+SET\s+|` + | ||
| `DELETE\s+FROM\s+|CALL\s+|CREATE\s+TABLE\s+|ALTER\s+TABLE\s+|DROP\s+TABLE\s+|WITH\s+\S+\s+AS\s*\().*`) | ||
| errorSampleArguments = regexp.MustCompile(`(?is)\b(args|arguments|parameters)\s*[:=\[]?.*`) | ||
| ) | ||
|
|
||
| func backendErrorSample(err error) (code, sample string) { | ||
| if err == nil { | ||
| return "", "" | ||
| } | ||
|
|
||
| if backend, ok := errors.AsType[*pgconn.PgError](err); ok { | ||
| return backend.Code, backend.Message | ||
| } | ||
|
|
||
| if backend, ok := errors.AsType[*mysql.MySQLError](err); ok { | ||
| return strconv.FormatUint(uint64(backend.Number), 10), backend.Message | ||
| } | ||
|
|
||
| for { | ||
| if cause := errors.Unwrap(err); cause != nil { | ||
| err = cause | ||
|
|
||
| continue | ||
| } | ||
|
|
||
| if joined, ok := err.(interface{ Unwrap() []error }); ok && len(joined.Unwrap()) > 0 { | ||
| err = joined.Unwrap()[0] | ||
|
|
||
| continue | ||
| } | ||
|
|
||
| return "", err.Error() | ||
| } | ||
| } | ||
|
|
||
| func representativeError(err error, redactor *strings.Replacer) (code, sample string) { | ||
| code, sample = backendErrorSample(err) | ||
|
|
||
| if redactor != nil { | ||
| redacted := redactor.Replace(sample) | ||
| if redacted != sample && errorSampleSQL.MatchString(sample) { | ||
| redacted = "<SQL omitted>" | ||
| } | ||
|
|
||
| sample = redacted | ||
| } | ||
|
|
||
| sample = errorSampleQuoted.ReplaceAllString(sample, "<redacted>") | ||
| sample = errorSampleArguments.ReplaceAllString(sample, "<arguments omitted>") | ||
| sample = errorSampleSQL.ReplaceAllString(sample, "<SQL omitted>") | ||
| sample = strings.ToValidUTF8(sample, "?") | ||
|
|
||
| sample = strings.Map(func(r rune) rune { | ||
| if unicode.IsControl(r) || unicode.In(r, unicode.Cf) { | ||
| return ' ' | ||
| } | ||
|
|
||
| return r | ||
| }, sample) | ||
| if len(sample) > maxErrorSampleBytes { | ||
| sample = sample[:maxErrorSampleBytes] | ||
| for !utf8.ValidString(sample) { | ||
| sample = sample[:len(sample)-1] | ||
| } | ||
| } | ||
|
|
||
| return code, strings.TrimSpace(sample) | ||
| } | ||
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,154 @@ | ||
| package bench | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/go-sql-driver/mysql" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| "github.com/stretchr/testify/require" | ||
| "go.uber.org/zap" | ||
|
|
||
| "github.com/stroppy-io/stroppy/v6/pkg/driver" | ||
| ) | ||
|
|
||
| func TestRepresentativeError(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| for _, tc := range []struct { | ||
| name string | ||
| err error | ||
| code string | ||
| want string | ||
| }{ | ||
| {"postgres", fmt.Errorf("SELECT secret args [secret]: %w", &pgconn.PgError{ | ||
| Code: "23505", Message: `duplicate key value violates unique constraint "secret_index"`, | ||
| Detail: "Key (password)=(secret) already exists", Where: "SELECT secret", | ||
| }), "23505", "duplicate key value violates unique constraint <redacted>"}, | ||
| { | ||
| "mysql", &mysql.MySQLError{Number: 1062, Message: "Duplicate entry 'secret' for key 'PRIMARY'"}, | ||
| "1062", "Duplicate entry <redacted> for key <redacted>", | ||
| }, | ||
| { | ||
| "wrapped unknown", fmt.Errorf("query SELECT secret: %w", errors.New("backend unavailable")), | ||
| "", "backend unavailable", | ||
| }, | ||
| {"arguments", errors.New("backend failure; args [secret]"), "", "backend failure; <arguments omitted>"}, | ||
| {"sql", errors.New("backend failure: SELECT secret FROM table"), "", "<SQL omitted>"}, | ||
| { | ||
| "replace", errors.New("backend failure: REPLACE INTO users VALUES (12345)"), | ||
| "", "backend failure: <SQL omitted>", | ||
| }, | ||
| {"configured secret", errors.New("authentication failed secret"), "", "authentication failed <redacted>"}, | ||
| { | ||
| "serialization", &pgconn.PgError{Code: "40001", Message: "could not serialize access due to concurrent update"}, | ||
| "40001", "could not serialize access due to concurrent update", | ||
| }, | ||
| { | ||
| "foreign key", &mysql.MySQLError{ | ||
| Number: 1452, | ||
| Message: "Cannot add or update a child row: a foreign key constraint fails ('secret')", | ||
| }, | ||
| "1452", "Cannot add or update a child row: a foreign key constraint fails (<redacted>)", | ||
| }, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| code, sample := representativeError(tc.err, strings.NewReplacer("secret", "<redacted>")) | ||
| require.Equal(t, tc.code, code) | ||
| require.Equal(t, tc.want, sample) | ||
| require.NotContains(t, sample, "secret") | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestErrorSampleRedactionCannotDisableSQLOmission(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| for _, tc := range []struct { | ||
| secret string | ||
| message string | ||
| }{ | ||
| {"SET", "execution failed: UPDATE users SET password=12345"}, | ||
| {"UPDATE", "execution failed: UPDATE users SET password=12345"}, | ||
| {"'prefix' SELECT", "failure 'prefix' SELECT private_suffix FROM users"}, | ||
| {"prefix'quote", "failure prefix'quote private_suffix: REPLACE INTO users VALUES (12345)"}, | ||
| } { | ||
| t.Run(tc.secret, func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| _, sample := representativeError(errors.New(tc.message), strings.NewReplacer(tc.secret, "<redacted>")) | ||
| require.Equal(t, "<SQL omitted>", sample) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestErrorReporterRetainsBoundedFirstSample(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| reporter := newErrorReporter(zap.NewNop(), time.Hour) | ||
| t.Cleanup(reporter.stopAndWait) | ||
|
|
||
| first := "first " + strings.Repeat(string(rune(0x754c)), maxErrorSampleBytes) | ||
| reporter.record(nil, terminalErrorIteration, "workload", &pgconn.PgError{Code: "XX000", Message: first}, nil) | ||
|
|
||
| var workers sync.WaitGroup | ||
| for range 16 { | ||
| workers.Go(func() { | ||
| reporter.record(nil, terminalErrorIteration, "workload", errors.New("later error"), nil) | ||
| }) | ||
| } | ||
|
|
||
| workers.Wait() | ||
|
|
||
| summary := reporter.snapshot() | ||
| require.Len(t, summary.groups, 1) | ||
| require.Equal(t, uint64(17), summary.groups[0].count) | ||
| require.True(t, strings.HasPrefix(summary.groups[0].sample, "first ")) | ||
| require.LessOrEqual(t, len(summary.groups[0].sample), maxErrorSampleBytes) | ||
| require.True(t, utf8.ValidString(summary.groups[0].sample)) | ||
| converted := reportErrors(summary) | ||
| require.Equal(t, summary.groups[0].sample, converted.Groups[0].Sample) | ||
| require.Equal(t, "XX000", converted.Groups[0].Code) | ||
| data, err := json.Marshal(converted) | ||
| require.NoError(t, err) | ||
| require.Contains(t, string(data), `"code":"XX000"`) | ||
|
|
||
| var output bytes.Buffer | ||
| reporter.writeSummary(&output) | ||
| require.Contains(t, output.String(), "sample=\"first ") | ||
| } | ||
|
|
||
| func TestConstraintErrorsRemainTerminalAndContinue(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| reporter := newErrorReporter(zap.NewNop(), time.Hour) | ||
| t.Cleanup(reporter.stopAndWait) | ||
|
|
||
| for _, kind := range []driver.ErrorKind{driver.ErrorKindUniqueViolation, driver.ErrorKindConstraintViolation} { | ||
| policy := newTxRetryPolicy(func(error) driver.ErrorFacts { return driver.ErrorFacts{Kind: kind} }, | ||
| TxRetryPolicyOptions{MaxAttempts: 3}) | ||
| attempts := 0 | ||
| err := Retry0(context.Background(), policy, func() error { | ||
| attempts++ | ||
|
|
||
| return errors.New("constraint rejected") | ||
| }) | ||
| require.Error(t, err) | ||
| require.False(t, IsFatalError(err)) | ||
| require.Equal(t, 1, attempts) | ||
| reporter.record(nil, terminalErrorIteration, "workload", err, policy.Classify) | ||
| } | ||
|
|
||
| require.Equal(t, uint64(2), reporter.snapshot().failedIterations) | ||
| require.Len(t, reporter.snapshot().groups, 2) | ||
| } |
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
Oops, something went wrong.
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.