From 55fd612e4333634774c4e45af2096cd6715033f9 Mon Sep 17 00:00:00 2001 From: Pradeep Kintali Date: Mon, 23 Nov 2026 08:35:46 -0800 Subject: [PATCH 1/4] Preserve requested lag values when required metrics reject checks Keep requested measurements separate from dependency admission failures and retain first-failure short-circuiting. Add response diagnostics and regression coverage, including unchanged Ruby client HTTP compatibility. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: fbc83df2-d1af-406f-b97b-51cf0aaa570d --- doc/http.md | 74 +++++++++ pkg/throttle/api_dependencies_test.go | 14 +- pkg/throttle/check.go | 38 +++-- pkg/throttle/check_response_test.go | 152 ++++++++++++++++++ pkg/throttle/check_result.go | 74 ++++++++- .../ruby_client_compatibility_test.go | 109 +++++++++++++ pkg/throttle/safety_telemetry_test.go | 3 + pkg/throttle/throttler_test.go | 27 +++- 8 files changed, 457 insertions(+), 34 deletions(-) create mode 100644 pkg/throttle/check_response_test.go create mode 100644 pkg/throttle/ruby_client_compatibility_test.go diff --git a/doc/http.md b/doc/http.md index b2e06ac..10aeabe 100644 --- a/doc/http.md +++ b/doc/http.md @@ -131,3 +131,77 @@ 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. + +If the requested metric fails, Freno returns its value, status, and reason +without evaluating dependencies. Otherwise, `Dependencies` contains the required +metrics evaluated in configured order, stopping at the first failure. Each +includes its own name, value, threshold, status, and any evaluated nested +dependencies. 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", + "MeasurementAvailable": true, + "BlockingMetricName": "mysql/repositories-primary", + "RejectionReason": "threshold", + "Dependencies": [ + { + "StatusCode": 429, + "MetricName": "mysql/repositories-primary", + "Value": 80, + "Threshold": 75, + "Message": "Threshold exceeded", + "MeasurementAvailable": true, + "BlockingMetricName": "mysql/repositories-primary", + "RejectionReason": "threshold" + } + ] +} +``` + +Admission still follows the first failing check: the requested metric first, +then required dependencies in configured order. `BlockingMetricName` and +`RejectionReason` describe that decision. 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. + +When a measurement is unavailable, its result includes +`MeasurementAvailable: false` and `MeasurementError`. For compatibility with +existing clients, `Value` remains numeric and retains the legacy error-path +value; it must not be interpreted as a valid reading when availability is +false. The original missing-host fail-open/fail-closed setting remains in +effect. Measurement availability describes the local numeric reading, not +permission to write or the health of its dependencies. + +An unchanged Ruby `replication_delay` client reads only `Value`; it does not +honor admission status or the new availability metadata. 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..87ccb25 100644 --- a/pkg/throttle/check.go +++ b/pkg/throttle/check.go @@ -106,26 +106,35 @@ func (check *ThrottlerCheck) checkMySQLCluster( if rootResult.StatusCode != http.StatusOK { return rootResult } - clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName] + if clusterSettings == nil { + return rootResult + } + for _, requiredCluster := range clusterSettings.RequiredClusters { requiredFlags := *flags requiredFlags.ReadCheck = false requiredFlags.OverrideThreshold = 0 requiredResult := check.checkMySQLCluster(appName, requiredCluster, &requiredFlags, checkedClusters) - if requiredResult == nil || requiredResult.StatusCode == http.StatusOK { + if requiredResult == nil { 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.measurementError = err.Error() + requiredResult.rejectionReason = "missing_metric" + } + rootResult.Dependencies = append(rootResult.Dependencies, requiredResult) + if requiredResult.StatusCode != http.StatusOK { + rootResult.StatusCode = requiredResult.StatusCode + rootResult.Error = requiredResult.Error + rootResult.Message = requiredResult.Message + rootResult.blockingResult = requiredResult.rejectionResult() + return rootResult } - return requiredResult } return rootResult } @@ -163,18 +172,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..2bde439 --- /dev/null +++ b/pkg/throttle/check_response_test.go @@ -0,0 +1,152 @@ +package throttle + +import ( + "encoding/json" + "errors" + "net/http" + "testing" + + "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 + wantReason 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", 0.05, float64(80)}, + {"primary recovery", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(35, base.RecoveryNotCompleteError), false, 429, "mysql/primary", "recovery", 0.05, float64(35)}, + {"primary shared health", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), true, 429, "mysql/primary", "shared_domain", 0.05, float64(23)}, + {"primary probe error", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(999, errors.New("probe failed")), false, 500, "mysql/primary", "metric_error", 0.05, float64(999)}, + {"primary no hosts", base.NewSimpleMetricResult(0.05), base.NoHostsMetricResult, false, 500, "mysql/primary", "no_hosts", 0.05, float64(0)}, + {"primary missing", base.NewSimpleMetricResult(0.05), base.NoSuchMetric, false, 500, "mysql/primary", "missing_metric", 0.05, float64(0)}, + {"lag overload skips pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "threshold", float64(6), float64(23)}, + {"lag recovery skips pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "recovery", float64(2), float64(23)}, + {"both overloaded keeps first blocker", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(80), false, 429, "mysql/replicas", "threshold", float64(6), float64(80)}, + {"lag error skips pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "metric_error", float64(999), float64(23)}, + {"both unavailable", base.NoMetricResultYet, base.NoMetricResultYet, false, 500, "mysql/replicas", "metric_error", float64(0), float64(0)}, + {"legacy lag no-hosts fail-open is unchanged", base.NoHostsMetricResult, base.NewSimpleMetricResult(23), false, 200, "", "", 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"]) + _, lagErr := test.replica.Get() + lagAvailable := lagErr == nil || errors.Is(lagErr, base.RecoveryNotCompleteError) + assert.Equal(t, lagAvailable, body["MeasurementAvailable"]) + if !lagAvailable { + assert.Equal(t, lagErr.Error(), body["MeasurementError"]) + } else { + assert.NotContains(t, body, "MeasurementError") + } + if test.wantBlocker == "" { + assert.NotContains(t, body, "BlockingMetricName") + } else { + assert.Equal(t, test.wantBlocker, body["BlockingMetricName"]) + assert.Equal(t, test.wantReason, body["RejectionReason"]) + } + if test.wantBlocker == "mysql/replicas" { + assert.Empty(t, result.Dependencies) + assert.NotContains(t, body, "Dependencies") + assert.Equal(t, map[string]bool{"replicas": true}, checked) + return + } + wantDependencies := 1 + if test.wantStatus == http.StatusOK { + wantDependencies = 2 + } + if !assert.Len(t, result.Dependencies, wantDependencies) { + return + } + assert.Len(t, checked, wantDependencies+1) + assert.Equal(t, "mysql/primary", result.Dependencies[0].MetricName) + if wantDependencies == 2 { + 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"]) + _, primaryErr := test.primary.Get() + available := primaryErr == nil || errors.Is(primaryErr, base.RecoveryNotCompleteError) + assert.Equal(t, available, primary["MeasurementAvailable"]) + if !available { + assert.NotEmpty(t, primary["MeasurementError"]) + } + }) + } +} + +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) + + 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) { + return + } + assert.Empty(t, result.Dependencies[0].Dependencies) +} diff --git a/pkg/throttle/check_result.go b/pkg/throttle/check_result.go index fd6a9da..2d4432b 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,67 @@ 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"` - rejectionReason string + 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 + valueUnavailable bool + measurementError string +} + +func (result *CheckResult) MarshalJSON() ([]byte, error) { + type response CheckResult + return json.Marshal(struct { + *response + MeasurementAvailable bool `json:"MeasurementAvailable"` + MeasurementError string `json:"MeasurementError,omitempty"` + BlockingMetricName string `json:"BlockingMetricName,omitempty"` + RejectionReason string `json:"RejectionReason,omitempty"` + }{ + response: (*response)(result), + MeasurementAvailable: !result.valueUnavailable, + MeasurementError: result.measurementError, + BlockingMetricName: result.blockingMetricName(), + RejectionReason: result.rejectionResult().reason(), + }) +} + +func (result *CheckResult) reason() string { + if result.StatusCode == http.StatusOK { + return "" + } + if result.rejectionReason != "" { + return result.rejectionReason + } + switch { + case errors.Is(result.Error, base.RecoveryNotCompleteError): + return "recovery" + case errors.Is(result.Error, base.ThresholdExceededError) && result.Value > result.Threshold: + return "threshold" + case result.StatusCode == http.StatusInternalServerError: + return safetyMetricErrorReason(result.Error) + default: + return "" + } +} + +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 { @@ -46,9 +101,14 @@ func NewCheckResult(statusCode int, value float64, threshold float64, err error) Value: value, Threshold: threshold, Error: err, + valueUnavailable: err != nil && !errors.Is(err, base.RecoveryNotCompleteError) && + !errors.Is(err, base.ThresholdExceededError), } if err != nil { result.Message = err.Error() + if result.valueUnavailable { + result.measurementError = err.Error() + } } return result } diff --git a/pkg/throttle/ruby_client_compatibility_test.go b/pkg/throttle/ruby_client_compatibility_test.go new file mode 100644 index 0000000..c05b9b0 --- /dev/null +++ b/pkg/throttle/ruby_client_compatibility_test.go @@ -0,0 +1,109 @@ +package throttle_test + +import ( + "errors" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "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 = 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 seconds, got #{delay.inspect}" unless delay == 0.05 + +# 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 == 150 + +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" +puts "lag=#{delay}s wait=#{wait_millis}ms admission=#{result.code}" +` + start := time.Date(2026, time.November, 23, 0, 0, 0, 0, time.UTC) + for _, step := range []struct { + name string + elapsed time.Duration + metric base.MetricResult + status string + shared int64 + }{ + {"primary overloaded", 0, base.NewSimpleMetricResult(80), "429", 0}, + {"recovering", time.Second, base.NewSimpleMetricResult(35), "429", 0}, + {"healthy", 2 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, + {"primary probe fails", 3 * time.Second, base.NewErrorMetricResult(0, errors.New("probe failed")), "500", 0}, + {"fresh recovery", 4 * time.Second, base.NewSimpleMetricResult(35), "429", 0}, + {"recovered after probe failure", 5 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, + {"shared domain unhealthy", 6 * time.Second, base.NewSimpleMetricResult(35), "429", 1}, + {"shared domain healthy again", 7 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, + } { + t.Run(step.name, func(t *testing.T) { + throttle.StabilizeTestMySQLClusterMetric(throttler, "primary", step.metric, start.Add(step.elapsed)) + throttle.SetTestMySQLSharedHealth(throttler, "primary", step.shared) + command := exec.Command(ruby, "-I"+filepath.Join(clientPath, "lib"), "-e", script, server.URL, step.status) + 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) }) } From 97535af25b17c16342029fe2a17f980eed914792 Mon Sep 17 00:00:00 2001 From: Pradeep Kintali Date: Mon, 23 Nov 2026 08:45:58 -0800 Subject: [PATCH 2/4] Include primary pressure diagnostics when lag checks fail Report required measurements consistently while retaining the first admission failure and the original combined dependency guard. Prevent diagnostic-only checks from setting low-priority throttling state and cover lag failure and recovery with the unchanged Ruby client. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: fbc83df2-d1af-406f-b97b-51cf0aaa570d --- doc/http.md | 11 +-- pkg/throttle/check.go | 31 +++++--- pkg/throttle/check_response_test.go | 73 ++++++++++++++----- .../ruby_client_compatibility_test.go | 36 ++++++--- 4 files changed, 102 insertions(+), 49 deletions(-) diff --git a/doc/http.md b/doc/http.md index 10aeabe..8b3b6d6 100644 --- a/doc/http.md +++ b/doc/http.md @@ -140,11 +140,12 @@ 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. -If the requested metric fails, Freno returns its value, status, and reason -without evaluating dependencies. Otherwise, `Dependencies` contains the required -metrics evaluated in configured order, stopping at the first failure. Each -includes its own name, value, threshold, status, and any evaluated nested -dependencies. These checks use collected measurements already held by Freno, +`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. diff --git a/pkg/throttle/check.go b/pkg/throttle/check.go index 87ccb25..6a6da8f 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,20 +104,25 @@ func (check *ThrottlerCheck) checkMySQLCluster( return check.throttler.getMySQLClusterMetrics(clusterName) } rootResult := check.checkAppMetricResult(appName, "mysql", clusterName, metricResultFunc, flags) - if rootResult.StatusCode != http.StatusOK { - return rootResult - } clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName] if clusterSettings == nil { return rootResult } + 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 { + if requiredResult != nil { + rootResult.Dependencies = append(rootResult.Dependencies, requiredResult) + } + if requiredResult == nil || requiredResult.StatusCode == http.StatusOK { continue } if requiredResult.StatusCode == http.StatusNotFound { @@ -127,15 +133,16 @@ func (check *ThrottlerCheck) checkMySQLCluster( requiredResult.measurementError = err.Error() requiredResult.rejectionReason = "missing_metric" } - rootResult.Dependencies = append(rootResult.Dependencies, requiredResult) - if requiredResult.StatusCode != http.StatusOK { - rootResult.StatusCode = requiredResult.StatusCode - rootResult.Error = requiredResult.Error - rootResult.Message = requiredResult.Message - rootResult.blockingResult = requiredResult.rejectionResult() - return rootResult + 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 } diff --git a/pkg/throttle/check_response_test.go b/pkg/throttle/check_response_test.go index 2bde439..4c4e34d 100644 --- a/pkg/throttle/check_response_test.go +++ b/pkg/throttle/check_response_test.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "testing" + "time" "github.com/github/freno/pkg/base" "github.com/github/freno/pkg/config" @@ -39,10 +40,10 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { {"primary probe error", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(999, errors.New("probe failed")), false, 500, "mysql/primary", "metric_error", 0.05, float64(999)}, {"primary no hosts", base.NewSimpleMetricResult(0.05), base.NoHostsMetricResult, false, 500, "mysql/primary", "no_hosts", 0.05, float64(0)}, {"primary missing", base.NewSimpleMetricResult(0.05), base.NoSuchMetric, false, 500, "mysql/primary", "missing_metric", 0.05, float64(0)}, - {"lag overload skips pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "threshold", float64(6), float64(23)}, - {"lag recovery skips pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "recovery", float64(2), float64(23)}, + {"lag overload includes pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "threshold", float64(6), float64(23)}, + {"lag recovery includes pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "recovery", float64(2), float64(23)}, {"both overloaded keeps first blocker", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(80), false, 429, "mysql/replicas", "threshold", float64(6), float64(80)}, - {"lag error skips pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "metric_error", float64(999), float64(23)}, + {"lag error includes pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "metric_error", float64(999), float64(23)}, {"both unavailable", base.NoMetricResultYet, base.NoMetricResultYet, false, 500, "mysql/replicas", "metric_error", float64(0), float64(0)}, {"legacy lag no-hosts fail-open is unchanged", base.NoHostsMetricResult, base.NewSimpleMetricResult(23), false, 200, "", "", float64(0), float64(23)}, } { @@ -84,24 +85,12 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { assert.Equal(t, test.wantBlocker, body["BlockingMetricName"]) assert.Equal(t, test.wantReason, body["RejectionReason"]) } - if test.wantBlocker == "mysql/replicas" { - assert.Empty(t, result.Dependencies) - assert.NotContains(t, body, "Dependencies") - assert.Equal(t, map[string]bool{"replicas": true}, checked) + if !assert.Len(t, result.Dependencies, 2) { return } - wantDependencies := 1 - if test.wantStatus == http.StatusOK { - wantDependencies = 2 - } - if !assert.Len(t, result.Dependencies, wantDependencies) { - return - } - assert.Len(t, checked, wantDependencies+1) + assert.Equal(t, map[string]bool{"replicas": true, "primary": true, "other": true}, checked) assert.Equal(t, "mysql/primary", result.Dependencies[0].MetricName) - if wantDependencies == 2 { - assert.Equal(t, 10.0, result.Dependencies[1].Value) - } + 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"]) @@ -115,6 +104,50 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { } } +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 }) @@ -145,8 +178,8 @@ func TestNestedDependenciesKeepLagAndBlockerIdentity(t *testing.T) { 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) { + if !assert.Len(t, result.Dependencies, 1) || !assert.Len(t, result.Dependencies[0].Dependencies, 1) { return } - assert.Empty(t, result.Dependencies[0].Dependencies) + assert.Equal(t, 80.0, result.Dependencies[0].Dependencies[0].Value) } diff --git a/pkg/throttle/ruby_client_compatibility_test.go b/pkg/throttle/ruby_client_compatibility_test.go index c05b9b0..fa64101 100644 --- a/pkg/throttle/ruby_client_compatibility_test.go +++ b/pkg/throttle/ruby_client_compatibility_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "testing" "time" @@ -52,7 +53,7 @@ func TestRubyClientLagPressureCompatibility(t *testing.T) { require "faraday" require "freno/client" -url, expected_status = ARGV +url, expected_status, expected_lag, expected_pressure = ARGV connection = Faraday.new(url: url) do |builder| builder.options.open_timeout = 2 builder.options.timeout = 2 @@ -62,12 +63,12 @@ client = Freno::Client.new(connection) do |config| config.default_store_name = "replicas" end delay = client.replication_delay -raise "expected lag seconds, got #{delay.inspect}" unless delay == 0.05 +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 == 150 +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 @@ -76,29 +77,40 @@ raise "incorrect admission boolean" unless client.check? == (expected_status == 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}, - {"recovering", time.Second, base.NewSimpleMetricResult(35), "429", 0}, - {"healthy", 2 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, - {"primary probe fails", 3 * time.Second, base.NewErrorMetricResult(0, errors.New("probe failed")), "500", 0}, - {"fresh recovery", 4 * time.Second, base.NewSimpleMetricResult(35), "429", 0}, - {"recovered after probe failure", 5 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, - {"shared domain unhealthy", 6 * time.Second, base.NewSimpleMetricResult(35), "429", 1}, - {"shared domain healthy again", 7 * time.Second, base.NewSimpleMetricResult(35), "200", 0}, + {"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) - command := exec.Command(ruby, "-I"+filepath.Join(clientPath, "lib"), "-e", script, server.URL, step.status) + 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) From 851b30aee084ea9691c4441d9330cb94c697fc2f Mon Sep 17 00:00:00 2001 From: Pradeep Kintali Date: Mon, 23 Nov 2026 08:53:52 -0800 Subject: [PATCH 3/4] Remove measurement availability boolean from check responses Keep measurement errors, numeric values and admission diagnostics while omitting the unneeded availability flag. Update response tests and HTTP documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: fbc83df2-d1af-406f-b97b-51cf0aaa570d --- doc/http.md | 18 ++++++++---------- pkg/throttle/check_response_test.go | 6 ++++-- pkg/throttle/check_result.go | 21 ++++++++------------- 3 files changed, 20 insertions(+), 25 deletions(-) diff --git a/doc/http.md b/doc/http.md index 8b3b6d6..0cd2827 100644 --- a/doc/http.md +++ b/doc/http.md @@ -160,7 +160,6 @@ HTTP 429 and a body containing: "Value": 0.05, "Threshold": 1, "Message": "Threshold exceeded", - "MeasurementAvailable": true, "BlockingMetricName": "mysql/repositories-primary", "RejectionReason": "threshold", "Dependencies": [ @@ -170,7 +169,6 @@ HTTP 429 and a body containing: "Value": 80, "Threshold": 75, "Message": "Threshold exceeded", - "MeasurementAvailable": true, "BlockingMetricName": "mysql/repositories-primary", "RejectionReason": "threshold" } @@ -185,16 +183,16 @@ 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. -When a measurement is unavailable, its result includes -`MeasurementAvailable: false` and `MeasurementError`. For compatibility with -existing clients, `Value` remains numeric and retains the legacy error-path -value; it must not be interpreted as a valid reading when availability is -false. The original missing-host fail-open/fail-closed setting remains in -effect. Measurement availability describes the local numeric reading, not -permission to write or the health of its dependencies. +When a measurement is unavailable, its result includes `MeasurementError`. +For compatibility with existing clients, `Value` remains numeric and retains +the legacy error-path +value; it must not be interpreted as a valid reading when `MeasurementError` +is present. The original missing-host fail-open/fail-closed setting remains in +effect. `MeasurementError` describes a problem with the local numeric reading, +not the health of its dependencies. An unchanged Ruby `replication_delay` client reads only `Value`; it does not -honor admission status or the new availability metadata. This change preserves +honor admission status or the new measurement-error field. 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. diff --git a/pkg/throttle/check_response_test.go b/pkg/throttle/check_response_test.go index 4c4e34d..9e8512e 100644 --- a/pkg/throttle/check_response_test.go +++ b/pkg/throttle/check_response_test.go @@ -73,7 +73,7 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { assert.Equal(t, float64(5), body["Threshold"]) _, lagErr := test.replica.Get() lagAvailable := lagErr == nil || errors.Is(lagErr, base.RecoveryNotCompleteError) - assert.Equal(t, lagAvailable, body["MeasurementAvailable"]) + assert.NotContains(t, body, "MeasurementAvailable") if !lagAvailable { assert.Equal(t, lagErr.Error(), body["MeasurementError"]) } else { @@ -96,9 +96,11 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { assert.Equal(t, test.wantPrimary, primary["Value"]) _, primaryErr := test.primary.Get() available := primaryErr == nil || errors.Is(primaryErr, base.RecoveryNotCompleteError) - assert.Equal(t, available, primary["MeasurementAvailable"]) + assert.NotContains(t, primary, "MeasurementAvailable") if !available { assert.NotEmpty(t, primary["MeasurementError"]) + } else { + assert.NotContains(t, primary, "MeasurementError") } }) } diff --git a/pkg/throttle/check_result.go b/pkg/throttle/check_result.go index 2d4432b..b2c2e9b 100644 --- a/pkg/throttle/check_result.go +++ b/pkg/throttle/check_result.go @@ -41,7 +41,6 @@ type CheckResult struct { Dependencies []*CheckResult `json:"Dependencies,omitempty"` rejectionReason string blockingResult *CheckResult - valueUnavailable bool measurementError string } @@ -49,16 +48,14 @@ func (result *CheckResult) MarshalJSON() ([]byte, error) { type response CheckResult return json.Marshal(struct { *response - MeasurementAvailable bool `json:"MeasurementAvailable"` - MeasurementError string `json:"MeasurementError,omitempty"` - BlockingMetricName string `json:"BlockingMetricName,omitempty"` - RejectionReason string `json:"RejectionReason,omitempty"` + MeasurementError string `json:"MeasurementError,omitempty"` + BlockingMetricName string `json:"BlockingMetricName,omitempty"` + RejectionReason string `json:"RejectionReason,omitempty"` }{ - response: (*response)(result), - MeasurementAvailable: !result.valueUnavailable, - MeasurementError: result.measurementError, - BlockingMetricName: result.blockingMetricName(), - RejectionReason: result.rejectionResult().reason(), + response: (*response)(result), + MeasurementError: result.measurementError, + BlockingMetricName: result.blockingMetricName(), + RejectionReason: result.rejectionResult().reason(), }) } @@ -101,12 +98,10 @@ func NewCheckResult(statusCode int, value float64, threshold float64, err error) Value: value, Threshold: threshold, Error: err, - valueUnavailable: err != nil && !errors.Is(err, base.RecoveryNotCompleteError) && - !errors.Is(err, base.ThresholdExceededError), } if err != nil { result.Message = err.Error() - if result.valueUnavailable { + if !errors.Is(err, base.RecoveryNotCompleteError) && !errors.Is(err, base.ThresholdExceededError) { result.measurementError = err.Error() } } From 7b127a319350d11e2efa0a6ec109d67206869fbe Mon Sep 17 00:00:00 2001 From: Pradeep Kintali Date: Mon, 23 Nov 2026 09:00:06 -0800 Subject: [PATCH 4/4] Keep dependency response diagnostics minimal Expose only Dependencies and top-level BlockingMetricName as new JSON properties. Preserve existing result fields and messages in nested measurements, remove redundant reason/error properties, and keep internal rejection telemetry unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: fbc83df2-d1af-406f-b97b-51cf0aaa570d --- doc/http.md | 26 +++++----- pkg/throttle/check.go | 1 - pkg/throttle/check_response_test.go | 64 ++++++++++++----------- pkg/throttle/check_result.go | 78 ++++++++++++++--------------- 4 files changed, 86 insertions(+), 83 deletions(-) diff --git a/doc/http.md b/doc/http.md index 0cd2827..9860e6f 100644 --- a/doc/http.md +++ b/doc/http.md @@ -161,38 +161,36 @@ HTTP 429 and a body containing: "Threshold": 1, "Message": "Threshold exceeded", "BlockingMetricName": "mysql/repositories-primary", - "RejectionReason": "threshold", "Dependencies": [ { "StatusCode": 429, "MetricName": "mysql/repositories-primary", "Value": 80, "Threshold": 75, - "Message": "Threshold exceeded", - "BlockingMetricName": "mysql/repositories-primary", - "RejectionReason": "threshold" + "Message": "Threshold exceeded" } ] } ``` Admission still follows the first failing check: the requested metric first, -then required dependencies in configured order. `BlockingMetricName` and -`RejectionReason` describe that decision. Rejection counters and logs retain +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. -When a measurement is unavailable, its result includes `MeasurementError`. -For compatibility with existing clients, `Value` remains numeric and retains -the legacy error-path -value; it must not be interpreted as a valid reading when `MeasurementError` -is present. The original missing-host fail-open/fail-closed setting remains in -effect. `MeasurementError` describes a problem with the local numeric reading, -not the health of its dependencies. +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 the new measurement-error field. This change preserves +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. diff --git a/pkg/throttle/check.go b/pkg/throttle/check.go index 6a6da8f..3da078e 100644 --- a/pkg/throttle/check.go +++ b/pkg/throttle/check.go @@ -130,7 +130,6 @@ func (check *ThrottlerCheck) checkMySQLCluster( requiredResult.StatusCode = http.StatusInternalServerError requiredResult.Error = err requiredResult.Message = err.Error() - requiredResult.measurementError = err.Error() requiredResult.rejectionReason = "missing_metric" } if blocker == nil { diff --git a/pkg/throttle/check_response_test.go b/pkg/throttle/check_response_test.go index 9e8512e..4cbcb06 100644 --- a/pkg/throttle/check_response_test.go +++ b/pkg/throttle/check_response_test.go @@ -29,23 +29,23 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { shared bool wantStatus int wantBlocker string - wantReason 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", 0.05, float64(80)}, - {"primary recovery", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(35, base.RecoveryNotCompleteError), false, 429, "mysql/primary", "recovery", 0.05, float64(35)}, - {"primary shared health", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), true, 429, "mysql/primary", "shared_domain", 0.05, float64(23)}, - {"primary probe error", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(999, errors.New("probe failed")), false, 500, "mysql/primary", "metric_error", 0.05, float64(999)}, - {"primary no hosts", base.NewSimpleMetricResult(0.05), base.NoHostsMetricResult, false, 500, "mysql/primary", "no_hosts", 0.05, float64(0)}, - {"primary missing", base.NewSimpleMetricResult(0.05), base.NoSuchMetric, false, 500, "mysql/primary", "missing_metric", 0.05, float64(0)}, - {"lag overload includes pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "threshold", float64(6), float64(23)}, - {"lag recovery includes pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "recovery", float64(2), float64(23)}, - {"both overloaded keeps first blocker", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(80), false, 429, "mysql/replicas", "threshold", float64(6), float64(80)}, - {"lag error includes pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "metric_error", float64(999), float64(23)}, - {"both unavailable", base.NoMetricResultYet, base.NoMetricResultYet, false, 500, "mysql/replicas", "metric_error", float64(0), float64(0)}, - {"legacy lag no-hosts fail-open is unchanged", base.NoHostsMetricResult, base.NewSimpleMetricResult(23), false, 200, "", "", float64(0), 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() @@ -71,19 +71,14 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { } assert.Equal(t, test.wantLag, body["Value"]) assert.Equal(t, float64(5), body["Threshold"]) - _, lagErr := test.replica.Get() - lagAvailable := lagErr == nil || errors.Is(lagErr, base.RecoveryNotCompleteError) + assert.Equal(t, test.wantMessage, body["Message"]) assert.NotContains(t, body, "MeasurementAvailable") - if !lagAvailable { - assert.Equal(t, lagErr.Error(), body["MeasurementError"]) - } else { - assert.NotContains(t, body, "MeasurementError") - } + 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"]) - assert.Equal(t, test.wantReason, body["RejectionReason"]) } if !assert.Len(t, result.Dependencies, 2) { return @@ -94,14 +89,11 @@ func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) { dependencies := body["Dependencies"].([]interface{}) primary := dependencies[0].(map[string]interface{}) assert.Equal(t, test.wantPrimary, primary["Value"]) - _, primaryErr := test.primary.Get() - available := primaryErr == nil || errors.Is(primaryErr, base.RecoveryNotCompleteError) assert.NotContains(t, primary, "MeasurementAvailable") - if !available { - assert.NotEmpty(t, primary["MeasurementError"]) - } else { - assert.NotContains(t, primary, "MeasurementError") - } + assert.NotContains(t, primary, "MeasurementError") + assert.NotContains(t, primary, "RejectionReason") + assert.NotContains(t, primary, "BlockingMetricName") + assert.Equal(t, result.Dependencies[0].Message, primary["Message"]) }) } } @@ -174,6 +166,22 @@ func TestNestedDependenciesKeepLagAndBlockerIdentity(t *testing.T) { 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) diff --git a/pkg/throttle/check_result.go b/pkg/throttle/check_result.go index b2c2e9b..2304536 100644 --- a/pkg/throttle/check_result.go +++ b/pkg/throttle/check_result.go @@ -32,50 +32,51 @@ 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"` - Dependencies []*CheckResult `json:"Dependencies,omitempty"` - rejectionReason string - blockingResult *CheckResult - measurementError string + 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 } -func (result *CheckResult) MarshalJSON() ([]byte, error) { - type response CheckResult - return json.Marshal(struct { - *response - MeasurementError string `json:"MeasurementError,omitempty"` - BlockingMetricName string `json:"BlockingMetricName,omitempty"` - RejectionReason string `json:"RejectionReason,omitempty"` - }{ - response: (*response)(result), - MeasurementError: result.measurementError, - BlockingMetricName: result.blockingMetricName(), - RejectionReason: result.rejectionResult().reason(), - }) +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) reason() string { - if result.StatusCode == http.StatusOK { - return "" +func (result *CheckResult) response() *checkResultResponse { + if result == nil { + return nil } - if result.rejectionReason != "" { - return result.rejectionReason + response := &checkResultResponse{ + StatusCode: result.StatusCode, + Value: result.Value, + Threshold: result.Threshold, + MetricName: result.MetricName, + Message: result.Message, } - switch { - case errors.Is(result.Error, base.RecoveryNotCompleteError): - return "recovery" - case errors.Is(result.Error, base.ThresholdExceededError) && result.Value > result.Threshold: - return "threshold" - case result.StatusCode == http.StatusInternalServerError: - return safetyMetricErrorReason(result.Error) - default: - return "" + 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 { @@ -101,9 +102,6 @@ func NewCheckResult(statusCode int, value float64, threshold float64, err error) } if err != nil { result.Message = err.Error() - if !errors.Is(err, base.RecoveryNotCompleteError) && !errors.Is(err, base.ThresholdExceededError) { - result.measurementError = err.Error() - } } return result }