diff --git a/doc/http.md b/doc/http.md index b2e06ac..9860e6f 100644 --- a/doc/http.md +++ b/doc/http.md @@ -131,3 +131,74 @@ A `GET` request for `http://my.freno.service:9777/check/archive/mysql/main1` may ``` Extra info such as the threshold or actual replication lag value is irrelevant for automated requests, which should just know whether they're allowed to proceed or not. For humans this is beneficial input. + +## Requested measurements and required dependencies + +For a configured MySQL store, `MetricName`, `Value`, and `Threshold` always +describe the requested store (or its configured fallback), even when a required +dependency blocks admission. Existing replication-delay clients can continue to +read lag seconds from `Value`; a primary's running-thread count never replaces +the requested store's lag. + +`Dependencies` contains the required metrics on both accepted and rejected +checks, including when the requested metric fails. Each includes its own name, +value, threshold, status, and any evaluated nested dependencies. Freno retains +the first failure as the admission decision; later checks only complete the +diagnostic response and do not set additional low-priority throttling state. +These checks use collected measurements already held by Freno, +not additional database queries per request. A directly requested primary store +still returns primary pressure in its own `Value`; it is not a replication-lag +endpoint. + +For example, healthy replica lag with an overloaded required primary returns +HTTP 429 and a body containing: + +```json +{ + "StatusCode": 429, + "MetricName": "mysql/repositories", + "Value": 0.05, + "Threshold": 1, + "Message": "Threshold exceeded", + "BlockingMetricName": "mysql/repositories-primary", + "Dependencies": [ + { + "StatusCode": 429, + "MetricName": "mysql/repositories-primary", + "Value": 80, + "Threshold": 75, + "Message": "Threshold exceeded" + } + ] +} +``` + +Admission still follows the first failing check: the requested metric first, +then required dependencies in configured order. The top-level +`BlockingMetricName` identifies the first blocker; the existing `Message` +explains the rejection. Dependency entries contain the existing result fields +without repeating the blocking metric. Rejection counters and logs retain +the blocking metric's identity and value, rather than the top-level lag. +Recovery and shared-domain health can still cause HTTP 429 when the current +pressure is below the throttle threshold. + +A probe failure is reported through the failing metric's `StatusCode` and +`Message`. For compatibility with existing clients, `Value` remains numeric +and retains the legacy error-path value; that value is not a valid measurement. +The overall status can also describe a dependency failure while the requested +lag is valid; `BlockingMetricName` identifies which metric blocked admission. +The original missing-host fail-open/fail-closed setting remains in effect. + +An unchanged Ruby `replication_delay` client reads only `Value`; it does not +honor admission status or error messages. This change preserves +its numeric contract and removes pressure/lag unit confusion, but does not make +that client handle unavailable lag differently. Write admission must still use +the status-based check. + +The opt-in Go test `TestRubyClientLagPressureCompatibility` runs the actual Ruby +client against an in-process Freno HTTP server. Set `FRENO_RUBY_CLIENT_PATH` to an +unchanged client checkout, provide Ruby with Faraday, and run: + +```sh +go test ./pkg/throttle -run '^TestRubyClientLagPressureCompatibility$' -v +``` diff --git a/pkg/throttle/api_dependencies_test.go b/pkg/throttle/api_dependencies_test.go index f04ccf7..24b1c6d 100644 --- a/pkg/throttle/api_dependencies_test.go +++ b/pkg/throttle/api_dependencies_test.go @@ -43,7 +43,7 @@ func TestHTTPMySQLPrimaryDependencies(t *testing.T) { wantValue float64 wantThreshold float64 }{ - {"required primary blocks", "RequiredClusters", http.StatusTooManyRequests, "mysql/primary", 60, 50}, + {"required primary blocks", "RequiredClusters", http.StatusTooManyRequests, "mysql/replicas", 1, 5}, {"removed shadow field is ignored", "ShadowRequiredClusters", http.StatusOK, "mysql/replicas", 1, 5}, } { t.Run(test.name, func(t *testing.T) { @@ -127,13 +127,17 @@ func TestHTTPMySQLPrimaryRecoveryAfterProbeError(t *testing.T) { if status != step.wantStatus || result.Message != step.wantMessage { t.Fatalf("at %s: unexpected HTTP check: %+v", step.elapsed, result) } - wantMetric := "mysql/primary" - if status == http.StatusOK { - wantMetric = "mysql/replicas" - } + wantMetric := "mysql/replicas" if result.MetricName != wantMetric { t.Fatalf("metric = %q, want %q", result.MetricName, wantMetric) } + if result.Value != 1 || result.Threshold != 5 || len(result.Dependencies) != 1 { + t.Fatalf("lag fields or primary measurement lost: %+v", result) + } + value, _ := step.metric.Get() + if result.Dependencies[0].Value != value { + t.Fatalf("primary value = %g, want %g", result.Dependencies[0].Value, value) + } t.Logf("at %s: HTTP %d, metric=%s, message=%q", step.elapsed, status, result.MetricName, result.Message) }) } diff --git a/pkg/throttle/check.go b/pkg/throttle/check.go index b4c817a..3da078e 100644 --- a/pkg/throttle/check.go +++ b/pkg/throttle/check.go @@ -21,6 +21,7 @@ type CheckFlags struct { OverrideThreshold float64 LowPriority bool OKIfNotExists bool + observationOnly bool } var StandardCheckFlags = &CheckFlags{} @@ -69,7 +70,7 @@ func (check *ThrottlerCheck) checkAppMetricResult(appName string, storeType stri } checkResult = newMetricCheckResult(value, threshold, err, failOnNoHosts) if err == nil && value > threshold { - if !flags.LowPriority && !flags.ReadCheck && appName != frenoAppName { + if !flags.LowPriority && !flags.ReadCheck && !flags.observationOnly && appName != frenoAppName { // low priority requests will henceforth be denied go check.throttler.nonLowPriorityAppRequestsThrottled.SetDefault(metricName, true) } @@ -103,29 +104,43 @@ func (check *ThrottlerCheck) checkMySQLCluster( return check.throttler.getMySQLClusterMetrics(clusterName) } rootResult := check.checkAppMetricResult(appName, "mysql", clusterName, metricResultFunc, flags) - if rootResult.StatusCode != http.StatusOK { + clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName] + if clusterSettings == nil { return rootResult } - clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName] + var blocker *CheckResult + if rootResult.StatusCode != http.StatusOK { + blocker = rootResult + } for _, requiredCluster := range clusterSettings.RequiredClusters { requiredFlags := *flags requiredFlags.ReadCheck = false requiredFlags.OverrideThreshold = 0 + requiredFlags.observationOnly = flags.observationOnly || blocker != nil requiredResult := check.checkMySQLCluster(appName, requiredCluster, &requiredFlags, checkedClusters) + if requiredResult != nil { + rootResult.Dependencies = append(rootResult.Dependencies, requiredResult) + } if requiredResult == nil || requiredResult.StatusCode == http.StatusOK { continue } if requiredResult.StatusCode == http.StatusNotFound { - checkResult := NewErrorCheckResult( - http.StatusInternalServerError, - fmt.Errorf("required MySQL cluster metric %q is unavailable", requiredCluster), - ) - checkResult.MetricName = fmt.Sprintf("mysql/%s", requiredCluster) - checkResult.rejectionReason = "missing_metric" - return checkResult + err := fmt.Errorf("required MySQL cluster metric %q is unavailable", requiredCluster) + requiredResult.StatusCode = http.StatusInternalServerError + requiredResult.Error = err + requiredResult.Message = err.Error() + requiredResult.rejectionReason = "missing_metric" } - return requiredResult + if blocker == nil { + blocker = requiredResult + } + } + if blocker != nil && blocker != rootResult { + rootResult.StatusCode = blocker.StatusCode + rootResult.Error = blocker.Error + rootResult.Message = blocker.Message + rootResult.blockingResult = blocker.rejectionResult() } return rootResult } @@ -163,18 +178,19 @@ func (check *ThrottlerCheck) Check(appName string, storeType string, storeName s } if checkResult.StatusCode == http.StatusTooManyRequests && appName != frenoAppName && appName != frenoShareDmainAppName { + rejection := checkResult.rejectionResult() reason := "other" switch { - case errors.Is(checkResult.Error, base.RecoveryNotCompleteError): + case errors.Is(rejection.Error, base.RecoveryNotCompleteError): reason = "recovery" - case errors.Is(checkResult.Error, base.ThresholdExceededError) && checkResult.Value > checkResult.Threshold: + case errors.Is(rejection.Error, base.ThresholdExceededError) && rejection.Value > rejection.Threshold: reason = "threshold" } - metricName := strings.ReplaceAll(checkResult.MetricName, "/", ".") + metricName := strings.ReplaceAll(rejection.MetricName, "/", ".") metrics.GetOrRegisterCounter(fmt.Sprintf("check.rejected.%s.%s.total", metricName, reason), nil).Inc(1) } if storeType == "mysql" { - check.recordMySQLRejection(appName, storeName, checkResult) + check.recordMySQLRejection(appName, storeName, checkResult.rejectionResult()) } go func(statusCode int) { diff --git a/pkg/throttle/check_response_test.go b/pkg/throttle/check_response_test.go new file mode 100644 index 0000000..4cbcb06 --- /dev/null +++ b/pkg/throttle/check_response_test.go @@ -0,0 +1,195 @@ +package throttle + +import ( + "encoding/json" + "errors" + "net/http" + "testing" + "time" + + "github.com/github/freno/pkg/base" + "github.com/github/freno/pkg/config" + "github.com/stretchr/testify/assert" +) + +func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { + original := config.Settings().Stores.MySQL + t.Cleanup(func() { config.Settings().Stores.MySQL = original }) + config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{ + Clusters: map[string]*config.MySQLClusterConfigurationSettings{ + "replicas": {RequiredClusters: []string{"primary", "other"}}, + "primary": {FailOnNoHosts: true}, + "other": {}, + }, + } + for _, test := range []struct { + name string + replica base.MetricResult + primary base.MetricResult + shared bool + wantStatus int + wantBlocker string + wantMessage string + wantLag interface{} + wantPrimary interface{} + }{ + {"healthy", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), false, 200, "", "", 0.05, float64(23)}, + {"primary overload", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(80), false, 429, "mysql/primary", "Threshold exceeded", 0.05, float64(80)}, + {"primary recovery", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(35, base.RecoveryNotCompleteError), false, 429, "mysql/primary", "Recovery period not complete", 0.05, float64(35)}, + {"primary shared health", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), true, 429, "mysql/primary", "Threshold exceeded", 0.05, float64(23)}, + {"primary probe error", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(999, errors.New("probe failed")), false, 500, "mysql/primary", "probe failed", 0.05, float64(999)}, + {"primary no hosts", base.NewSimpleMetricResult(0.05), base.NoHostsMetricResult, false, 500, "mysql/primary", "No hosts found", 0.05, float64(0)}, + {"primary missing", base.NewSimpleMetricResult(0.05), base.NoSuchMetric, false, 500, "mysql/primary", `required MySQL cluster metric "primary" is unavailable`, 0.05, float64(0)}, + {"lag overload includes pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "Threshold exceeded", float64(6), float64(23)}, + {"lag recovery includes pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "Recovery period not complete", float64(2), float64(23)}, + {"both overloaded keeps first blocker", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(80), false, 429, "mysql/replicas", "Threshold exceeded", float64(6), float64(80)}, + {"lag error includes pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "lag failed", float64(999), float64(23)}, + {"both unavailable", base.NoMetricResultYet, base.NoMetricResultYet, false, 500, "mysql/replicas", "Metric not collected yet", float64(0), float64(0)}, + {"legacy lag no-hosts fail-open is unchanged", base.NoHostsMetricResult, base.NewSimpleMetricResult(23), false, 200, "", "No hosts found", float64(0), float64(23)}, + } { + t.Run(test.name, func(t *testing.T) { + throttler := NewThrottler() + setTestMySQLClusterMetric(throttler, "replicas", 0.05, 5) + setTestMySQLClusterMetric(throttler, "primary", 23, 50) + setTestMySQLClusterMetric(throttler, "other", 10, 20) + throttler.aggregatedMetrics.SetDefault("mysql/replicas", test.replica) + throttler.aggregatedMetrics.SetDefault("mysql/primary", test.primary) + if test.shared { + throttler.shareDomainMetricHealth.SetDefault("mysql/primary", &base.MetricHealth{SecondsSinceLastHealthy: 1}) + } + checked := make(map[string]bool) + result := NewThrottlerCheck(throttler).checkMySQLCluster("test-app", "replicas", StandardCheckFlags, checked) + assert.Equal(t, test.wantStatus, result.StatusCode) + assert.Equal(t, "mysql/replicas", result.MetricName) + data, err := json.Marshal(result) + if !assert.NoError(t, err) { + return + } + var body map[string]interface{} + if !assert.NoError(t, json.Unmarshal(data, &body)) { + return + } + assert.Equal(t, test.wantLag, body["Value"]) + assert.Equal(t, float64(5), body["Threshold"]) + assert.Equal(t, test.wantMessage, body["Message"]) + assert.NotContains(t, body, "MeasurementAvailable") + assert.NotContains(t, body, "MeasurementError") + assert.NotContains(t, body, "RejectionReason") + if test.wantBlocker == "" { + assert.NotContains(t, body, "BlockingMetricName") + } else { + assert.Equal(t, test.wantBlocker, body["BlockingMetricName"]) + } + if !assert.Len(t, result.Dependencies, 2) { + return + } + assert.Equal(t, map[string]bool{"replicas": true, "primary": true, "other": true}, checked) + assert.Equal(t, "mysql/primary", result.Dependencies[0].MetricName) + assert.Equal(t, 10.0, result.Dependencies[1].Value) + dependencies := body["Dependencies"].([]interface{}) + primary := dependencies[0].(map[string]interface{}) + assert.Equal(t, test.wantPrimary, primary["Value"]) + assert.NotContains(t, primary, "MeasurementAvailable") + assert.NotContains(t, primary, "MeasurementError") + assert.NotContains(t, primary, "RejectionReason") + assert.NotContains(t, primary, "BlockingMetricName") + assert.Equal(t, result.Dependencies[0].Message, primary["Message"]) + }) + } +} + +func TestDiagnosticDependenciesDoNotSetLowPriorityThrottlingState(t *testing.T) { + original := config.Settings().Stores.MySQL + t.Cleanup(func() { config.Settings().Stores.MySQL = original }) + config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{ + Clusters: map[string]*config.MySQLClusterConfigurationSettings{ + "replicas": {RequiredClusters: []string{"primary", "other"}}, + "primary": {}, + "other": {}, + }, + } + for _, test := range []struct { + name string + lag float64 + blocker string + diagnostics []string + }{ + {"lag blocks first", 6, "mysql/replicas", []string{"mysql/primary", "mysql/other"}}, + {"primary blocks first", 0.05, "mysql/primary", []string{"mysql/other"}}, + } { + t.Run(test.name, func(t *testing.T) { + throttler := NewThrottler() + setTestMySQLClusterMetric(throttler, "replicas", test.lag, 5) + setTestMySQLClusterMetric(throttler, "primary", 80, 50) + setTestMySQLClusterMetric(throttler, "other", 30, 20) + result := NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags) + assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) + assert.Equal(t, test.blocker, result.rejectionResult().MetricName) + assert.Len(t, result.Dependencies, 2) + assert.Eventually(t, func() bool { + _, exists := throttler.nonLowPriorityAppRequestsThrottled.Get(test.blocker) + return exists + }, time.Second, time.Millisecond) + assert.Never(t, func() bool { + for _, metric := range test.diagnostics { + if _, exists := throttler.nonLowPriorityAppRequestsThrottled.Get(metric); exists { + return true + } + } + return false + }, 50*time.Millisecond, time.Millisecond) + }) + } +} + +func TestNestedDependenciesKeepLagAndBlockerIdentity(t *testing.T) { + original := config.Settings().Stores.MySQL + t.Cleanup(func() { config.Settings().Stores.MySQL = original }) + config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{ + Clusters: map[string]*config.MySQLClusterConfigurationSettings{ + "replicas": {RequiredClusters: []string{"intermediate"}}, + "intermediate": {RequiredClusters: []string{"primary"}}, + "primary": {}, + }, + } + throttler := NewThrottler() + setTestMySQLClusterMetric(throttler, "replicas", 0.05, 1) + setTestMySQLClusterMetric(throttler, "intermediate", 0.1, 1) + setTestMySQLClusterMetric(throttler, "primary", 80, 75) + result := NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags) + assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) + assert.Equal(t, 0.05, result.Value) + assert.Equal(t, "mysql/replicas", result.MetricName) + if !assert.Len(t, result.Dependencies, 1) { + return + } + assert.Equal(t, 0.1, result.Dependencies[0].Value) + assert.Equal(t, "mysql/primary", result.rejectionResult().MetricName) + assert.Equal(t, 80.0, result.rejectionResult().Value) + data, err := json.Marshal(result) + if !assert.NoError(t, err) { + return + } + var body map[string]interface{} + if !assert.NoError(t, json.Unmarshal(data, &body)) { + return + } + assert.Equal(t, "mysql/primary", body["BlockingMetricName"]) + intermediate := body["Dependencies"].([]interface{})[0].(map[string]interface{}) + primary := intermediate["Dependencies"].([]interface{})[0].(map[string]interface{}) + for _, dependency := range []map[string]interface{}{intermediate, primary} { + assert.NotContains(t, dependency, "BlockingMetricName") + assert.NotContains(t, dependency, "RejectionReason") + assert.NotContains(t, dependency, "MeasurementError") + } + + throttler.aggregatedMetrics.Delete("mysql/intermediate") + result = NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags) + assert.Equal(t, http.StatusInternalServerError, result.StatusCode) + assert.Equal(t, 0.05, result.Value) + assert.Equal(t, "mysql/intermediate", result.rejectionResult().MetricName) + if !assert.Len(t, result.Dependencies, 1) || !assert.Len(t, result.Dependencies[0].Dependencies, 1) { + return + } + assert.Equal(t, 80.0, result.Dependencies[0].Dependencies[0].Value) +} diff --git a/pkg/throttle/check_result.go b/pkg/throttle/check_result.go index fd6a9da..2304536 100644 --- a/pkg/throttle/check_result.go +++ b/pkg/throttle/check_result.go @@ -1,6 +1,7 @@ package throttle import ( + "encoding/json" "errors" "net/http" @@ -31,13 +32,65 @@ func newMetricCheckResult(value, threshold float64, err error, failOnNoHosts boo // CheckResult is the result for an app inquiring on a metric. It also exports as JSON via the API type CheckResult struct { - StatusCode int `json:"StatusCode"` - Value float64 `json:"Value"` - Threshold float64 `json:"Threshold"` - MetricName string `json:"MetricName,omitempty"` - Error error `json:"-"` - Message string `json:"Message"` + StatusCode int `json:"StatusCode"` + Value float64 `json:"Value"` + Threshold float64 `json:"Threshold"` + MetricName string `json:"MetricName,omitempty"` + Error error `json:"-"` + Message string `json:"Message"` + Dependencies []*CheckResult `json:"Dependencies,omitempty"` rejectionReason string + blockingResult *CheckResult +} + +type checkResultResponse struct { + StatusCode int `json:"StatusCode"` + Value float64 `json:"Value"` + Threshold float64 `json:"Threshold"` + MetricName string `json:"MetricName,omitempty"` + Message string `json:"Message"` + Dependencies []*checkResultResponse `json:"Dependencies,omitempty"` +} + +func (result *CheckResult) response() *checkResultResponse { + if result == nil { + return nil + } + response := &checkResultResponse{ + StatusCode: result.StatusCode, + Value: result.Value, + Threshold: result.Threshold, + MetricName: result.MetricName, + Message: result.Message, + } + for _, dependency := range result.Dependencies { + response.Dependencies = append(response.Dependencies, dependency.response()) + } + return response +} + +func (result *CheckResult) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + *checkResultResponse + BlockingMetricName string `json:"BlockingMetricName,omitempty"` + }{ + checkResultResponse: result.response(), + BlockingMetricName: result.blockingMetricName(), + }) +} + +func (result *CheckResult) rejectionResult() *CheckResult { + if result.blockingResult != nil { + return result.blockingResult + } + return result +} + +func (result *CheckResult) blockingMetricName() string { + if result.StatusCode == http.StatusOK { + return "" + } + return result.rejectionResult().MetricName } func NewCheckResult(statusCode int, value float64, threshold float64, err error) *CheckResult { diff --git a/pkg/throttle/ruby_client_compatibility_test.go b/pkg/throttle/ruby_client_compatibility_test.go new file mode 100644 index 0000000..fa64101 --- /dev/null +++ b/pkg/throttle/ruby_client_compatibility_test.go @@ -0,0 +1,121 @@ +package throttle_test + +import ( + "errors" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/github/freno/pkg/base" + "github.com/github/freno/pkg/config" + frenohttp "github.com/github/freno/pkg/http" + "github.com/github/freno/pkg/throttle" +) + +func TestRubyClientLagPressureCompatibility(t *testing.T) { + clientPath := os.Getenv("FRENO_RUBY_CLIENT_PATH") + if clientPath == "" { + t.Skip("set FRENO_RUBY_CLIENT_PATH to an unchanged freno-client checkout and provide Ruby with Faraday") + } + ruby, err := exec.LookPath("ruby") + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(clientPath, "lib", "freno", "client.rb")); err != nil { + t.Fatal(err) + } + + defer config.Reset() + recoveryThreshold := 40.0 + config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{ + Clusters: map[string]*config.MySQLClusterConfigurationSettings{ + "replicas": {ThrottleThreshold: 1, RequiredClusters: []string{"primary"}}, + "primary": { + ThrottleThreshold: 75, + RecoveryThreshold: &recoveryThreshold, + RecoveryDurationMillis: 1000, + FailOnNoHosts: true, + }, + }, + } + throttler := throttle.NewThrottler() + throttle.SetTestMySQLClusterMetric(throttler, "replicas", 0.05, 1) + throttle.SetTestMySQLClusterMetric(throttler, "primary", 80, 75) + router := frenohttp.ConfigureRoutes(frenohttp.NewAPIImpl(throttle.NewThrottlerCheck(throttler), nil)) + server := httptest.NewServer(router) + defer server.Close() + + const script = ` +require "faraday" +require "freno/client" + +url, expected_status, expected_lag, expected_pressure = ARGV +connection = Faraday.new(url: url) do |builder| + builder.options.open_timeout = 2 + builder.options.timeout = 2 +end +client = Freno::Client.new(connection) do |config| + config.default_app = "test-app" + config.default_store_name = "replicas" +end +delay = client.replication_delay +raise "expected lag value #{expected_lag}, got #{delay.inspect}" unless delay == expected_lag.to_f + +# The application's default_replication_wait! calculation uses the maximum +# cluster delay, converts seconds to milliseconds and adds 100ms. +wait_millis = [delay].max * 1000 + 100 +raise "incorrect application wait: #{wait_millis}" unless wait_millis == expected_lag.to_f * 1000 + 100 + +result = client.check +raise "incorrect admission status: #{result.code}" unless result.code == expected_status.to_i +raise "incorrect admission boolean" unless client.check? == (expected_status == "200") + +body = JSON.parse(connection.get("/check/test-app/mysql/replicas").body) +raise "requested metric replaced" unless body["MetricName"] == "mysql/replicas" +raise "missing pressure" unless body.fetch("Dependencies").first["MetricName"] == "mysql/primary" +raise "incorrect pressure" unless body.fetch("Dependencies").first["Value"] == expected_pressure.to_f +puts "lag=#{delay}s wait=#{wait_millis}ms admission=#{result.code}" +` + start := time.Date(2026, time.November, 23, 0, 0, 0, 0, time.UTC) + healthyLag := base.NewSimpleMetricResult(0.05) + for _, step := range []struct { + name string + elapsed time.Duration + metric base.MetricResult + status string + shared int64 + lag base.MetricResult + }{ + {"primary overloaded", 0, base.NewSimpleMetricResult(80), "429", 0, healthyLag}, + {"recovering", time.Second, base.NewSimpleMetricResult(35), "429", 0, healthyLag}, + {"healthy", 2 * time.Second, base.NewSimpleMetricResult(35), "200", 0, healthyLag}, + {"primary probe fails", 3 * time.Second, base.NewErrorMetricResult(0, errors.New("probe failed")), "500", 0, healthyLag}, + {"fresh recovery", 4 * time.Second, base.NewSimpleMetricResult(35), "429", 0, healthyLag}, + {"recovered after probe failure", 5 * time.Second, base.NewSimpleMetricResult(35), "200", 0, healthyLag}, + {"shared domain unhealthy", 6 * time.Second, base.NewSimpleMetricResult(35), "429", 1, healthyLag}, + {"shared domain healthy again", 7 * time.Second, base.NewSimpleMetricResult(35), "200", 0, healthyLag}, + {"lag overloaded includes pressure", 8 * time.Second, base.NewSimpleMetricResult(35), "429", 0, base.NewSimpleMetricResult(6)}, + {"both overloaded includes pressure", 9 * time.Second, base.NewSimpleMetricResult(80), "429", 0, base.NewSimpleMetricResult(6)}, + {"lag probe fails includes pressure", 10 * time.Second, base.NewSimpleMetricResult(35), "500", 0, base.NewErrorMetricResult(0, errors.New("lag failed"))}, + {"lag and primary recovered", 11 * time.Second, base.NewSimpleMetricResult(35), "200", 0, healthyLag}, + } { + t.Run(step.name, func(t *testing.T) { + throttle.StabilizeTestMySQLClusterMetric(throttler, "replicas", step.lag, start.Add(step.elapsed)) + throttle.StabilizeTestMySQLClusterMetric(throttler, "primary", step.metric, start.Add(step.elapsed)) + throttle.SetTestMySQLSharedHealth(throttler, "primary", step.shared) + lag, _ := step.lag.Get() + pressure, _ := step.metric.Get() + command := exec.Command(ruby, "-I"+filepath.Join(clientPath, "lib"), "-e", script, server.URL, step.status, + strconv.FormatFloat(lag, 'f', -1, 64), strconv.FormatFloat(pressure, 'f', -1, 64)) + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("unchanged Ruby client failed: %v\n%s", err, output) + } + t.Log(string(output)) + }) + } +} diff --git a/pkg/throttle/safety_telemetry_test.go b/pkg/throttle/safety_telemetry_test.go index adf220b..2b4940f 100644 --- a/pkg/throttle/safety_telemetry_test.go +++ b/pkg/throttle/safety_telemetry_test.go @@ -135,6 +135,9 @@ func TestSafetyRejectionTelemetry(t *testing.T) { assert.Equal(t, 1, strings.Count(logs(), "event=freno_admission_rejected")) assert.Contains(t, logs(), fmt.Sprintf("reason=%q", test.wantReason)) assert.Contains(t, logs(), fmt.Sprintf("dependency=%q", dependency)) + if test.name == "primary threshold" { + assert.Contains(t, logs(), "value=60 threshold=50") + } assert.NotContains(t, logs(), "private connection details") assert.NotContains(t, logs(), "unbounded-caller-input") // The next interval logs again without suppressing any request counters. diff --git a/pkg/throttle/throttler_test.go b/pkg/throttle/throttler_test.go index 990231f..8f28949 100644 --- a/pkg/throttle/throttler_test.go +++ b/pkg/throttle/throttler_test.go @@ -181,6 +181,10 @@ func StabilizeTestMySQLClusterMetric(throttler *Throttler, clusterName string, m throttler.aggregatedMetrics.SetDefault("mysql/"+clusterName, throttler.stabilizeMySQLMetric(clusterName, metric, now)) } +func SetTestMySQLSharedHealth(throttler *Throttler, clusterName string, seconds int64) { + throttler.shareDomainMetricHealth.SetDefault("mysql/"+clusterName, &base.MetricHealth{SecondsSinceLastHealthy: seconds}) +} + func newTestMySQLFallbackCheck(fallbackCluster string) (*ThrottlerCheck, *Throttler) { config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{ FallbackCluster: fallbackCluster, @@ -345,9 +349,11 @@ func TestCheckMySQLRequiredClusters(t *testing.T) { setTestMySQLClusterMetric(throttler, "primary", 60.0, 50.0) result := check.Check("transitions", "mysql", "replicas", "", &CheckFlags{}) assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) - assert.Equal(t, 60.0, result.Value) - assert.Equal(t, 50.0, result.Threshold) - assert.Equal(t, "mysql/primary", result.MetricName) + assert.Equal(t, 1.0, result.Value) + assert.Equal(t, 5.0, result.Threshold) + assert.Equal(t, "mysql/replicas", result.MetricName) + assert.Equal(t, "mysql/primary", result.rejectionResult().MetricName) + assert.Equal(t, 60.0, result.Dependencies[0].Value) }) t.Run("ProxySQL cluster blocks admission", func(t *testing.T) { @@ -355,8 +361,10 @@ func TestCheckMySQLRequiredClusters(t *testing.T) { setTestMySQLClusterMetric(throttler, "proxysql", 90.0, 80.0) result := check.Check("transitions", "mysql", "replicas", "", &CheckFlags{}) assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) - assert.Equal(t, 90.0, result.Value) - assert.Equal(t, 80.0, result.Threshold) + assert.Equal(t, 1.0, result.Value) + assert.Equal(t, 5.0, result.Threshold) + assert.Equal(t, "mysql/proxysql", result.rejectionResult().MetricName) + assert.Equal(t, 90.0, result.Dependencies[1].Value) }) t.Run("read threshold override only applies to requested cluster", func(t *testing.T) { @@ -367,7 +375,8 @@ func TestCheckMySQLRequiredClusters(t *testing.T) { OverrideThreshold: 100.0, }) assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) - assert.Equal(t, 50.0, result.Threshold) + assert.Equal(t, 100.0, result.Threshold) + assert.Equal(t, 50.0, result.Dependencies[0].Threshold) }) t.Run("read threshold override bypasses only the requested cluster recovery latch", func(t *testing.T) { @@ -393,7 +402,8 @@ func TestCheckMySQLRequiredClusters(t *testing.T) { OverrideThreshold: 100.0, }) assert.Equal(t, http.StatusTooManyRequests, result.StatusCode) - assert.Equal(t, "mysql/primary", result.MetricName) + assert.Equal(t, "mysql/replicas", result.MetricName) + assert.Equal(t, "mysql/primary", result.rejectionResult().MetricName) }) t.Run("missing required metric fails closed", func(t *testing.T) { @@ -402,7 +412,8 @@ func TestCheckMySQLRequiredClusters(t *testing.T) { result := check.Check("transitions", "mysql", "replicas", "", &CheckFlags{OKIfNotExists: true}) assert.Equal(t, http.StatusInternalServerError, result.StatusCode) assert.EqualError(t, result.Error, `required MySQL cluster metric "primary" is unavailable`) - assert.Equal(t, "mysql/primary", result.MetricName) + assert.Equal(t, "mysql/replicas", result.MetricName) + assert.Equal(t, "mysql/primary", result.rejectionResult().MetricName) }) }