diff --git a/ddtrace/tracer/remote_config.go b/ddtrace/tracer/remote_config.go index 42376695a0b..21602066f19 100644 --- a/ddtrace/tracer/remote_config.go +++ b/ddtrace/tracer/remote_config.go @@ -371,7 +371,7 @@ func (t *tracer) startDynamicInstrumentationRCSubscriptions() error { t.dynInstSubscriptions.mu.Lock() defer t.dynInstSubscriptions.mu.Unlock() - if t.dynInstSubscriptions.ldSubscriptionToken != 0 || t.dynInstSubscriptions.symDBSubscriptionToken != 0 { + if !t.dynInstSubscriptions.ldSubscriptionToken.IsZero() || !t.dynInstSubscriptions.symDBSubscriptionToken.IsZero() { return errors.New("programming error: dynamic instrumentation RC subscriptions already started") } @@ -400,19 +400,19 @@ func (t *tracer) startDynamicInstrumentationRCSubscriptions() error { func (t *tracer) stopDynamicInstrumentationRCSubscriptions() error { t.dynInstSubscriptions.mu.Lock() defer t.dynInstSubscriptions.mu.Unlock() - if t.dynInstSubscriptions.ldSubscriptionToken != 0 { + if !t.dynInstSubscriptions.ldSubscriptionToken.IsZero() { err := remoteconfig.Unsubscribe(t.dynInstSubscriptions.ldSubscriptionToken) if err != nil { return err } - t.dynInstSubscriptions.ldSubscriptionToken = 0 + t.dynInstSubscriptions.ldSubscriptionToken = remoteconfig.SubscriptionToken{} } - if t.dynInstSubscriptions.symDBSubscriptionToken != 0 { + if !t.dynInstSubscriptions.symDBSubscriptionToken.IsZero() { err := remoteconfig.Unsubscribe(t.dynInstSubscriptions.symDBSubscriptionToken) if err != nil { return err } - t.dynInstSubscriptions.symDBSubscriptionToken = 0 + t.dynInstSubscriptions.symDBSubscriptionToken = remoteconfig.SubscriptionToken{} } return nil } diff --git a/ddtrace/tracer/remote_config_errortracking_test.go b/ddtrace/tracer/remote_config_errortracking_test.go index 57df6961220..6b827bdd964 100644 --- a/ddtrace/tracer/remote_config_errortracking_test.go +++ b/ddtrace/tracer/remote_config_errortracking_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" + rc "github.com/DataDog/datadog-agent/pkg/remoteconfig/state" + "github.com/DataDog/dd-trace-go/v2/internal/log" internalffe "github.com/DataDog/dd-trace-go/v2/internal/openfeature" "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" @@ -58,6 +60,10 @@ func TestRemoteConfigDisabledOpenFeatureSubscriptionLogsLocallyWithoutReporting( } func TestRemoteConfigSubscriptionErrorsReportedToTelemetry(t *testing.T) { + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + staleToken, err := remoteconfig.Subscribe("STALE_TEST_PRODUCT", func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { return nil }) + require.NoError(t, err) + remoteconfig.Stop() t.Setenv("DD_REMOTE_CONFIGURATION_ENABLED", "false") t.Cleanup(remoteconfig.Reset) @@ -79,7 +85,7 @@ func TestRemoteConfigSubscriptionErrorsReportedToTelemetry(t *testing.T) { // enable path left both real tokens at zero because the subscriptions // never started. tr.dynInstSubscriptions.mu.Lock() - tr.dynInstSubscriptions.ldSubscriptionToken = 1 + tr.dynInstSubscriptions.ldSubscriptionToken = staleToken tr.dynInstSubscriptions.mu.Unlock() disabled := false tr.handleDynamicInstrumentationEnabledRC(&disabled) diff --git a/internal/openfeature/evaluator_capabilities.go b/internal/openfeature/evaluator_capabilities.go new file mode 100644 index 00000000000..d7208af9df9 --- /dev/null +++ b/internal/openfeature/evaluator_capabilities.go @@ -0,0 +1,34 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2025 Datadog, Inc. + +package openfeature + +import ( + "slices" + + "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" +) + +// DependentFlagVariantKeyV1 identifies prerequisite variant-key evaluation support. +const DependentFlagVariantKeyV1 = "dependent-flag-variant-key-v1" + +// DependentFlagsVariantKeyQueryParameter requests prerequisite variant keys in UFC responses. +const DependentFlagsVariantKeyQueryParameter = "cap_dependent-flags-variant-key" + +// DependentFlagsVariantKeyQueryVersion is the supported query parameter version. +const DependentFlagsVariantKeyQueryVersion = "v1" + +// EvaluatorCapabilities reports features supported by the Go evaluator and exposure hooks. +// The tracer needs this report before the provider exists, so it lives in the +// lightweight internal package. +func EvaluatorCapabilities() []string { return []string{DependentFlagVariantKeyV1} } + +func remoteConfigCapabilities(evaluatorCapabilities []string) []remoteconfig.Capability { + capabilities := []remoteconfig.Capability{remoteconfig.FFEFlagEvaluation} + if slices.Contains(evaluatorCapabilities, DependentFlagVariantKeyV1) { + capabilities = append(capabilities, remoteconfig.FFEFlagDependentFlagVariantKeyV1) + } + return capabilities +} diff --git a/internal/openfeature/evaluator_capabilities_test.go b/internal/openfeature/evaluator_capabilities_test.go new file mode 100644 index 00000000000..123ea5924bf --- /dev/null +++ b/internal/openfeature/evaluator_capabilities_test.go @@ -0,0 +1,34 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2025 Datadog, Inc. + +package openfeature + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" +) + +func TestEvaluatorCapabilities(t *testing.T) { + assert.Equal(t, []string{DependentFlagVariantKeyV1}, EvaluatorCapabilities()) + assert.Equal(t, remoteconfig.Capability(50), remoteconfig.FFEFlagDependentFlagVariantKeyV1) + for _, test := range []struct { + name string + capabilities []string + expected []remoteconfig.Capability + }{ + {"absent", nil, []remoteconfig.Capability{46}}, + {"empty", []string{}, []remoteconfig.Capability{46}}, + {"unknown", []string{"unknown-v1"}, []remoteconfig.Capability{46}}, + {"supported", []string{DependentFlagVariantKeyV1}, []remoteconfig.Capability{46, 50}}, + {"mixed", []string{"unknown-v1", DependentFlagVariantKeyV1}, []remoteconfig.Capability{46, 50}}, + } { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expected, remoteConfigCapabilities(test.capabilities)) + }) + } +} diff --git a/internal/openfeature/rc_subscription.go b/internal/openfeature/rc_subscription.go index 131fc2e7628..69a6018876e 100644 --- a/internal/openfeature/rc_subscription.go +++ b/internal/openfeature/rc_subscription.go @@ -12,6 +12,7 @@ package openfeature import ( "bytes" + "errors" "fmt" "sync" @@ -30,13 +31,22 @@ const ( // apply statuses. This matches the signature of DatadogProvider.rcCallback. type Callback func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus +// ProviderToken identifies one provider's ownership of either a tracer-owned +// callback attachment or a provider-owned slow-path subscription. +type ProviderToken uint64 + // rcState bridges the tracer's early RC subscription (during tracer.Start) // with the late-created DatadogProvider (during NewDatadogProvider). var rcState struct { sync.Mutex - subscribed bool - callback Callback - buffered remoteconfig.ProductUpdate // latest snapshot; RC sends full state each time + subscribed bool + callback Callback + callbackToken ProviderToken + buffered remoteconfig.ProductUpdate // pending changes received while no provider is attached + delivered remoteconfig.ProductUpdate // last acknowledged state, retained for replacement providers + providerSubscription remoteconfig.SubscriptionToken + providerToken ProviderToken + nextProviderToken ProviderToken } // SubscribeRC subscribes to the FFE_FLAGS RC product using a forwarding @@ -55,6 +65,9 @@ func SubscribeRC() error { log.Debug("openfeature: RC subscription for %s was lost (tracer restart?), re-subscribing", FFEProductName) rcState.subscribed = false rcState.callback = nil + rcState.callbackToken = 0 + rcState.buffered = nil + rcState.delivered = nil } if has, _ := remoteconfig.HasProduct(FFEProductName); has { @@ -62,7 +75,7 @@ func SubscribeRC() error { return nil } - if _, err := remoteconfig.Subscribe(FFEProductName, forwardingCallback, remoteconfig.FFEFlagEvaluation); err != nil { + if _, err := remoteconfig.Subscribe(FFEProductName, forwardingCallback, remoteConfigCapabilities(EvaluatorCapabilities())...); err != nil { return err } @@ -72,22 +85,25 @@ func SubscribeRC() error { } // forwardingCallback is the RC callback registered by SubscribeRC. If a -// provider callback is attached, it forwards directly. Otherwise, it buffers -// the latest update for replay when the provider attaches. +// provider callback is attached, it forwards directly and records only the +// paths the provider acknowledged. Otherwise, it buffers changes for replay +// when the provider attaches. func forwardingCallback(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { rcState.Lock() defer rcState.Unlock() if rcState.callback != nil { - return rcState.callback(update) + statuses := rcState.callback(update) + applyAcknowledgedUpdateLocked(update, statuses) + return statuses } - // Buffer the latest update for replay. - cpy := make(remoteconfig.ProductUpdate, len(update)) - for k, v := range update { - cpy[k] = bytes.Clone(v) + if rcState.buffered == nil { + rcState.buffered = make(remoteconfig.ProductUpdate, len(update)) + } + for path, data := range update { + rcState.buffered[path] = bytes.Clone(data) } - rcState.buffered = cpy // Acknowledge all paths so RC doesn't consider them errored. statuses := make(map[string]rc.ApplyStatus, len(update)) @@ -97,60 +113,143 @@ func forwardingCallback(update remoteconfig.ProductUpdate) map[string]rc.ApplySt return statuses } +// applyAcknowledgedUpdateLocked advances the replayable state only for paths +// which the provider accepted. The caller holds rcState. +func applyAcknowledgedUpdateLocked(update remoteconfig.ProductUpdate, statuses map[string]rc.ApplyStatus) { + for path, data := range update { + if statuses[path].State != rc.ApplyStateAcknowledged { + continue + } + if data == nil { + delete(rcState.delivered, path) + continue + } + if rcState.delivered == nil { + rcState.delivered = make(remoteconfig.ProductUpdate) + } + rcState.delivered[path] = bytes.Clone(data) + } +} + // AttachCallback wires the given callback to the global RC subscription. // If SubscribeRC() was called (i.e. the tracer subscribed), it replays any -// buffered config and returns true. Otherwise returns false, meaning the -// caller should fall back to its own RC subscription. -func AttachCallback(cb Callback) bool { +// buffered config and returns an ownership token with true. Otherwise it +// returns a zero token with false, meaning the caller should fall back to its +// own RC subscription. +func AttachCallback(cb Callback) (ProviderToken, bool) { rcState.Lock() defer rcState.Unlock() if !rcState.subscribed { - return false + return 0, false } if rcState.callback != nil { log.Warn("openfeature: callback already attached, multiple providers are not supported") //errtrack:ignore caller initialized multiple providers - return false + return 0, false } + token := nextProviderTokenLocked() rcState.callback = cb + rcState.callbackToken = token + if len(rcState.delivered) > 0 { + cb(rcState.delivered) + containLoggerPanic(func() { + log.Debug("openfeature: replayed last acknowledged RC config to replacement provider") + }) + } if rcState.buffered != nil { - log.Debug("openfeature: replaying buffered RC config to provider") - // Apply statuses are intentionally discarded: the RC client already received - // ApplyStateAcknowledged from forwardingCallback when this update was buffered. - // This call only initializes the provider's in-memory state. - cb(rcState.buffered) + // The RC client already received ApplyStateAcknowledged when this update was + // buffered. The replay statuses only determine which paths are safe to retain. + statuses := cb(rcState.buffered) + applyAcknowledgedUpdateLocked(rcState.buffered, statuses) rcState.buffered = nil + containLoggerPanic(func() { + log.Debug("openfeature: replayed buffered RC config to provider") + }) } - return true + return token, true +} + +// containLoggerPanic keeps an application logger from interrupting ownership +// transitions after the callback state has already changed. +func containLoggerPanic(logf func()) { + defer func() { _ = recover() }() + logf() } -// SubscribeProvider attempts to subscribe a provider callback to RC. +// SubscribeProvider attempts to subscribe a provider callback to RC. A +// provider-owned slow-path subscription returns its ownership token; the +// tracer-owned fast path returns a zero token until AttachCallback succeeds. // It holds the subscription mutex to prevent races with SubscribeRC. -func SubscribeProvider(cb remoteconfig.ProductCallback) (tracerOwnsSubscription bool, err error) { +func SubscribeProvider(cb remoteconfig.ProductCallback) (tracerOwnsSubscription bool, token ProviderToken, err error) { rcState.Lock() defer rcState.Unlock() if rcState.subscribed { - return true, nil + return true, 0, nil } // Slow path: tracer didn't subscribe, so we need to start RC and subscribe ourselves. if err := remoteconfig.Start(remoteconfig.DefaultClientConfig()); err != nil { - return false, fmt.Errorf("failed to start Remote Config: %w", err) + return false, 0, fmt.Errorf("failed to start Remote Config: %w", err) } if has, _ := remoteconfig.HasProduct(FFEProductName); has { - return false, fmt.Errorf("RC product %s already subscribed", FFEProductName) + return false, 0, fmt.Errorf("RC product %s already subscribed", FFEProductName) } - if _, err := remoteconfig.Subscribe(FFEProductName, cb, remoteconfig.FFEFlagEvaluation); err != nil { - return false, err + capabilities := remoteConfigCapabilities(EvaluatorCapabilities()) + subscription, err := remoteconfig.Subscribe(FFEProductName, cb, capabilities...) + if err != nil { + return false, 0, err } + token = nextProviderTokenLocked() + rcState.providerSubscription = subscription + rcState.providerToken = token log.Debug("openfeature: provider subscribed to RC product %s", FFEProductName) - return false, nil + return false, token, nil +} + +// nextProviderTokenLocked returns a non-zero token. The caller holds rcState. +func nextProviderTokenLocked() ProviderToken { + rcState.nextProviderToken++ + if rcState.nextProviderToken == 0 { + rcState.nextProviderToken++ + } + return rcState.nextProviderToken +} + +// UnsubscribeProvider releases only the provider ownership represented by +// token. Fast-path ownership detaches the matching callback while retaining +// the tracer subscription; slow-path ownership removes its subscription and +// exact capability set. Stale tokens are harmless. +func UnsubscribeProvider(token ProviderToken) error { + rcState.Lock() + defer rcState.Unlock() + + if token == 0 { + return nil + } + if rcState.callbackToken == token { + rcState.callback = nil + rcState.callbackToken = 0 + return nil + } + if rcState.providerToken != token { + return nil + } + subscription := rcState.providerSubscription + rcState.providerSubscription = remoteconfig.SubscriptionToken{} + rcState.providerToken = 0 + if err := remoteconfig.Unsubscribe(subscription); err != nil { + if errors.Is(err, remoteconfig.ErrClientNotStarted) { + return nil + } + return err + } + return nil } diff --git a/internal/openfeature/rc_subscription_test.go b/internal/openfeature/rc_subscription_test.go index c8e5d4500cf..b77e6498916 100644 --- a/internal/openfeature/rc_subscription_test.go +++ b/internal/openfeature/rc_subscription_test.go @@ -6,15 +6,30 @@ package openfeature import ( + "os" + "os/exec" "testing" rc "github.com/DataDog/datadog-agent/pkg/remoteconfig/state" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/DataDog/dd-trace-go/v2/internal/log" "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" ) +type panickingRCLogger struct{} + +func (panickingRCLogger) Log(string) { panic("logger failure") } + +func acknowledgedStatuses(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + statuses := make(map[string]rc.ApplyStatus, len(update)) + for path := range update { + statuses[path] = rc.ApplyStatus{State: rc.ApplyStateAcknowledged} + } + return statuses +} + func TestForwardingCallbackBuffersWhenNoCallback(t *testing.T) { ResetForTest() defer ResetForTest() @@ -27,10 +42,11 @@ func TestForwardingCallbackBuffersWhenNoCallback(t *testing.T) { rcState.Lock() require.NotNil(t, rcState.buffered) assert.Contains(t, rcState.buffered, "path/1") + assert.Empty(t, rcState.delivered) rcState.Unlock() } -func TestForwardingCallbackBuffersOnlyLatest(t *testing.T) { +func TestForwardingCallbackAccumulatesPendingChanges(t *testing.T) { ResetForTest() defer ResetForTest() @@ -39,7 +55,7 @@ func TestForwardingCallbackBuffersOnlyLatest(t *testing.T) { rcState.Lock() require.NotNil(t, rcState.buffered) - assert.NotContains(t, rcState.buffered, "path/old") + assert.Contains(t, rcState.buffered, "path/old") assert.Contains(t, rcState.buffered, "path/new") rcState.Unlock() } @@ -51,11 +67,7 @@ func TestForwardingCallbackForwardsWhenCallbackAttached(t *testing.T) { var received remoteconfig.ProductUpdate cb := func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { received = update - statuses := make(map[string]rc.ApplyStatus, len(update)) - for path := range update { - statuses[path] = rc.ApplyStatus{State: rc.ApplyStateAcknowledged} - } - return statuses + return acknowledgedStatuses(update) } rcState.Lock() @@ -71,6 +83,36 @@ func TestForwardingCallbackForwardsWhenCallbackAttached(t *testing.T) { rcState.Lock() assert.Nil(t, rcState.buffered) + assert.Equal(t, []byte(`live`), rcState.delivered["path/live"]) + rcState.Unlock() +} + +func TestForwardingCallbackRetainsOnlyAcknowledgedState(t *testing.T) { + ResetForTest() + defer ResetForTest() + + rcState.Lock() + rcState.subscribed = true + rcState.delivered = remoteconfig.ProductUpdate{ + "path/good": []byte(`good`), + "path/removed": []byte(`remove-me`), + } + rcState.callback = func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + return map[string]rc.ApplyStatus{ + "path/good": {State: rc.ApplyStateError}, + "path/removed": {State: rc.ApplyStateAcknowledged}, + } + } + rcState.Unlock() + + forwardingCallback(remoteconfig.ProductUpdate{ + "path/good": []byte(`malformed`), + "path/removed": nil, + }) + + rcState.Lock() + assert.Equal(t, []byte(`good`), rcState.delivered["path/good"]) + assert.NotContains(t, rcState.delivered, "path/removed") rcState.Unlock() } @@ -78,7 +120,7 @@ func TestAttachCallbackNotSubscribed(t *testing.T) { ResetForTest() defer ResetForTest() - got := AttachCallback(func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { return nil }) + _, got := AttachCallback(func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { return nil }) assert.False(t, got) } @@ -98,7 +140,7 @@ func TestAttachCallbackReplaysBuffer(t *testing.T) { return nil } - got := AttachCallback(cb) + _, got := AttachCallback(cb) assert.True(t, got) assert.Contains(t, received, "path/buf") @@ -116,7 +158,7 @@ func TestAttachCallbackNoBuffer(t *testing.T) { rcState.Unlock() called := false - got := AttachCallback(func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + _, got := AttachCallback(func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { called = true return nil }) @@ -171,3 +213,102 @@ func TestSubscribeRCAfterTracerRestart(t *testing.T) { require.NoError(t, err) assert.True(t, has, "FFE_FLAGS should be subscribed on the new RC client after restart") } + +func TestFastPathDetachBuffersForReplacement(t *testing.T) { + ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + ResetForTest() + remoteconfig.Reset() + }) + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + require.NoError(t, SubscribeRC()) + + var firstUpdates, replacementUpdates []string + firstToken, attached := AttachCallback(func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + for path := range update { + firstUpdates = append(firstUpdates, path) + } + return nil + }) + require.True(t, attached) + forwardingCallback(remoteconfig.ProductUpdate{"live/first": []byte("first")}) + require.Equal(t, []string{"live/first"}, firstUpdates) + + require.NoError(t, UnsubscribeProvider(firstToken)) + forwardingCallback(remoteconfig.ProductUpdate{"buffered/replacement": []byte("buffered")}) + require.Equal(t, []string{"live/first"}, firstUpdates, "detached callback must not receive buffered updates") + + replacementToken, attached := AttachCallback(func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + for path := range update { + replacementUpdates = append(replacementUpdates, path) + } + return nil + }) + require.True(t, attached) + require.Equal(t, []string{"buffered/replacement"}, replacementUpdates, "replacement should replay the buffered update") + + // A stale shutdown must not detach the replacement. + require.NoError(t, UnsubscribeProvider(firstToken)) + forwardingCallback(remoteconfig.ProductUpdate{"live/replacement": []byte("live")}) + require.Equal(t, []string{"live/first"}, firstUpdates) + require.Equal(t, []string{"buffered/replacement", "live/replacement"}, replacementUpdates) + + for _, capability := range []remoteconfig.Capability{ + remoteconfig.FFEFlagEvaluation, + remoteconfig.FFEFlagDependentFlagVariantKeyV1, + } { + has, err := remoteconfig.HasCapability(capability) + require.NoError(t, err) + assert.True(t, has, "fast-path detach must keep tracer capability %d", capability) + } + require.NoError(t, UnsubscribeProvider(replacementToken)) +} + +func TestAttachReplacementReplaysDeliveredStateWithPanickingDebugLogger(t *testing.T) { + if os.Getenv("DD_RC_REPLAY_LOGGER_PANIC_SUBPROCESS") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestAttachReplacementReplaysDeliveredStateWithPanickingDebugLogger$", "-test.count=1") + cmd.Env = append(os.Environ(), "DD_RC_REPLAY_LOGGER_PANIC_SUBPROCESS=1", "DD_LOGGING_RATE=0") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + return + } + + ResetForTest() + t.Cleanup(ResetForTest) + rcState.Lock() + rcState.subscribed = true + rcState.Unlock() + + firstToken, attached := AttachCallback(func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + return acknowledgedStatuses(update) + }) + require.True(t, attached) + forwardingCallback(remoteconfig.ProductUpdate{"delivered/state": []byte("value")}) + require.NoError(t, UnsubscribeProvider(firstToken)) + + previousLevel := log.GetLevel() + log.SetLevel(log.LevelDebug) + undoLogger := log.UseLogger(panickingRCLogger{}) + t.Cleanup(func() { + undoLogger() + log.SetLevel(previousLevel) + }) + + var replacementUpdates []string + replacementToken, attached := AttachCallback(func(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + for path := range update { + replacementUpdates = append(replacementUpdates, path) + } + return nil + }) + require.True(t, attached) + require.NotZero(t, replacementToken) + require.Equal(t, []string{"delivered/state"}, replacementUpdates) + + // The detached provider's stale token cannot remove replacement ownership. + require.NoError(t, UnsubscribeProvider(firstToken)) + forwardingCallback(remoteconfig.ProductUpdate{"live/state": []byte("next")}) + require.Equal(t, []string{"delivered/state", "live/state"}, replacementUpdates) + require.NoError(t, UnsubscribeProvider(replacementToken)) +} diff --git a/internal/openfeature/testing.go b/internal/openfeature/testing.go index 4a975b5f8b4..ca22d3ec55a 100644 --- a/internal/openfeature/testing.go +++ b/internal/openfeature/testing.go @@ -5,7 +5,11 @@ package openfeature -import "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" +import ( + rc "github.com/DataDog/datadog-agent/pkg/remoteconfig/state" + + "github.com/DataDog/dd-trace-go/v2/internal/remoteconfig" +) // ResetForTest resets the global rcState for test isolation. func ResetForTest() { @@ -13,7 +17,11 @@ func ResetForTest() { defer rcState.Unlock() rcState.subscribed = false rcState.callback = nil + rcState.callbackToken = 0 rcState.buffered = nil + rcState.delivered = nil + rcState.providerSubscription = remoteconfig.SubscriptionToken{} + rcState.providerToken = 0 } // SetSubscribedForTest sets the subscribed flag without actually calling Subscribe. @@ -36,3 +44,8 @@ func GetBufferedForTest() remoteconfig.ProductUpdate { defer rcState.Unlock() return rcState.buffered } + +// ForwardForTest delivers an update through the tracer-owned forwarding path. +func ForwardForTest(update remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { + return forwardingCallback(update) +} diff --git a/internal/remoteconfig/remoteconfig.go b/internal/remoteconfig/remoteconfig.go index 8ecf081cc75..656f9c75f65 100644 --- a/internal/remoteconfig/remoteconfig.go +++ b/internal/remoteconfig/remoteconfig.go @@ -141,6 +141,9 @@ const ( FFEFlagEvaluation ) +// FFEFlagDependentFlagVariantKeyV1 is protocol registration, not evaluator support. +const FFEFlagDependentFlagVariantKeyV1 Capability = 50 + // ErrClientNotStarted is returned when the remote config client is not started. var ErrClientNotStarted = errors.New("remote config client not started") @@ -181,6 +184,9 @@ type Client struct { lastError error lastConfigStates []*configState + // registrationSnapshotHook lets tests hold a request snapshot open while + // another goroutine attempts to subscribe. It is nil outside tests. + registrationSnapshotHook func() } // subscription represents a callback that was registered to run on updates to a @@ -438,7 +444,18 @@ func (c *Client) requestPoll() { } } -type SubscriptionToken int +// SubscriptionToken identifies a subscription on the client that created it. +// Tokens from a stopped client are harmless when a replacement client is +// running, even if both clients allocated the same numeric subscription ID. +type SubscriptionToken struct { + client *Client + id int +} + +// IsZero reports whether token identifies no subscription. +func (token SubscriptionToken) IsZero() bool { + return token.client == nil +} // Subscribe registers a product and its callback to be invoked when the client // receives configuration updates for the specified product. The returned token @@ -446,10 +463,8 @@ type SubscriptionToken int // // It is legal to call Subscribe multiple times with the same product, and even // to call it multiple times with the same product and different capabilities. -// Note, however, that the capabilities reported to RC are the union of all -// capabilities passed to Subscribe and RegisterCapability (across all -// products); in other words, the capabilities are not tied to a specific -// product or subscription. +// The capabilities reported to RC are the union of all capabilities passed to +// active subscriptions and RegisterCapability calls across all products. // // Subscribe should be preferred over RegisterProduct and RegisterCallback if // your callback only handles a single product. @@ -458,12 +473,12 @@ func Subscribe(product string, callback ProductCallback, capabilities ...Capabil // global) can't cause a nil deref mid-function. c := clientSingleton.Load() if c == nil { - return 0, ErrClientNotStarted + return SubscriptionToken{}, ErrClientNotStarted } c.productsMu.RLock() defer c.productsMu.RUnlock() if _, found := c.products[product]; found { - return 0, fmt.Errorf("product %s already registered via RegisterProduct", product) + return SubscriptionToken{}, fmt.Errorf("product %s already registered via RegisterProduct", product) } c.subscriptionsMu.Lock() @@ -478,16 +493,11 @@ func Subscribe(product string, callback ProductCallback, capabilities ...Capabil } c.subscriptionsMu.subs = append(c.subscriptionsMu.subs, sub) - c.capabilitiesMu.Lock() - defer c.capabilitiesMu.Unlock() - for _, cap := range capabilities { - c.capabilities[cap] = struct{}{} - } // Poll now: Subscribe registers product+callback+capabilities atomically, so // the poll can't arrive before the callback. (RegisterProduct/RegisterCapability // don't — they're used before a callback exists; see those.) c.requestPoll() - return SubscriptionToken(id), nil + return SubscriptionToken{client: c, id: id}, nil } // Unsubscribe removes a subscription previously registered via Subscribe. The @@ -498,15 +508,20 @@ func Unsubscribe(token SubscriptionToken) error { if client == nil { return ErrClientNotStarted } + if token.client != client { + // The issuing client was stopped or replaced. Its subscriptions ended + // with it, and token.id may identify an unrelated subscription now. + return nil + } client.subscriptionsMu.Lock() defer client.subscriptionsMu.Unlock() for i, sub := range client.subscriptionsMu.subs { - if sub.id == int(token) { + if sub.id == token.id { client.subscriptionsMu.subs = append(client.subscriptionsMu.subs[:i], client.subscriptionsMu.subs[i+1:]...) return nil } } - return fmt.Errorf("subscription %d not found", token) + return fmt.Errorf("subscription %d not found", token.id) } // RegisterCallback allows registering a callback that will be invoked when the client @@ -633,30 +648,57 @@ func HasCapability(cpb Capability) (bool, error) { return false, ErrClientNotStarted } client.capabilitiesMu.RLock() - defer client.capabilitiesMu.RUnlock() _, found := client.capabilities[cpb] - return found, nil + client.capabilitiesMu.RUnlock() + if found { + return true, nil + } + client.subscriptionsMu.RLock() + defer client.subscriptionsMu.RUnlock() + for _, subscription := range client.subscriptionsMu.subs { + if slices.Contains(subscription.capabilities, cpb) { + return true, nil + } + } + return false, nil } -func (c *Client) allCapabilities() *big.Int { - capa := big.NewInt(0) - - // Read registered capabilities without holding the lock while we also read subscriptions. +// requestRegistrations snapshots the products and capabilities reported in one +// request while holding the registration locks in the Client's documented +// order. A concurrent Subscribe therefore cannot appear in only one field. +func (c *Client) requestRegistrations() ([]string, *big.Int) { + c.productsMu.RLock() + c.subscriptionsMu.RLock() c.capabilitiesMu.RLock() - for i := range c.capabilities { - capa.SetBit(capa, int(i), 1) + defer c.capabilitiesMu.RUnlock() + defer c.subscriptionsMu.RUnlock() + defer c.productsMu.RUnlock() + if c.registrationSnapshotHook != nil { + c.registrationSnapshotHook() } - c.capabilitiesMu.RUnlock() - c.subscriptionsMu.RLock() - for _, s := range c.subscriptionsMu.subs { - for _, cap := range s.capabilities { - capa.SetBit(capa, int(cap), 1) + products := make(map[string]struct{}) + for product := range c.products { + products[product] = struct{}{} + } + + capabilities := big.NewInt(0) + for capability := range c.capabilities { + capabilities.SetBit(capabilities, int(capability), 1) + } + + for _, subscription := range c.subscriptionsMu.subs { + products[subscription.product] = struct{}{} + for _, capability := range subscription.capabilities { + capabilities.SetBit(capabilities, int(capability), 1) } } - c.subscriptionsMu.RUnlock() - return capa + productList := make([]string, 0, len(products)) + for product := range products { + productList = append(productList, product) + } + return productList, capabilities } func (c *Client) globalCallbacks() []Callback { @@ -874,7 +916,7 @@ func (c *Client) newUpdateRequest() (bytes.Buffer, error) { c.lastConfigStates = pbConfigState } - capa := c.allCapabilities() + products, capabilities := c.requestRegistrations() var tags []string for k, v := range internal.GetGitMetadataTags() { tags = append(tags, k+":"+v) @@ -889,7 +931,7 @@ func (c *Client) newUpdateRequest() (bytes.Buffer, error) { Error: errMsg, }, ID: c.clientID, - Products: c.allProducts(), + Products: products, IsTracer: true, ClientTracer: &clientTracer{ RuntimeID: c.RuntimeID, @@ -901,7 +943,7 @@ func (c *Client) newUpdateRequest() (bytes.Buffer, error) { ProcessTags: processtags.GlobalTags().Slice(), Tags: tags, }, - Capabilities: capa.Bytes(), + Capabilities: capabilities.Bytes(), }, CachedTargetFiles: pbCachedFiles, } diff --git a/internal/remoteconfig/remoteconfig_test.go b/internal/remoteconfig/remoteconfig_test.go index 254d1c31b4c..4e12e1eca46 100644 --- a/internal/remoteconfig/remoteconfig_test.go +++ b/internal/remoteconfig/remoteconfig_test.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "io" + "math/big" "math/rand" "net/http" "reflect" @@ -373,6 +374,100 @@ func TestSubscribe(t *testing.T) { require.Len(t, client.callbacks, 1) } +func TestSubscriptionTokenCannotUnsubscribeReplacementClient(t *testing.T) { + Reset() + t.Cleanup(Reset) + + oldClient, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(oldClient) + oldToken, err := Subscribe("FFE_FLAGS", func(ProductUpdate) map[string]state.ApplyStatus { return nil }) + require.NoError(t, err) + require.Equal(t, 1, oldToken.id) + + replacementClient, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(replacementClient) + replacementToken, err := Subscribe("APM_TRACING", func(ProductUpdate) map[string]state.ApplyStatus { return nil }) + require.NoError(t, err) + require.Equal(t, oldToken.id, replacementToken.id, "subscription IDs restart with each client") + + require.NoError(t, Unsubscribe(oldToken)) + has, err := HasProduct("APM_TRACING") + require.NoError(t, err) + assert.True(t, has, "an old token must not affect a replacement client") +} + +func TestSubscriptionCapabilitiesFollowSubscriptionLifetime(t *testing.T) { + Reset() + t.Cleanup(Reset) + + client, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(client) + callback := func(ProductUpdate) map[string]state.ApplyStatus { return nil } + first, err := Subscribe("FIRST", callback, FFEFlagEvaluation) + require.NoError(t, err) + second, err := Subscribe("SECOND", callback, FFEFlagEvaluation) + require.NoError(t, err) + + has, err := HasCapability(FFEFlagEvaluation) + require.NoError(t, err) + require.True(t, has) + require.NoError(t, Unsubscribe(first)) + has, err = HasCapability(FFEFlagEvaluation) + require.NoError(t, err) + require.True(t, has, "the remaining subscription still owns the capability") + + require.NoError(t, Unsubscribe(second)) + has, err = HasCapability(FFEFlagEvaluation) + require.NoError(t, err) + assert.False(t, has, "the capability ends with its final subscription") +} + +func TestSubscriptionTokenSafeDuringClientReplacement(t *testing.T) { + Reset() + t.Cleanup(Reset) + + for i := range 1000 { + oldClient, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(oldClient) + oldToken, err := Subscribe("FFE_FLAGS", func(ProductUpdate) map[string]state.ApplyStatus { return nil }) + require.NoError(t, err) + + replacementClient, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(replacementClient) + _, err = Subscribe("APM_TRACING", func(ProductUpdate) map[string]state.ApplyStatus { return nil }) + require.NoError(t, err) + clientSingleton.Store(oldClient) + + start := make(chan struct{}) + unsubscribeErr := make(chan error, 1) + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + <-start + unsubscribeErr <- Unsubscribe(oldToken) + }() + go func() { + defer wg.Done() + <-start + clientSingleton.Store(replacementClient) + }() + close(start) + wg.Wait() + require.NoError(t, <-unsubscribeErr) + + clientSingleton.Store(replacementClient) + has, err := HasProduct("APM_TRACING") + require.NoError(t, err) + require.True(t, has, "iteration %d: replacement subscription removed", i) + } +} + func TestNewUpdateRequest(t *testing.T) { cfg := DefaultClientConfig() cfg.ServiceName = "test-svc" @@ -604,8 +699,8 @@ func TestAsync(t *testing.T) { require.Empty(t, client.callbacks) } -// Ensure the lock ordering between capabilities and subscriptions does not deadlock. -func TestAllCapabilitiesNoDeadlockWithSubscribe(t *testing.T) { +// Ensure request registration snapshots do not deadlock with subscriptions. +func TestRequestRegistrationsNoDeadlockWithSubscribe(t *testing.T) { Reset() cfg := DefaultClientConfig() c, err := newClient(cfg) @@ -637,11 +732,11 @@ func TestAllCapabilitiesNoDeadlockWithSubscribe(t *testing.T) { } }() - // Read allCapabilities concurrently. + // Read request registrations concurrently. go func() { defer wg.Done() for range iterations { - c.allCapabilities() + c.requestRegistrations() } }() @@ -654,10 +749,69 @@ func TestAllCapabilitiesNoDeadlockWithSubscribe(t *testing.T) { select { case <-done: case <-time.After(5 * time.Second): - t.Fatal("allCapabilities deadlocked with concurrent subscribe") + t.Fatal("requestRegistrations deadlocked with concurrent subscribe") } } +func TestNewUpdateRequestSnapshotsSubscriptionRegistrationAtomically(t *testing.T) { + Reset() + t.Cleanup(Reset) + + client, err := newClient(DefaultClientConfig()) + require.NoError(t, err) + clientSingleton.Store(client) + + snapshotEntered := make(chan struct{}) + releaseSnapshot := make(chan struct{}) + client.registrationSnapshotHook = func() { + close(snapshotEntered) + <-releaseSnapshot + } + + type requestResult struct { + body bytes.Buffer + err error + } + requestDone := make(chan requestResult, 1) + go func() { + body, err := client.newUpdateRequest() + requestDone <- requestResult{body: body, err: err} + }() + <-snapshotEntered + + subscribeStarted := make(chan struct{}) + subscribeDone := make(chan error, 1) + go func() { + close(subscribeStarted) + _, err := Subscribe("ATOMIC_PRODUCT", func(ProductUpdate) map[string]state.ApplyStatus { return nil }, FFEFlagEvaluation) + subscribeDone <- err + }() + <-subscribeStarted + select { + case err := <-subscribeDone: + t.Fatalf("Subscribe completed while the request held its registration snapshot: %v", err) + default: + } + + close(releaseSnapshot) + first := <-requestDone + require.NoError(t, first.err) + require.NoError(t, <-subscribeDone) + client.registrationSnapshotHook = nil + + var before clientGetConfigsRequest + require.NoError(t, json.Unmarshal(first.body.Bytes(), &before)) + assert.NotContains(t, before.Client.Products, "ATOMIC_PRODUCT") + assert.Equal(t, uint(0), new(big.Int).SetBytes(before.Client.Capabilities).Bit(int(FFEFlagEvaluation))) + + afterBody, err := client.newUpdateRequest() + require.NoError(t, err) + var after clientGetConfigsRequest + require.NoError(t, json.Unmarshal(afterBody.Bytes(), &after)) + assert.Contains(t, after.Client.Products, "ATOMIC_PRODUCT") + assert.Equal(t, uint(1), new(big.Int).SetBytes(after.Client.Capabilities).Bit(int(FFEFlagEvaluation))) +} + // roundTripFunc adapts a function to an http.RoundTripper. type roundTripFunc func(*http.Request) (*http.Response, error) diff --git a/openfeature/agentless_source.go b/openfeature/agentless_source.go index 0098cf1265a..cb5763abaa7 100644 --- a/openfeature/agentless_source.go +++ b/openfeature/agentless_source.go @@ -14,6 +14,7 @@ import ( "math/rand/v2" "net/http" "net/url" + "slices" "strconv" "strings" "sync" @@ -87,7 +88,12 @@ func newAgentlessSource(settings internalffe.Settings, selection *FlagSelection, if err != nil { return nil, err } - requestURL, selectionSent := requestURLWithFlagSelection(endpoint.url, selection) + requestURL, err := url.Parse(endpoint.url) + if err != nil { + return nil, err + } + addEvaluatorCapabilities(requestURL, internalffe.EvaluatorCapabilities()) + requestURLString, selectionSent := requestURLWithFlagSelection(requestURL.String(), selection) apiKey := "" if endpoint.managed { @@ -95,7 +101,7 @@ func newAgentlessSource(settings internalffe.Settings, selection *FlagSelection, } s := &agentlessSource{ - endpoint: requestURL, + endpoint: requestURLString, apiKey: apiKey, env: settings.Env, managed: endpoint.managed, @@ -235,6 +241,34 @@ func reportMalformedAgentlessConfiguration(err error) { telemetrylog.ReportError("openfeature: agentless: received malformed configuration", err) } +func addEvaluatorCapabilities(requestURL *url.URL, capabilities []string) { + if !slices.Contains(capabilities, internalffe.DependentFlagVariantKeyV1) { + return + } + capability := url.QueryEscape(internalffe.DependentFlagsVariantKeyQueryParameter) + "=" + url.QueryEscape(internalffe.DependentFlagsVariantKeyQueryVersion) + if requestURL.RawQuery == "" { + requestURL.RawQuery = capability + return + } + + // Remove every existing spelling of this key, including stale and duplicate + // values, without re-encoding or reordering unrelated query segments. + segments := strings.Split(requestURL.RawQuery, "&") + kept := segments[:0] + for _, segment := range segments { + rawKey, _, _ := strings.Cut(segment, "=") + key, err := url.QueryUnescape(rawKey) + if err == nil && key == internalffe.DependentFlagsVariantKeyQueryParameter { + continue + } + kept = append(kept, segment) + } + requestURL.RawQuery = capability + if len(kept) > 0 { + requestURL.RawQuery += "&" + strings.Join(kept, "&") + } +} + // attempt is only used to number debug log lines. func (s *agentlessSource) pollOnce(attempt int) (pollOutcome, time.Duration) { ctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout) diff --git a/openfeature/agentless_source_httptest_test.go b/openfeature/agentless_source_httptest_test.go index be0653e8d01..320ed690173 100644 --- a/openfeature/agentless_source_httptest_test.go +++ b/openfeature/agentless_source_httptest_test.go @@ -714,3 +714,75 @@ func (l *capturingLogger) countContaining(substr string) int { } return count } + +func TestAgentlessSourceRequestsDependentFlagsParameter(t *testing.T) { + var requests int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + assert.Equal(t, "v1", r.URL.Query().Get("cap_dependent-flags-variant-key")) + if requests == 1 { + w.Header().Set("ETag", fakeUFCBackendETag) + _, _ = w.Write([]byte(fakeUFCValidBody)) + } else { + assert.Equal(t, fakeUFCBackendETag, r.Header.Get("If-None-Match")) + w.WriteHeader(http.StatusNotModified) + } + })) + defer server.Close() + source, err := newAgentlessSource(internalffe.Settings{ + AgentlessBaseURL: server.URL, + PollInterval: time.Second, + RequestTimeout: time.Second, + }, nil, func(*universalFlagsConfiguration) {}) + require.NoError(t, err) + source.pollOnce(1) + source.pollOnce(1) + assert.Equal(t, 2, requests) +} + +func TestAddEvaluatorCapabilitiesUsesQueryParameter(t *testing.T) { + for _, test := range []struct { + name string + requestURL string + capabilities []string + expected string + }{ + { + name: "absent", + requestURL: "https://example.test/ufc?token=preserved", + expected: "https://example.test/ufc?token=preserved", + }, + { + name: "unknown", + requestURL: "https://example.test/ufc?token=preserved", + capabilities: []string{"unknown-v1"}, + expected: "https://example.test/ufc?token=preserved", + }, + { + name: "dependent flags", + requestURL: "https://example.test/ufc?token=preserved", + capabilities: []string{internalffe.DependentFlagVariantKeyV1}, + expected: "https://example.test/ufc?cap_dependent-flags-variant-key=v1&token=preserved", + }, + { + name: "duplicate and stale values", + requestURL: "https://example.test/ufc?cap_dependent-flags-variant-key=stale&token=%2f&cap_dependent-flags-variant-key=v1&empty=&cap_dependent-flags-variant-key=older#fragment", + capabilities: []string{internalffe.DependentFlagVariantKeyV1}, + expected: "https://example.test/ufc?cap_dependent-flags-variant-key=v1&token=%2f&empty=#fragment", + }, + { + name: "encoded stale key", + requestURL: "https://example.test/ufc?token=a+b&cap%5Fdependent-flags-variant-key=stale&token=%2F", + capabilities: []string{internalffe.DependentFlagVariantKeyV1}, + expected: "https://example.test/ufc?cap_dependent-flags-variant-key=v1&token=a+b&token=%2F", + }, + } { + t.Run(test.name, func(t *testing.T) { + requestURL, err := url.Parse(test.requestURL) + require.NoError(t, err) + addEvaluatorCapabilities(requestURL, test.capabilities) + + assert.Equal(t, test.expected, requestURL.String()) + }) + } +} diff --git a/openfeature/customer_exposure_hook_test.go b/openfeature/customer_exposure_hook_test.go index 272a008c9ac..af6ede1afea 100644 --- a/openfeature/customer_exposure_hook_test.go +++ b/openfeature/customer_exposure_hook_test.go @@ -10,6 +10,8 @@ import ( "encoding/json" "errors" "net/http" + "os" + "os/exec" "strconv" "sync" "sync/atomic" @@ -569,6 +571,42 @@ func TestCustomerExposureHookPanicLogging(t *testing.T) { assert.Zero(t, logger.countContaining("private callback value")) } +// DD_LOGGING_RATE is initialized once by the log package. The subprocess makes +// both callback-recovery logs immediate while a customer logger panics on them. +func TestCustomerExposureHookDependencyPanicAndLoggerPanicDoNotChangeAssignment(t *testing.T) { + if os.Getenv("DD_EXPOSURE_CALLBACK_PANIC_SUBPROCESS") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestCustomerExposureHookDependencyPanicAndLoggerPanicDoNotChangeAssignment$", "-test.count=1") + cmd.Env = append(os.Environ(), "DD_EXPOSURE_CALLBACK_PANIC_SUBPROCESS=1", "DD_LOGGING_RATE=0") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + return + } + + h := newOptOutHarness(t, ProviderConfig{}) + h.provider.setConfiguration(dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + )) + var callbacks atomic.Int32 + h.client.AddHooks(NewExposureHook(func(ExposureEvaluation) { + callbacks.Add(1) + panic("private callback value") + })) + previousLevel := log.GetLevel() + log.SetLevel(log.LevelDebug) + undoLogger := log.UseLogger(panickingLogger{}) + t.Cleanup(func() { + undoLogger() + log.SetLevel(previousLevel) + }) + + value, err := h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + require.True(t, value) + require.Equal(t, int32(2), callbacks.Load(), "dependency and root callbacks both run") +} + func TestCustomerExposureHookAfterPanicLimitation(t *testing.T) { h := newOptOutHarness(t, ProviderConfig{}) var rows []ExposureEvaluation @@ -606,3 +644,114 @@ func TestDisabledExposureDeliveryDoesNotStartWorker(t *testing.T) { w.stop() w.stop() } + +func TestDisabledExposureDeliveryPublishesAndCachesDependenciesForCustomerHooks(t *testing.T) { + internalconfig.SetUseFreshConfig(true) + t.Cleanup(func() { internalconfig.SetUseFreshConfig(false); internalconfig.CreateNew() }) + t.Setenv("DD_FEATURE_FLAGS_EXPOSURES_DATADOG_LOGGING_ENABLED", "false") + h := newOptOutHarness(t, ProviderConfig{}) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + h.provider.mu.Unlock() + + var rows []ExposureEvaluation + h.client.AddHooks(NewExposureHook(func(e ExposureEvaluation) { rows = append(rows, e) })) + evalCtx := of.NewEvaluationContext("subject", nil) + _, err := h.client.BooleanValue(context.Background(), "root", false, evalCtx) + require.NoError(t, err) + _, err = h.client.BooleanValue(context.Background(), "dependency", false, evalCtx) + require.NoError(t, err) + + require.Len(t, rows, 3) + assert.Equal(t, "dependency", rows[0].Details.FlagKey) + assert.True(t, rows[0].ShouldSend()) + assert.Equal(t, "root", rows[1].Details.FlagKey) + assert.True(t, rows[1].ShouldSend()) + assert.Equal(t, "dependency", rows[2].Details.FlagKey) + assert.True(t, rows[2].IsCacheHit(), "the prerequisite callback shares the direct-read cache") + require.Empty(t, h.provider.exposureWriter.buffer) +} + +func TestCustomerExposureHookDependenciesRequireFinalRootSuccess(t *testing.T) { + for _, test := range []struct { + name string + configure func(*universalFlagsConfiguration) + rejectRoot bool + }{ + { + name: "application_after_rejects_root", + rejectRoot: true, + }, + { + name: "dependency_graph_fails", + configure: func(config *universalFlagsConfiguration) { + config.Flags["root"].Allocations[0].Rules[0].Conditions = append( + config.Flags["root"].Allocations[0].Rules[0].Conditions, + dependencyCondition("missing", operatorOneOf, "on")) + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + if test.configure != nil { + test.configure(config) + } + h.provider.mu.Lock() + h.provider.configuration = config + h.provider.mu.Unlock() + var rows []ExposureEvaluation + h.client.AddHooks(NewExposureHook(func(e ExposureEvaluation) { rows = append(rows, e) })) + var options []of.Option + if test.rejectRoot { + options = append(options, of.WithHooks(rejectExposureResultHook{})) + } + _, err := h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("subject", nil), options...) + require.Error(t, err) + require.Len(t, rows, 1, "failed roots must not replay transactionally selected prerequisites") + assert.Equal(t, "root", rows[0].Details.FlagKey) + assert.False(t, rows[0].IsExposure()) + h.provider.exposureWriter.flush() + assert.Empty(t, h.sink.exposures) + }) + } +} + +func TestCustomerExposureHookDependencyFeaturesAreDetached(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + dependency := dependencyTestFlag("dependency", "dependency-on", nil) + dependency.Allocations[0].Splits[0].Features = splitFeatures{ + {Key: "cohort", Value: "control", Destinations: []string{"HOOK"}}, + } + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependency, + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + h.provider.mu.Unlock() + + h.client.AddHooks(NewExposureHook(func(e ExposureEvaluation) { + if e.Details.FlagKey == "dependency" { + features := e.Features() + require.Equal(t, map[string]any{"cohort": "control"}, features) + features["cohort"] = "caller mutation" + e.Details.FlagMetadata[metadataHookFeaturePrefix+"cohort"] = "metadata mutation" + } + })) + var second []ExposureEvaluation + h.client.AddHooks(NewExposureHook(func(e ExposureEvaluation) { second = append(second, e) })) + + _, err := h.client.BooleanValue(context.Background(), "root", false, of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + require.Len(t, second, 2) + require.Equal(t, "dependency", second[0].Details.FlagKey) + require.Equal(t, map[string]any{"cohort": "control"}, second[0].Features()) + require.Equal(t, "control", dependency.Allocations[0].Splits[0].featureMetadata()[metadataHookFeaturePrefix+"cohort"]) +} diff --git a/openfeature/debug_logging_test.go b/openfeature/debug_logging_test.go index cdede6b1e85..23db097722a 100644 --- a/openfeature/debug_logging_test.go +++ b/openfeature/debug_logging_test.go @@ -252,7 +252,7 @@ func TestDebugLogging_AfterHookFailure(t *testing.T) { name: "ObjectValueDetails keeps the resolved value", flagType: "object", evaluate: func(c *of.Client) (any, error) { - details, err := c.ObjectValueDetails(context.Background(), "bool-flag", false, evalCtx) + details, err := c.ObjectValueDetails(context.Background(), "bool-flag", anyEvaluationDefault{}, evalCtx) return details.Value, err }, want: true, @@ -273,8 +273,12 @@ func TestDebugLogging_AfterHookFailure(t *testing.T) { require.ErrorContains(t, err, "application after hook failed") require.Equal(t, tc.want, value) - logger.assertContains(t, `openfeature: provider resolved "bool-flag": type=`+tc.flagType+`, value=true, default=false, variant="on", reason=TARGETING_MATCH, allocation="allocation1", serial_id=, error_code=, error_message=""`) - logger.assertContains(t, `openfeature: evaluation of "bool-flag" failed: after hook: application after hook failed (default value false, targeting_key="user-1", attributes={"country":"US"})`) + defaultValue := "false" + if tc.flagType == "object" { + defaultValue = "{}" + } + logger.assertContains(t, `openfeature: provider resolved "bool-flag": type=`+tc.flagType+`, value=true, default=`+defaultValue+`, variant="on", reason=TARGETING_MATCH, allocation="allocation1", serial_id=, error_code=, error_message=""`) + logger.assertContains(t, `openfeature: evaluation of "bool-flag" failed: after hook: application after hook failed (default value `+defaultValue+`, targeting_key="user-1", attributes={"country":"US"})`) assertNoReturnedValueClaims(t, logger, "bool-flag") }) } diff --git a/openfeature/dependent_flags_test.go b/openfeature/dependent_flags_test.go new file mode 100644 index 00000000000..1d7097a9493 --- /dev/null +++ b/openfeature/dependent_flags_test.go @@ -0,0 +1,1572 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2026 Datadog, Inc. + +package openfeature + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "strings" + "sync" + "testing" + "time" + + of "github.com/open-feature/go-sdk/openfeature" + "github.com/stretchr/testify/require" + + "github.com/DataDog/dd-trace-go/v2/internal/log" +) + +func TestDependentFlags_JSONConfiguration(t *testing.T) { + var config universalFlagsConfiguration + require.NoError(t, json.Unmarshal([]byte(`{ + "format":"SERVER", + "evaluatorParams":{"maxDependencyDepth":3}, + "flags":{"root":{"key":"root","enabled":true,"variationType":"BOOLEAN", + "variations":{"on":{"key":"on","value":true}}, + "allocations":[{"key":"root-allocation","rules":[{"conditions":[ + {"operator":"ONE_OF","flagEvaluation":{"key":"dependency"},"value":["on"]} + ]}],"splits":[{"variationKey":"on","shards":[]}]} + ]}} + }`), &config)) + require.JSONEq(t, `{"maxDependencyDepth":3}`, string(config.EvaluatorParams)) + require.Equal(t, 3, configuredMaxDependencyDepth(&config)) + condition := config.Flags["root"].Allocations[0].Rules[0].Conditions[0] + require.Equal(t, "dependency", condition.FlagEvaluation.Key) + require.Empty(t, condition.Attribute) +} + +func TestDependentFlags_NonObjectEvaluatorParamsUseDefaults(t *testing.T) { + for _, raw := range []string{`null`, `42`, `"future"`, `true`, `[]`} { + t.Run(raw, func(t *testing.T) { + var config universalFlagsConfiguration + require.NoError(t, json.Unmarshal([]byte(`{"format":"SERVER","evaluatorParams":`+raw+`,"flags":{}}`), &config)) + require.JSONEq(t, raw, string(config.EvaluatorParams)) + }) + } +} + +func TestDependentFlags_EvaluatorParamsRemainOptionalAndExtensible(t *testing.T) { + var config universalFlagsConfiguration + require.NoError(t, json.Unmarshal([]byte(`{ + "format":"SERVER", + "evaluatorParams":{"futureOption":{"enabled":true},"maxDependencyDepth":3}, + "flags":{} + }`), &config)) + + encoded, err := json.Marshal(&config) + require.NoError(t, err) + var roundTrip struct { + EvaluatorParams json.RawMessage `json:"evaluatorParams"` + } + require.NoError(t, json.Unmarshal(encoded, &roundTrip)) + require.JSONEq(t, `{"futureOption":{"enabled":true},"maxDependencyDepth":3}`, string(roundTrip.EvaluatorParams)) + + var withoutParams universalFlagsConfiguration + require.NoError(t, json.Unmarshal([]byte(`{"format":"SERVER","flags":{}}`), &withoutParams)) + require.Empty(t, withoutParams.EvaluatorParams) + encoded, err = json.Marshal(&withoutParams) + require.NoError(t, err) + require.NotContains(t, string(encoded), "evaluatorParams") +} + +func TestDependentFlags_JSONConditionValidation(t *testing.T) { + tests := []struct { + name string + condition string + valid bool + }{ + {name: "explicit empty attribute", condition: `{"operator":"ONE_OF","attribute":"","value":["on"]}`, valid: true}, + {name: "missing source", condition: `{"operator":"ONE_OF","value":["on"]}`}, + {name: "both sources", condition: `{"operator":"ONE_OF","attribute":"","flagEvaluation":{"key":"dependency"},"value":["on"]}`}, + {name: "extra flag evaluation field", condition: `{"operator":"ONE_OF","flagEvaluation":{"key":"dependency","extra":true},"value":["on"]}`, valid: true}, + {name: "empty flag evaluation key", condition: `{"operator":"ONE_OF","flagEvaluation":{"key":""},"value":["on"]}`}, + {name: "null flag evaluation key", condition: `{"operator":"ONE_OF","flagEvaluation":{"key":null},"value":["on"]}`}, + {name: "non string flag evaluation key", condition: `{"operator":"ONE_OF","flagEvaluation":{"key":42},"value":["on"]}`}, + {name: "dependency matches operator", condition: `{"operator":"MATCHES","flagEvaluation":{"key":"dependency"},"value":"on"}`}, + {name: "dependency not matches operator", condition: `{"operator":"NOT_MATCHES","flagEvaluation":{"key":"dependency"},"value":"on"}`}, + {name: "non string member", condition: `{"operator":"ONE_OF","flagEvaluation":{"key":"dependency"},"value":["on",1]}`}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var config universalFlagsConfiguration + require.NoError(t, json.Unmarshal([]byte(dependencyJSONConfiguration(test.condition)), &config)) + _, valid := config.Flags["root"] + require.Equal(t, test.valid, valid) + if !test.valid { + require.Contains(t, config.invalidFlags, "root") + result := evaluateConfiguredFlag(&config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, of.ParseErrorCode, errorCodeFor(result.Error)) + } + }) + } +} + +func TestDependentFlags_NotOneOf(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "selected", dependencyCondition("dependency", operatorNotOneOf, "off")), + ) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + require.Equal(t, []string{"dependency"}, dependencyExposureKeys(result)) +} + +func TestDependentFlags_NestedEvaluationReturnsTelemetryBatch(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("leaf", "leaf-on", nil), + dependencyTestFlag("middle", "middle-on", dependencyCondition("leaf", operatorOneOf, "leaf-on")), + dependencyTestFlag("root", "root-on", dependencyCondition("middle", operatorOneOf, "middle-on")), + ) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + + require.NoError(t, result.Error) + require.Equal(t, true, result.Value) + require.Equal(t, []string{"middle", "leaf"}, dependencyEvaluationKeys(result)) + for _, record := range result.DependencyEvaluations { + require.NotZero(t, record.Result.Metadata[metadataEvalTimeKey]) + } + require.Equal(t, []string{"leaf", "middle"}, dependencyExposureKeys(result)) +} + +func TestDependentFlags_TransactionalExposureRollbackAndMemoReplay(t *testing.T) { + dependency := dependencyTestFlag("dependency", "dependency-on", nil) + root := dependencyTestFlag("root", "root-on", nil) + root.Allocations[0].Rules = []*rule{ + {Conditions: []*condition{ + dependencyCondition("dependency", operatorOneOf, "dependency-on"), + {Attribute: "tier", Operator: operatorOneOf, Value: []string{"paid"}}, + }}, + {Conditions: []*condition{dependencyCondition("dependency", operatorOneOf, "dependency-on")}}, + } + config := dependencyTestConfig(dependency, root) + + result := evaluateConfiguredFlag(config, "root", false, map[string]any{"tier": "free"}, time.Now(), experimentationExclusion{}) + + require.NoError(t, result.Error) + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result), "memoized prerequisites return evaluation telemetry once") + require.Equal(t, []string{"dependency"}, dependencyExposureKeys(result), "the second rule replays the rolled-back candidate") + + root.Allocations[0].Rules = root.Allocations[0].Rules[:1] + result = evaluateConfiguredFlag(config, "root", false, map[string]any{"tier": "free"}, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.Equal(t, of.DefaultReason, result.Reason) + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result), "reached evaluations survive rejected rules") + require.Empty(t, dependencyExposureKeys(result), "an unmatched root path must not commit prerequisite exposures") +} + +func TestDependentFlags_MemoizationDeduplicatesActualEvaluation(t *testing.T) { + dependency := dependencyTestFlag("dependency", "on", nil) + root := dependencyTestFlag("root", "on", nil) + root.Allocations[0].Rules = []*rule{{Conditions: []*condition{ + dependencyCondition("dependency", operatorOneOf, "on"), + dependencyCondition("dependency", operatorOneOf, "on"), + }}} + counts := make(map[string]int) + result := evaluateConfiguredFlagWithCounter(dependencyTestConfig(dependency, root), "root", func(key string) { + counts[key]++ + }) + + require.NoError(t, result.Error) + require.Equal(t, 1, counts["dependency"], "memo lookup must bypass actual prerequisite evaluation") + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result)) + require.Equal(t, []string{"dependency"}, dependencyExposureKeys(result)) +} + +func TestDependentFlags_NoAssignmentAbortsWaterfall(t *testing.T) { + noAssignment := dependencyTestFlag("no-assignment", "on", nil) + noAssignment.Allocations[0].Splits = nil + later := dependencyTestFlag("later", "on", nil) + firstRoot := dependencyTestFlag("root", "on", dependencyCondition("no-assignment", operatorOneOf, "on")) + secondRoot := dependencyTestFlag("root", "on", dependencyCondition("later", operatorOneOf, "on")) + firstRoot.Allocations = append(firstRoot.Allocations, secondRoot.Allocations[0]) + counts := make(map[string]int) + result := evaluateConfiguredFlagWithCounter(dependencyTestConfig(noAssignment, later, firstRoot), "root", func(key string) { + counts[key]++ + }) + + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, of.GeneralCode, errorCodeFor(result.Error)) + require.Equal(t, 1, counts["no-assignment"]) + require.Zero(t, counts["later"], "a no-assignment prerequisite must abort before later allocations") + require.Equal(t, []string{"no-assignment"}, dependencyEvaluationKeys(result)) + require.Equal(t, of.GeneralCode, errorCodeFor(result.DependencyEvaluations[0].Result.Error)) + require.Empty(t, dependencyExposureKeys(result)) +} + +func TestDependentFlags_EarlierSiblingTelemetrySurvivesLaterFailure(t *testing.T) { + root := dependencyTestFlag("root", "on", nil) + root.Allocations[0].Rules = []*rule{{Conditions: []*condition{ + dependencyCondition("successful", operatorOneOf, "on"), + dependencyCondition("missing", operatorOneOf, "on"), + }}} + result := evaluateConfiguredFlag(dependencyTestConfig( + dependencyTestFlag("successful", "on", nil), root, + ), "root", false, nil, time.Now(), experimentationExclusion{}) + + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, of.GeneralCode, errorCodeFor(result.Error)) + require.Equal(t, []string{"successful", "missing"}, dependencyEvaluationKeys(result)) + require.NoError(t, result.DependencyEvaluations[0].Result.Error) + require.Equal(t, of.FlagNotFoundCode, errorCodeFor(result.DependencyEvaluations[1].Result.Error)) + require.Empty(t, dependencyExposureKeys(result), "all dependency exposures roll back on graph failure") +} + +func TestDependentFlags_RootGeneralPreservesDependencyError(t *testing.T) { + sharded := dependencyTestFlag("needs-targeting-key", "on", nil) + sharded.Allocations[0].Splits[0].Shards = []*shard{{ + Salt: "salt", TotalShards: 100, Ranges: []*shardRange{{Start: 0, End: 100}}, + }} + for _, test := range []struct { + name string + dependencyKey string + flags []*flag + dependencyCode of.ErrorCode + }{ + {name: "missing", dependencyKey: "missing", dependencyCode: of.FlagNotFoundCode}, + {name: "targeting key missing", dependencyKey: "needs-targeting-key", flags: []*flag{sharded}, dependencyCode: of.TargetingKeyMissingCode}, + } { + t.Run(test.name, func(t *testing.T) { + root := dependencyTestFlag("root", "on", dependencyCondition(test.dependencyKey, operatorOneOf, "on")) + result := evaluateConfiguredFlag(dependencyTestConfig(append(test.flags, root)...), "root", false, nil, time.Now(), experimentationExclusion{}) + + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, of.GeneralCode, errorCodeFor(result.Error), "root must not leak the prerequisite-specific code") + require.Len(t, result.DependencyEvaluations, 1) + require.Equal(t, test.dependencyKey, result.DependencyEvaluations[0].FlagKey) + require.Equal(t, test.dependencyCode, errorCodeFor(result.DependencyEvaluations[0].Result.Error)) + require.NotEmpty(t, result.DependencyEvaluations[0].Result.Error.Error()) + require.Empty(t, dependencyExposureKeys(result)) + }) + } +} + +func TestDependentFlags_ReplaysMemoizedSubtreeAfterRollback(t *testing.T) { + leaf := dependencyTestFlag("leaf", "leaf-on", nil) + parent := dependencyTestFlag("parent", "parent-on", dependencyCondition("leaf", operatorOneOf, "leaf-on")) + root := dependencyTestFlag("root", "root-on", nil) + root.Allocations[0].Rules = []*rule{ + {Conditions: []*condition{dependencyCondition("parent", operatorOneOf, "wrong")}}, + {Conditions: []*condition{dependencyCondition("parent", operatorOneOf, "parent-on")}}, + } + config := dependencyTestConfig(leaf, parent, root) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.Equal(t, []string{"parent", "leaf"}, dependencyEvaluationKeys(result)) + require.Equal(t, []string{"leaf", "parent"}, dependencyExposureKeys(result)) +} + +func TestDependentFlags_RollsBackOnRootFailureAndNoAssignment(t *testing.T) { + for _, test := range []struct { + name string + variation string + splits []*split + wantError bool + }{ + {name: "root failure", variation: "missing", splits: []*split{{VariationKey: "missing", Shards: []*shard{}}}, wantError: true}, + {name: "no assignment", splits: []*split{}}, + } { + t.Run(test.name, func(t *testing.T) { + dependency := dependencyTestFlag("dependency", "on", nil) + root := dependencyTestFlag("root", "selected", dependencyCondition("dependency", operatorOneOf, "on")) + root.Allocations[0].Splits = test.splits + config := dependencyTestConfig(dependency, root) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + if test.wantError { + require.Error(t, result.Error) + } else { + require.NoError(t, result.Error) + require.Equal(t, of.DefaultReason, result.Reason) + } + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result), "reached evaluations are non-transactional") + require.Empty(t, dependencyExposureKeys(result)) + }) + } +} + +func TestDependentFlags_CycleMissingAndDepthErrors(t *testing.T) { + tests := []struct { + name string + config *universalFlagsConfiguration + root string + wantCode of.ErrorCode + wantReached []string + }{ + { + name: "cycle", + config: dependencyTestConfig( + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + dependencyTestFlag("dependency", "dependency-on", dependencyCondition("root", operatorOneOf, "root-on")), + ), + root: "root", wantCode: of.GeneralCode, wantReached: []string{"dependency"}, + }, + { + name: "missing", + config: dependencyTestConfig( + dependencyTestFlag("root", "root-on", dependencyCondition("missing", operatorOneOf, "on")), + ), + root: "root", wantCode: of.GeneralCode, wantReached: []string{"missing"}, + }, + { + name: "maximum depth", + config: dependencyTestConfigWithDepth(1, + dependencyTestFlag("leaf", "leaf-on", nil), + dependencyTestFlag("dependency", "dependency-on", dependencyCondition("leaf", operatorOneOf, "leaf-on")), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ), + root: "root", wantCode: of.GeneralCode, wantReached: []string{"dependency", "leaf"}, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result := evaluateConfiguredFlag(test.config, test.root, false, nil, time.Now(), experimentationExclusion{}) + require.Equal(t, of.ErrorReason, result.Reason) + var graphErr *dependencyGraphError + require.True(t, errors.As(result.Error, &graphErr)) + require.Equal(t, test.wantCode, graphErr.code) + require.Contains(t, toResolutionError(result.Error).Error(), string(test.wantCode)+":") + require.Equal(t, test.wantReached, dependencyEvaluationKeys(result)) + require.Empty(t, dependencyExposureKeys(result)) + }) + } +} + +func TestDependentFlags_OverDepthEmitsRejectedNodeBeforeAncestors(t *testing.T) { + config := dependencyTestConfigWithDepth(1, + dependencyTestFlag("leaf", "leaf-on", nil), + dependencyTestFlag("dependency", "dependency-on", dependencyCondition("leaf", operatorOneOf, "leaf-on")), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + type telemetryEvent struct { + key string + reason of.Reason + errorCode of.ErrorCode + message string + } + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + events := make([]telemetryEvent, 0, len(result.DependencyEvaluations)) + for _, record := range result.DependencyEvaluations { + events = append(events, telemetryEvent{ + key: record.FlagKey, + reason: record.Result.Reason, + errorCode: errorCodeFor(record.Result.Error), + message: record.Result.Error.Error(), + }) + } + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, []telemetryEvent{ + {key: "dependency", reason: of.ErrorReason, errorCode: of.GeneralCode, message: "prerequisite flag \"leaf\" failed: maximum flag dependency depth exceeded"}, + {key: "leaf", reason: of.ErrorReason, errorCode: of.GeneralCode, message: "maximum flag dependency depth exceeded"}, + }, events) +} + +func TestDependentFlags_MemoizedSubtreeDepthFailureDoesNotReemitMemoizedNode(t *testing.T) { + for _, rootDependencies := range [][]string{{"a", "b"}, {"b", "a"}} { + t.Run(rootDependencies[0]+" first", func(t *testing.T) { + leaf := dependencyTestFlag("leaf", "on", nil) + a := dependencyTestFlag("a", "on", dependencyCondition("leaf", operatorOneOf, "on")) + b := dependencyTestFlag("b", "on", dependencyCondition("a", operatorOneOf, "on")) + root := dependencyTestFlag("root", "on", nil) + root.Allocations[0].Rules = []*rule{{Conditions: []*condition{ + dependencyCondition(rootDependencies[0], operatorOneOf, "on"), + dependencyCondition(rootDependencies[1], operatorOneOf, "on"), + }}} + config := dependencyTestConfigWithDepth(2, leaf, a, b, root) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + + require.Equal(t, of.ErrorReason, result.Reason) + want := []string{"a", "leaf", "b"} + if rootDependencies[0] == "b" { + want = []string{"b", "a", "leaf"} + } + require.Equal(t, want, dependencyEvaluationKeys(result)) + require.Empty(t, dependencyExposureKeys(result)) + }) + } +} + +func TestDependentFlags_MissingTelemetryUsesContractMessage(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("root", "on", dependencyCondition("missing", operatorOneOf, "on")), + ) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.Len(t, result.DependencyEvaluations, 1) + dependencyResult := result.DependencyEvaluations[0].Result + require.EqualError(t, dependencyResult.Error, "prerequisite flag is missing") + require.Equal(t, of.ErrorReason, dependencyResult.Reason) + require.Equal(t, of.FlagNotFoundCode, errorCodeFor(dependencyResult.Error)) +} + +func TestDependentFlags_DefaultAndZeroDepth(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error, "missing evaluatorParams uses the default") + + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":0}`) + result = evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.Equal(t, of.ErrorReason, result.Reason) + var graphErr *dependencyGraphError + require.ErrorAs(t, result.Error, &graphErr) + require.Equal(t, of.GeneralCode, graphErr.code) +} + +func TestDependentFlags_DefaultDepthBoundary(t *testing.T) { + for _, test := range []struct { + edges int + wantError bool + }{ + {edges: 10}, + {edges: 11, wantError: true}, + } { + t.Run(fmt.Sprintf("edges_%d", test.edges), func(t *testing.T) { + config := dependencyChainConfig(test.edges) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.Len(t, result.DependencyEvaluations, test.edges) + if test.wantError { + require.Equal(t, of.ErrorReason, result.Reason) + require.Equal(t, of.GeneralCode, errorCodeFor(result.Error)) + require.Empty(t, dependencyExposureKeys(result)) + return + } + require.NoError(t, result.Error) + require.Len(t, dependencyExposureKeys(result), test.edges) + }) + } +} + +func TestDependentFlags_InvalidConfiguredDepthLogsAndUsesDefault(t *testing.T) { + for _, configured := range []string{ + "null", `"3"`, "1.5", "-1", "256", + "254.99999999999999", "255.00000000000001", "1e-400", + "1e1000000", "1e-1000000", + } { + t.Run(configured, func(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + require.NoError(t, json.Unmarshal([]byte(`{"maxDependencyDepth":`+configured+`}`), &config.EvaluatorParams)) + state := new(dependencyEvaluatorState) + evaluate := func() evaluationResult { + root, exists := config.Flags["root"] + return evaluateConfiguredFlagLookedUpWithState(config, "root", root, exists, false, nil, + time.Now(), experimentationExclusion{}, state) + } + result := evaluate() + secondResult := evaluate() + log.Flush() + require.NoError(t, result.Error) + require.NoError(t, secondResult.Error) + require.Equal(t, of.TargetingMatchReason, result.Reason) + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result)) + require.Len(t, result.DependencyEvaluations, 1) + record := result.DependencyEvaluations[0] + require.Equal(t, valueTypeBoolean, record.FlagType) + require.Equal(t, false, record.DefaultValue) + require.Equal(t, true, record.Result.Value) + require.NoError(t, record.Result.Error) + require.Equal(t, []string{"dependency"}, dependencyExposureKeys(result)) + require.Equal(t, 1, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10"), "one immutable configuration emits one diagnostic") + }) + } +} + +func TestDependentFlags_InvalidDepthDiagnosticStateCanBeSharedAcrossConfigCopies(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + require.NoError(t, json.Unmarshal([]byte(`{"maxDependencyDepth":null}`), &config.EvaluatorParams)) + copied := &universalFlagsConfiguration{ + CreatedAt: config.CreatedAt, + Format: config.Format, + Environment: config.Environment, + ObserveFullEvaluationData: config.ObserveFullEvaluationData, + EvaluatorParams: config.EvaluatorParams, + Flags: config.Flags, + invalidFlags: config.invalidFlags, + } + state := new(dependencyEvaluatorState) + + for _, candidate := range []*universalFlagsConfiguration{config, copied, config, copied} { + root, exists := candidate.Flags["root"] + result := evaluateConfiguredFlagLookedUpWithState(candidate, "root", root, exists, false, nil, + time.Now(), experimentationExclusion{}, state) + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + } + log.Flush() + require.Equal(t, 1, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10")) +} + +func TestDependentFlags_InvalidDepthDiagnosticIsOncePerProviderConfiguration(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":null}`) + provider := &DatadogProvider{} + provider.setConfiguration(config) + + for range 2 { + result := provider.evaluate(context.Background(), "root", false, nil, valueTypeBoolean) + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + } + log.Flush() + require.Equal(t, 1, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10")) + + provider.setConfiguration(config) + result := provider.evaluate(context.Background(), "root", false, nil, valueTypeBoolean) + require.NoError(t, result.Error) + log.Flush() + require.Equal(t, 2, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10"), "a replacement configuration gets a fresh diagnostic state") +} + +func TestDependentFlags_InvalidDepthDiagnosticIsError(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":null}`) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + log.Flush() + require.Equal(t, 1, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10")) +} + +// DD_LOGGING_RATE is read when the log package initializes. Run this case in a +// subprocess so log.Error reaches the application logger synchronously and can +// prove a logger panic neither escapes nor leaves sync.Once with a zero depth. +func TestDependentFlags_InvalidDepthPanickingLoggerStillUsesDefault(t *testing.T) { + if os.Getenv("DD_DEPENDENCY_DEPTH_PANIC_SUBPROCESS") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestDependentFlags_InvalidDepthPanickingLoggerStillUsesDefault$", "-test.count=1") + cmd.Env = append(os.Environ(), "DD_DEPENDENCY_DEPTH_PANIC_SUBPROCESS=1", "DD_LOGGING_RATE=0") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + return + } + + withPanickingLogger(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":null}`) + state := new(dependencyEvaluatorState) + for range 2 { + root, exists := config.Flags["root"] + result := evaluateConfiguredFlagLookedUpWithState(config, "root", root, exists, false, nil, + time.Now(), experimentationExclusion{}, state) + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result)) + } +} + +type reentrantDependencyDepthLogger struct { + once sync.Once + evaluate func() +} + +func (l *reentrantDependencyDepthLogger) Log(string) { + l.once.Do(l.evaluate) +} + +func TestDependentFlags_InvalidDepthReentrantLoggerDoesNotDeadlock(t *testing.T) { + if os.Getenv("DD_DEPENDENCY_DEPTH_REENTRANT_SUBPROCESS") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestDependentFlags_InvalidDepthReentrantLoggerDoesNotDeadlock$", "-test.count=1") + cmd.Env = append(os.Environ(), "DD_DEPENDENCY_DEPTH_REENTRANT_SUBPROCESS=1", "DD_LOGGING_RATE=0") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + return + } + + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":null}`) + state := new(dependencyEvaluatorState) + evaluate := func() evaluationResult { + root, exists := config.Flags["root"] + return evaluateConfiguredFlagLookedUpWithState(config, "root", root, exists, false, nil, + time.Now(), experimentationExclusion{}, state) + } + + inner := make(chan evaluationResult, 1) + logger := &reentrantDependencyDepthLogger{} + logger.evaluate = func() { inner <- evaluate() } + previousLevel := log.GetLevel() + log.SetLevel(log.LevelWarn) + undoLogger := log.UseLogger(logger) + t.Cleanup(func() { + undoLogger() + log.SetLevel(previousLevel) + }) + + outer := make(chan evaluationResult, 1) + go func() { outer <- evaluate() }() + for _, evaluation := range []struct { + name string + results <-chan evaluationResult + }{ + {name: "outer", results: outer}, + {name: "reentrant", results: inner}, + } { + select { + case result := <-evaluation.results: + require.NoError(t, result.Error, evaluation.name) + require.True(t, result.Value.(bool), evaluation.name) + require.Equal(t, []string{"dependency"}, dependencyEvaluationKeys(result), evaluation.name) + case <-time.After(2 * time.Second): + t.Fatalf("%s evaluation deadlocked", evaluation.name) + } + } +} + +func TestDependentFlags_UnreachableConditionsRemainLazy(t *testing.T) { + config, root := unreachableDependencyConditionsConfig(10_000) + state := new(dependencyEvaluatorState) + result := evaluateConfiguredFlagLookedUpWithState(config, "root", root, true, false, nil, + time.Now(), experimentationExclusion{}, state) + + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + require.Equal(t, of.StaticReason, result.Reason) + require.Empty(t, result.DependencyEvaluations) + require.Zero(t, state.maxDependencyDepth, "unreached dependencies must not resolve evaluator options") +} + +func BenchmarkDependentFlags_UnreachableConditions(b *testing.B) { + for _, count := range []int{0, 10_000} { + b.Run(fmt.Sprintf("conditions_%d", count), func(b *testing.B) { + config, root := unreachableDependencyConditionsConfig(count) + state := new(dependencyEvaluatorState) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + result := evaluateConfiguredFlagLookedUpWithState(config, "root", root, true, false, nil, + time.Now(), experimentationExclusion{}, state) + if result.Error != nil { + b.Fatal(result.Error) + } + } + }) + } +} + +func unreachableDependencyConditionsConfig(count int) (*universalFlagsConfiguration, *flag) { + root := dependencyTestFlag("root", "on", nil) + conditions := make([]*condition, count) + for i := range conditions { + conditions[i] = dependencyCondition(fmt.Sprintf("unreachable-%d", i), operatorOneOf, "on") + } + root.Allocations = append(root.Allocations, &allocation{ + Key: "unreachable-allocation", + Rules: []*rule{{ + Conditions: conditions, + }}, + Splits: []*split{{VariationKey: "on", Shards: []*shard{}}}, + }) + config := dependencyTestConfig(root) + config.EvaluatorParams = json.RawMessage(`{"maxDependencyDepth":null}`) + return config, root +} + +func TestDependentFlags_ExactIntegerDepthForms(t *testing.T) { + for configured, want := range map[string]int{ + "3.0": 3, + "1e2": 100, + "2.55e2": 255, + "-0": 0, + } { + t.Run(configured, func(t *testing.T) { + config := &universalFlagsConfiguration{ + EvaluatorParams: json.RawMessage(`{"maxDependencyDepth":` + configured + `}`), + } + require.Equal(t, want, configuredMaxDependencyDepth(config)) + }) + } +} + +func TestParseMaxDependencyDepthBoundsAdversarialExponents(t *testing.T) { + tests := []struct { + value string + want int + ok bool + }{ + {value: "1e1000000"}, + {value: "1e-1000000"}, + {value: "255e+000000000000000000000", want: 255, ok: true}, + {value: "255000e-000000000000000003", want: 255, ok: true}, + {value: "0e" + strings.Repeat("9", 100_000), ok: true}, + {value: "1e" + strings.Repeat("9", 100_000)}, + {value: "1e-" + strings.Repeat("9", 100_000)}, + {value: strings.Repeat("9", 100_000)}, + } + for _, tt := range tests { + got, ok := parseMaxDependencyDepth([]byte(tt.value)) + require.Equal(t, tt.ok, ok, "value prefix %.32q", tt.value) + require.Equal(t, tt.want, got, "value prefix %.32q", tt.value) + } +} + +func BenchmarkParseMaxDependencyDepthAdversarialExponent(b *testing.B) { + for _, size := range []int{7, 100_000} { + b.Run(fmt.Sprintf("digits_%d", size), func(b *testing.B) { + raw := []byte("1e" + strings.Repeat("9", size)) + b.SetBytes(int64(len(raw))) + b.ReportAllocs() + for b.Loop() { + _, _ = parseMaxDependencyDepth(raw) + } + }) + } +} + +func TestDependentFlags_InvalidConfiguredDepthPublishesSuccessfulDependencyBatch(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + require.NoError(t, json.Unmarshal([]byte(`{"maxDependencyDepth":null}`), &config.EvaluatorParams)) + h.provider.mu.Lock() + h.provider.configuration = config + h.provider.mu.Unlock() + + details, err := h.client.BooleanValueDetails(context.Background(), "root", false, + of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + require.True(t, details.Value) + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + require.Len(t, h.sink.events, 2) + keys := make([]string, 0, len(h.sink.events)) + for _, event := range h.sink.events { + keys = append(keys, event.Flag.Key) + } + require.ElementsMatch(t, []string{"dependency", "root"}, keys) + var metricCount int64 + for _, point := range findCounter(t, collectMetrics(t, h.reader)) { + metricCount += point.Value + } + require.Equal(t, int64(2), metricCount) + require.Len(t, h.sink.exposures, 2) +} + +func TestDependentFlags_InvalidConfiguredDepthIsNotReadForIndependentRoot(t *testing.T) { + logger := withLogLevel(t, log.LevelDebug) + config := dependencyTestConfig(dependencyTestFlag("root", "on", nil)) + require.NoError(t, json.Unmarshal([]byte(`{"maxDependencyDepth":null}`), &config.EvaluatorParams)) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.Equal(t, of.StaticReason, result.Reason) + require.True(t, result.Value.(bool)) + log.Flush() + require.Zero(t, logger.countContaining("maxDependencyDepth must be an integer from 0 through 255; using default 10")) +} + +func TestDependentFlags_InvalidConfiguredDepthIsNotReadBeforeDependencyCondition(t *testing.T) { + logger := withLogLevel(t, log.LevelDebug) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", + &condition{Attribute: "country", Operator: operatorOneOf, Value: []string{"US"}}, + dependencyCondition("dependency", operatorOneOf, "on"), + ), + ) + require.NoError(t, json.Unmarshal([]byte(`{"maxDependencyDepth":null}`), &config.EvaluatorParams)) + + result := evaluateConfiguredFlag(config, "root", false, map[string]any{"country": "CA"}, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.Equal(t, of.DefaultReason, result.Reason) + require.False(t, result.Value.(bool)) + require.Empty(t, result.DependencyEvaluations) + log.Flush() + require.Zero(t, logger.countContaining("maxDependencyDepth must be an integer from 0 through 255; using default 10")) +} + +func TestDependentFlags_MalformedOptionsObjectsLogAndFallBack(t *testing.T) { + for _, raw := range []string{`null`, `42`, `"future"`, `true`, `[]`} { + t.Run(raw, func(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + config.EvaluatorParams = json.RawMessage(raw) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + log.Flush() + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + require.Equal(t, 1, logger.countContaining("ERROR: openfeature: maxDependencyDepth must be an integer from 0 through 255; using default 10")) + }) + } +} + +func TestDependentFlags_ReturnedTelemetryIsDetachedAndPublisherCannotBreakEvaluation(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("leaf", "on", nil), + dependencyTestFlag("dependency", "on", dependencyCondition("leaf", operatorOneOf, "on")), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.True(t, result.Value.(bool)) + require.Len(t, result.DependencyEvaluations, 2) + var published []string + dropped := publishDependencyEvaluationBatch(result.DependencyEvaluations, func(record dependencyEvaluationRecord) { + published = append(published, record.FlagKey) + record.Result.Metadata[metadataAllocationKey] = "mutated" + record.Result.Value = false + if record.FlagKey == "dependency" { + panic("telemetry failure") + } + }) + require.Equal(t, int64(1), dropped) + require.Equal(t, []string{"dependency", "leaf"}, published, "one failed publisher call must not suppress later records") + require.True(t, result.DependencyEvaluations[1].Result.Value.(bool)) + require.Equal(t, "leaf-allocation", result.DependencyEvaluations[1].Result.Metadata[metadataAllocationKey]) + require.Equal(t, []string{"leaf", "dependency"}, dependencyExposureKeys(result)) + _, ok := result.Metadata[metadataDependencyExposuresKey].(string) + require.True(t, ok, "private dependency exposures must cross FlagMetadata as a scalar") +} + +func TestDependentFlags_PublisherPanicsAreCountedAndDoNotStopBatch(t *testing.T) { + records := make([]dependencyEvaluationRecord, 4) + for i := range records { + records[i].FlagKey = fmt.Sprintf("dependency-%d", i) + } + var published []string + dropped := publishDependencyEvaluationBatch(records, func(record dependencyEvaluationRecord) { + if record.FlagKey == "dependency-0" || record.FlagKey == "dependency-2" { + panic("private publisher value") + } + published = append(published, record.FlagKey) + }) + require.Equal(t, int64(2), dropped) + require.Equal(t, []string{"dependency-1", "dependency-3"}, published) +} + +// DD_LOGGING_RATE is initialized once by the log package, so use a subprocess +// to exercise the immediate Warn path with an application logger that panics. +func TestDependentFlags_PublisherPanicWarningContainsLoggerPanic(t *testing.T) { + if os.Getenv("DD_DEPENDENCY_PUBLISHER_PANIC_SUBPROCESS") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestDependentFlags_PublisherPanicWarningContainsLoggerPanic$", "-test.count=1") + cmd.Env = append(os.Environ(), "DD_DEPENDENCY_PUBLISHER_PANIC_SUBPROCESS=1", "DD_LOGGING_RATE=0") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + return + } + + withPanickingLogger(t, log.LevelWarn) + provider := new(DatadogProvider) + require.NotPanics(t, func() { + provider.reportDependencyPublisherPanics(1) + }) + require.True(t, provider.dependencyPublisherPanicWarned.Load()) +} + +func TestDependentFlags_PublisherPanicWarningIsSanitizedAndDeduplicated(t *testing.T) { + logger := withLogLevel(t, log.LevelWarn) + provider := &DatadogProvider{} + provider.reportDependencyPublisherPanics(1) + provider.reportDependencyPublisherPanics(2) + require.Equal(t, 1, logger.countContaining("dependency evaluation publisher panicked")) + require.Zero(t, logger.countContaining("private publisher value")) +} + +func TestDependentFlags_NestedJSONTelemetryIsDeeplyDetached(t *testing.T) { + configuredValue := map[string]any{ + "nested": map[string]any{"leaf": "original"}, + "any": []any{map[string]any{"leaf": "original"}, []any{"original"}}, + "strings": []string{"original", "stable"}, + } + expected := cloneTelemetryValue(configuredValue) + jsonFlag := func(key string) *flag { + flag := dependencyTestFlag(key, "json-on", nil) + flag.VariationType = valueTypeJSON + flag.Variations["json-on"].Value = configuredValue + return flag + } + config := dependencyTestConfig( + jsonFlag("json-a"), + jsonFlag("json-b"), + dependencyTestFlag("root", "on", + dependencyCondition("json-a", operatorOneOf, "json-on"), + dependencyCondition("json-b", operatorOneOf, "json-on")), + ) + + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.NoError(t, result.Error) + require.Len(t, result.DependencyEvaluations, 2) + var secondPublished any + publishDependencyEvaluationBatch(result.DependencyEvaluations, func(record dependencyEvaluationRecord) { + if record.FlagKey == "json-b" { + secondPublished = record.Result.Value + return + } + value := record.Result.Value.(map[string]any) + value["nested"].(map[string]any)["leaf"] = "mutated" + value["any"].([]any)[0].(map[string]any)["leaf"] = "mutated" + value["any"].([]any)[1].([]any)[0] = "mutated" + value["strings"].([]string)[0] = "mutated" + panic("publisher failure after mutation") + }) + + require.Equal(t, expected, result.DependencyEvaluations[0].Result.Value) + require.Equal(t, expected, result.DependencyEvaluations[1].Result.Value) + require.Equal(t, expected, secondPublished) + require.Equal(t, expected, config.Flags["json-a"].Variations["json-on"].Value) + require.Equal(t, expected, config.Flags["json-b"].Variations["json-on"].Value) +} + +func TestDependentFlags_DependencyErrorsAreDetached(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("parent", "on", dependencyCondition("missing", operatorOneOf, "on")), + dependencyTestFlag("root", "on", dependencyCondition("parent", operatorOneOf, "on")), + ) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + require.Error(t, result.Error) + require.Len(t, result.DependencyEvaluations, 2) + + rootErr := result.Error.(*dependencyGraphError) + parentErr := result.DependencyEvaluations[0].Result.Error.(*dependencyGraphError) + missingErr := result.DependencyEvaluations[1].Result.Error.(*dependencyGraphError) + require.NotSame(t, rootErr, parentErr) + require.NotSame(t, parentErr.cause, missingErr) + + missingErr.message = "publisher mutation" + parentErr.message = "publisher mutation" + require.NotEqual(t, "publisher mutation", rootErr.message) + require.NotEqual(t, "publisher mutation", parentErr.cause.(*dependencyGraphError).message) +} + +func TestDependentFlags_ParallelRootsKeepReturnedBatchesIndependent(t *testing.T) { + config := dependencyTestConfig( + dependencyTestFlag("dependency", "on", nil), + dependencyTestFlag("root", "on", dependencyCondition("dependency", operatorOneOf, "on")), + ) + const evaluations = 32 + var wg sync.WaitGroup + errs := make(chan error, evaluations) + for range evaluations { + wg.Go(func() { + result := evaluateConfiguredFlag(config, "root", false, nil, time.Now(), experimentationExclusion{}) + if result.Error != nil { + errs <- result.Error + return + } + if keys := dependencyEvaluationKeys(result); len(keys) != 1 || keys[0] != "dependency" { + errs <- errors.New("unexpected dependency evaluation batch") + return + } + result.DependencyEvaluations[0].Result.Metadata[metadataAllocationKey] = "caller mutation" + }) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } +} + +func TestDependentFlags_WideGraphDeduplicatesTelemetry(t *testing.T) { + const dependencyCount = 512 + flags := make([]*flag, 0, dependencyCount+1) + conditions := make([]*condition, 0, dependencyCount) + for i := range dependencyCount { + key := fmt.Sprintf("dependency-%d", i) + flags = append(flags, dependencyTestFlag(key, "on", nil)) + conditions = append(conditions, dependencyCondition(key, operatorOneOf, "on")) + } + root := dependencyTestFlag("root", "on", nil) + root.Allocations[0].Rules = []*rule{{Conditions: conditions}} + flags = append(flags, root) + + result := evaluateConfiguredFlag(dependencyTestConfig(flags...), "root", false, nil, time.Now(), experimentationExclusion{}) + + require.NoError(t, result.Error) + require.Len(t, result.DependencyEvaluations, dependencyCount) + encoded, ok := result.Metadata[metadataDependencyExposuresKey].(string) + require.True(t, ok) + exposures := decodeDependencyExposureCandidates(encoded) + require.Len(t, exposures, dependencyCount) + for i := range dependencyCount { + key := fmt.Sprintf("dependency-%d", i) + require.Equal(t, key, result.DependencyEvaluations[i].FlagKey) + require.Equal(t, key, exposures[i].FlagKey) + } +} + +func BenchmarkDependentFlags_WideGraph(b *testing.B) { + const dependencyCount = 512 + flags := make([]*flag, 0, dependencyCount+1) + conditions := make([]*condition, 0, dependencyCount) + for i := range dependencyCount { + key := fmt.Sprintf("dependency-%d", i) + flags = append(flags, dependencyTestFlag(key, "on", nil)) + conditions = append(conditions, dependencyCondition(key, operatorOneOf, "on")) + } + root := dependencyTestFlag("root", "on", nil) + root.Allocations[0].Rules = []*rule{{Conditions: conditions}} + flags = append(flags, root) + config := dependencyTestConfig(flags...) + now := time.Now() + + b.ReportAllocs() + b.ResetTimer() + for range b.N { + result := evaluateConfiguredFlag(config, "root", false, nil, now, experimentationExclusion{}) + exposures := decodeDependencyExposureCandidates(result.Metadata[metadataDependencyExposuresKey].(string)) + if result.Error != nil || len(result.DependencyEvaluations) != dependencyCount || len(exposures) != dependencyCount { + b.Fatalf("unexpected wide-graph result: error=%v evaluations=%d exposures=%d", result.Error, len(result.DependencyEvaluations), len(exposures)) + } + } +} + +func TestDependentFlags_ProviderTelemetryAndExposureIntegration(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("leaf", "leaf-on", nil), + dependencyTestFlag("middle", "middle-on", dependencyCondition("leaf", operatorOneOf, "leaf-on")), + dependencyTestFlag("root", "root-on", dependencyCondition("middle", operatorOneOf, "middle-on")), + ) + h.provider.mu.Unlock() + + details, err := h.client.BooleanValueDetails(context.Background(), "root", false, + of.NewEvaluationContext("subject", map[string]any{"tier": "paid"})) + require.NoError(t, err) + require.True(t, details.Value) + + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + require.Len(t, h.sink.events, 3) + evaluationKeys := make([]string, 0, len(h.sink.events)) + for _, event := range h.sink.events { + evaluationKeys = append(evaluationKeys, event.Flag.Key) + } + require.ElementsMatch(t, []string{"leaf", "middle", "root"}, evaluationKeys) + var metricCount int64 + for _, point := range findCounter(t, collectMetrics(t, h.reader)) { + metricCount += point.Value + } + require.Equal(t, int64(3), metricCount) + require.Len(t, h.sink.exposures, 3) + exposureKeys := make([]string, 0, len(h.sink.exposures)) + for _, exposure := range h.sink.exposures { + exposureKeys = append(exposureKeys, exposure.Flag.Key) + } + require.Equal(t, []string{"leaf", "middle", "root"}, exposureKeys) +} + +func TestDependentFlags_ConsentIsSnapshottedAtDependencyEvaluation(t *testing.T) { + for _, consent := range []bool{false, true} { + t.Run(fmt.Sprintf("consent_%t", consent), func(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + config := dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + config.ObserveFullEvaluationData = consent + h.provider.mu.Lock() + h.provider.configuration = config + h.provider.mu.Unlock() + + _, err := h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("private-subject", map[string]any{"private": "value"})) + require.NoError(t, err) + + // A later configuration must not change the consent already stamped on either + // the returned prerequisite batch or the root event waiting to be drained. + replacement := dependencyTestConfig() + replacement.ObserveFullEvaluationData = !consent + h.provider.mu.Lock() + h.provider.configuration = replacement + h.provider.mu.Unlock() + h.provider.flagEvalLoggingWriter.drainAndFlush() + require.Len(t, h.sink.events, 2) + for _, event := range h.sink.events { + if consent { + require.Equal(t, "private-subject", event.TargetingKey) + require.NotNil(t, event.Context) + } else { + require.NotEqual(t, "private-subject", event.TargetingKey) + require.Nil(t, event.Context) + } + } + }) + } +} + +func TestDependentFlags_EnvironmentIdentityIsSnapshottedBeforeDrain(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + want := environment{ID: testEnvironmentID, Name: "Production"} + config := dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + config.Environment = want + h.provider.setConfiguration(config) + + _, err := h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + + // Both events already carry the evaluated configuration's identity. Replacing + // the provider configuration before the writer drains must not relabel either. + replacement := dependencyTestConfig() + replacement.Environment = environment{ID: "22222222-2222-4222-8222-222222222222", Name: "Replacement"} + h.provider.setConfiguration(replacement) + h.provider.flagEvalLoggingWriter.stop() + require.Len(t, h.sink.events, 2) + for _, event := range h.sink.events { + require.NotNil(t, event.Environment) + require.Equal(t, want, *event.Environment, "flag %s", event.Flag.Key) + } +} + +func TestDependentFlags_EnvironmentIdentityRemainsCoherentDuringConcurrentRefresh(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + identities := []environment{ + {ID: testEnvironmentID, Name: "Production"}, + {ID: "22222222-2222-4222-8222-222222222222", Name: "Renamed"}, + {Name: "Legacy"}, + } + configs := make([]*universalFlagsConfiguration, len(identities)) + for i, identity := range identities { + configs[i] = dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + configs[i].Environment = identity + } + h.provider.setConfiguration(configs[0]) + + const workers = 8 + const evaluationsPerWorker = 50 + start := make(chan struct{}) + errCh := make(chan error, workers*evaluationsPerWorker) + var wg sync.WaitGroup + wg.Go(func() { + <-start + for i := range workers * evaluationsPerWorker { + h.provider.setConfiguration(configs[i%len(configs)]) + } + }) + for range workers { + wg.Go(func() { + <-start + for range evaluationsPerWorker { + value, err := h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("subject", nil)) + if err != nil { + errCh <- err + continue + } + if !value { + errCh <- errors.New("root evaluated false") + } + } + }) + } + close(start) + wg.Wait() + close(errCh) + for err := range errCh { + require.NoError(t, err) + } + + // Join the background worker before asserting exact concurrent counts. + h.provider.flagEvalLoggingWriter.stop() + counts := make(map[environment]map[string]int64) + for _, event := range h.sink.events { + require.NotNil(t, event.Environment, "flag %s", event.Flag.Key) + byFlag := counts[*event.Environment] + if byFlag == nil { + byFlag = make(map[string]int64) + counts[*event.Environment] = byFlag + } + byFlag[event.Flag.Key] += event.EvaluationCount + } + var roots, dependencies int64 + for identity, byFlag := range counts { + require.Contains(t, identities, identity) + require.Equal(t, byFlag["root"], byFlag["dependency"], "identity %+v", identity) + roots += byFlag["root"] + dependencies += byFlag["dependency"] + } + require.Equal(t, int64(workers*evaluationsPerWorker), roots) + require.Equal(t, roots, dependencies) +} + +func TestDependentFlags_PerPrerequisiteDoLogAndRollback(t *testing.T) { + for _, dependencyDoLog := range []bool{false, true} { + for _, rootDoLog := range []bool{false, true} { + name := fmt.Sprintf("dependency_%t_root_%t", dependencyDoLog, rootDoLog) + t.Run(name, func(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + dependency := dependencyTestFlag("dependency", "dependency-on", nil) + dependency.Allocations[0].DoLog = new(dependencyDoLog) + root := dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")) + root.Allocations[0].DoLog = new(rootDoLog) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig(dependency, root) + h.provider.mu.Unlock() + + _, err := h.client.BooleanValue(context.Background(), "root", false, of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + h.provider.exposureWriter.flush() + keys := make([]string, 0, len(h.sink.exposures)) + for _, exposure := range h.sink.exposures { + keys = append(keys, exposure.Flag.Key) + } + want := make([]string, 0, 2) + if dependencyDoLog { + want = append(want, "dependency") + } + if rootDoLog { + want = append(want, "root") + } + require.Equal(t, want, keys) + + h.sink.exposures = nil + root.Allocations[0].Rules[0].Conditions = append(root.Allocations[0].Rules[0].Conditions, + &condition{Attribute: "tier", Operator: operatorOneOf, Value: []string{"paid"}}) + _, err = h.client.BooleanValue(context.Background(), "root", false, + of.NewEvaluationContext("other-subject", map[string]any{"tier": "free"})) + require.NoError(t, err) + h.provider.exposureWriter.flush() + require.Empty(t, h.sink.exposures, "a rejected root path rolls back every prerequisite exposure") + }) + } + } +} + +func TestDependentFlags_MalformedPrerequisitePropagation(t *testing.T) { + for _, transitive := range []bool{false, true} { + name := "direct" + if transitive { + name = "transitive" + } + t.Run(name, func(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + rootDependency := "malformed" + flags := []*flag{dependencyTestFlag("root", "root-on", nil)} + if transitive { + rootDependency = "parent" + flags = append(flags, dependencyTestFlag("parent", "parent-on", dependencyCondition("malformed", operatorOneOf, "on"))) + } + flags[0].Allocations[0].Rules = []*rule{{Conditions: []*condition{dependencyCondition(rootDependency, operatorOneOf, "on")}}} + config := dependencyTestConfig(flags...) + config.invalidFlags["malformed"] = fmt.Errorf("%w: malformed prerequisite", errParseError) + h.provider.mu.Lock() + h.provider.configuration = config + h.provider.mu.Unlock() + + details, err := h.client.BooleanValueDetails(context.Background(), "root", false, of.NewEvaluationContext("subject", nil)) + require.Error(t, err) + require.Equal(t, of.GeneralCode, details.ErrorCode) + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + wantCodes := map[string]string{"malformed": string(of.ParseErrorCode), "root": string(of.GeneralCode)} + if transitive { + wantCodes["parent"] = string(of.GeneralCode) + } + require.Len(t, h.sink.events, len(wantCodes)) + for _, event := range h.sink.events { + require.NotNil(t, event.Error) + require.Equal(t, wantCodes[event.Flag.Key], event.Error.Message) + } + require.Empty(t, h.sink.exposures) + }) + } +} + +func TestDependentFlags_PublicObjectTypeMismatchDoesNotTraverseDependencies(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")), + ) + h.provider.mu.Unlock() + + defaultValue := map[string]any{"fallback": true} + details, err := h.client.ObjectValueDetails(context.Background(), "root", defaultValue, + of.NewEvaluationContext("subject", nil)) + require.Error(t, err) + require.Equal(t, defaultValue, details.Value) + require.Equal(t, of.TypeMismatchCode, details.ErrorCode) + + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + require.Len(t, h.sink.events, 1) + require.Equal(t, "root", h.sink.events[0].Flag.Key) + require.Empty(t, h.sink.exposures) +} + +func TestDependentFlags_IntegerFlagCanBeEvaluatedAsFloat(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + root := dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")) + root.VariationType = valueTypeInteger + root.Variations["root-on"].Value = int64(7) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + root, + ) + h.provider.mu.Unlock() + + details, err := h.client.FloatValueDetails(context.Background(), "root", 0, + of.NewEvaluationContext("subject", nil)) + require.NoError(t, err) + require.Equal(t, 7.0, details.Value) + require.Equal(t, of.TargetingMatchReason, details.Reason) + + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + require.Len(t, h.sink.events, 2) + require.ElementsMatch(t, []string{"dependency", "root"}, []string{ + h.sink.events[0].Flag.Key, + h.sink.events[1].Flag.Key, + }) + require.Len(t, h.sink.exposures, 2) +} + +func TestDependentFlags_PublicNumericReadsRequireLosslessConversion(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + makeFlag := func(key string, flagType valueType, value any) *flag { + configured := dependencyTestFlag(key, "selected", nil) + configured.VariationType = flagType + configured.Variations["selected"].Value = value + return configured + } + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + makeFlag("whole-number", valueTypeNumeric, float64(6)), + makeFlag("fraction", valueTypeNumeric, 1.5), + makeFlag("too-large-number", valueTypeNumeric, 1e300), + makeFlag("exact-integer", valueTypeInteger, int64(5)), + makeFlag("lossy-integer", valueTypeInteger, int64(9007199254740993)), + ) + h.provider.mu.Unlock() + + ctx := context.Background() + evalCtx := of.NewEvaluationContext("subject", nil) + + integer, err := h.client.IntValueDetails(ctx, "whole-number", -1, evalCtx) + require.NoError(t, err) + require.Equal(t, int64(6), integer.Value) + + for _, key := range []string{"fraction", "too-large-number"} { + integer, err = h.client.IntValueDetails(ctx, key, -1, evalCtx) + require.Error(t, err) + require.Equal(t, int64(-1), integer.Value) + require.Equal(t, of.TypeMismatchCode, integer.ErrorCode) + } + + number, err := h.client.FloatValueDetails(ctx, "exact-integer", -1, evalCtx) + require.NoError(t, err) + require.Equal(t, 5.0, number.Value) + + number, err = h.client.FloatValueDetails(ctx, "lossy-integer", -1, evalCtx) + require.Error(t, err) + require.Equal(t, -1.0, number.Value) + require.Equal(t, of.TypeMismatchCode, number.ErrorCode) +} + +func TestDependentFlags_InvalidRootActivationPrecedesTypeMismatch(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{ExperimentationOptOutMode: ExperimentationOptOutFutureExperimentsOnly}) + root := dependencyTestFlag("root", "root-on", dependencyCondition("dependency", operatorOneOf, "dependency-on")) + root.invalidActivation = true + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("dependency", "dependency-on", nil), + root, + ) + h.provider.mu.Unlock() + + details, err := h.client.StringValueDetails(context.Background(), "root", "fallback", + of.NewEvaluationContext("subject", map[string]any{ + experimentationOptOutAtAttribute: experimentOptOutTestTime, + })) + require.Error(t, err) + require.Equal(t, "fallback", details.Value) + require.Equal(t, of.ParseErrorCode, details.ErrorCode) + + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + require.Len(t, h.sink.events, 1) + require.Equal(t, "root", h.sink.events[0].Flag.Key) + require.Empty(t, h.sink.exposures) +} + +func TestDependentFlags_OptOutSuppressesDependencyErrorTelemetry(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{EnableEvaluationTelemetryOptOutParameter: new(true)}) + h.provider.mu.Lock() + h.provider.configuration = dependencyTestConfig( + dependencyTestFlag("root", "on", dependencyCondition("missing", operatorOneOf, "on")), + ) + h.provider.mu.Unlock() + + _, err := h.client.BooleanValueDetails(context.Background(), "root", false, + of.NewEvaluationContext("subject", map[string]any{optOutTestParameter: true})) + require.Error(t, err) + h.provider.flagEvalLoggingWriter.drainAndFlush() + require.Empty(t, h.sink.events) + var metricCount int64 + for _, point := range findCounter(t, collectMetrics(t, h.reader)) { + metricCount += point.Value + } + require.Zero(t, metricCount) +} + +func dependencyTestConfig(flags ...*flag) *universalFlagsConfiguration { + config := &universalFlagsConfiguration{Flags: make(map[string]*flag, len(flags)), invalidFlags: make(map[string]error)} + for _, flag := range flags { + config.Flags[flag.Key] = flag + } + return config +} + +func TestIndependentEvaluationDoesNotCreateDependencyTrace(t *testing.T) { + config := dependencyTestConfig(&flag{ + Key: "root", Enabled: true, VariationType: valueTypeBoolean, + Variations: map[string]*variant{}, + }) + result := evaluateConfiguredFlag(config, "root", false, nil, time.Time{}, experimentationExclusion{}) + require.NoError(t, result.Error) + require.Empty(t, result.DependencyEvaluations) + require.Empty(t, dependencyExposureKeys(result)) +} + +func BenchmarkIndependentEvaluationWithoutDependencyTrace(b *testing.B) { + config := dependencyTestConfig(&flag{ + Key: "root", Enabled: true, VariationType: valueTypeBoolean, + Variations: map[string]*variant{}, + }) + b.ReportAllocs() + for b.Loop() { + result := evaluateConfiguredFlag(config, "root", false, nil, time.Time{}, experimentationExclusion{}) + if result.Error != nil || len(result.DependencyEvaluations) != 0 { + b.Fatalf("unexpected independent result: error=%v dependencyEvaluations=%d", result.Error, len(result.DependencyEvaluations)) + } + } +} + +func dependencyTestConfigWithDepth(depth int, flags ...*flag) *universalFlagsConfiguration { + config := dependencyTestConfig(flags...) + config.EvaluatorParams = json.RawMessage(fmt.Sprintf(`{"maxDependencyDepth":%d}`, depth)) + return config +} + +func dependencyChainConfig(edges int) *universalFlagsConfiguration { + flags := make([]*flag, 0, edges+1) + for depth := edges; depth >= 0; depth-- { + key := "root" + if depth > 0 { + key = fmt.Sprintf("dependency-%d", depth) + } + if depth == edges { + flags = append(flags, dependencyTestFlag(key, "on", nil)) + continue + } + next := fmt.Sprintf("dependency-%d", depth+1) + flags = append(flags, dependencyTestFlag(key, "on", dependencyCondition(next, operatorOneOf, "on"))) + } + return dependencyTestConfig(flags...) +} + +func evaluateConfiguredFlagWithCounter(config *universalFlagsConfiguration, flagKey string, onEvaluate func(string)) evaluationResult { + now := time.Now() + session := &dependencyEvaluationSession{ + config: config, + now: now, + maxDepth: configuredMaxDependencyDepth(config), + active: map[string]bool{flagKey: true}, + memo: make(map[string]memoizedDependency), + exposureKeys: make(map[string]struct{}), + evaluationIndexes: make(map[string]int), + onEvaluate: onEvaluate, + } + result := evaluateConfiguredFlagOnce(config, flagKey, false, nil, now, experimentationExclusion{}, + dependencyResolverAtDepth{session: session, depth: 1}) + result.DependencyEvaluations = cloneDependencyEvaluationRecords(session.evaluations) + if result.Error == nil && len(session.exposures) > 0 { + if result.Metadata == nil { + result.Metadata = make(map[string]any, 1) + } + result.Metadata[metadataDependencyExposuresKey] = encodeDependencyExposureCandidates(session.exposures) + } + return result +} + +func dependencyTestFlag(key, variantKey string, conditions ...*condition) *flag { + rules := []*rule(nil) + if len(conditions) > 0 && conditions[0] != nil { + rules = []*rule{{Conditions: conditions}} + } + return &flag{ + Key: key, Enabled: true, VariationType: valueTypeBoolean, + Variations: map[string]*variant{variantKey: {Key: variantKey, Value: true}}, + Allocations: []*allocation{{ + Key: key + "-allocation", Rules: rules, + Splits: []*split{{VariationKey: variantKey, Shards: []*shard{}}}, + }}, + } +} + +func dependencyCondition(key string, operator conditionOperator, variants ...string) *condition { + return &condition{FlagEvaluation: &flagEvaluation{Key: key}, Operator: operator, Value: variants} +} + +func dependencyExposureKeys(result evaluationResult) []string { + encoded, _ := result.Metadata[metadataDependencyExposuresKey].(string) + candidates := decodeDependencyExposureCandidates(encoded) + keys := make([]string, 0, len(candidates)) + for _, candidate := range candidates { + keys = append(keys, candidate.FlagKey) + } + return keys +} + +func dependencyEvaluationKeys(result evaluationResult) []string { + keys := make([]string, 0, len(result.DependencyEvaluations)) + for _, evaluation := range result.DependencyEvaluations { + keys = append(keys, evaluation.FlagKey) + } + return keys +} + +func dependencyJSONConfiguration(condition string) string { + return `{"format":"SERVER","flags":{"root":{"key":"root","enabled":true,"variationType":"BOOLEAN",` + + `"variations":{"on":{"key":"on","value":true}},"allocations":[{"key":"allocation",` + + `"rules":[{"conditions":[` + condition + `]}],"splits":[{"variationKey":"on","shards":[]}]}` + + `]}}}` +} diff --git a/openfeature/evaluator.go b/openfeature/evaluator.go index 84aae2cb220..5f7a386d103 100644 --- a/openfeature/evaluator.go +++ b/openfeature/evaluator.go @@ -8,6 +8,7 @@ package openfeature import ( "crypto/md5" "encoding/binary" + "encoding/json" "fmt" "maps" "math" @@ -35,9 +36,16 @@ type evaluationResult struct { Error error // Metadata contains additional evaluation metadata for hooks Metadata map[string]any + // DependencyEvaluations contains each reached prerequisite exactly once. It is + // populated after the dependency graph finishes and is not exposed as flag + // metadata. + DependencyEvaluations []dependencyEvaluationRecord } const ( + defaultMaxDependencyDepth = 10 + maxMaxDependencyDepth = 255 + metadataAllocationKey = "dd.allocation.key" metadataDoLogKey = "__dd_do_log" metadataSplitSerialIDKey = "__dd_split_serial_id" @@ -59,14 +67,69 @@ const ( // cross-SDK contract key (confirmed in the PII RFC and the Java pilot); every SDK stamps and // reads consent under this exact key so the same identifier appears across SDK sources. metadataObserveFullEvaluationDataKey = "observe_full_evaluation_data" + metadataDependencyExposuresKey = "__dd_dependency_exposures" ) +type dependencyEvaluationRecord struct { + FlagKey string + FlagType valueType + DefaultValue any + Result evaluationResult +} + +type dependencyExposureCandidate struct { + FlagKey string + Result evaluationResult +} + +// dependencyExposureSnapshot is the scalar-safe representation carried across +// the public OpenFeature FlagMetadata boundary. The evaluator keeps the richer +// candidates private and exposes only the encoded JSON string. +type dependencyExposureSnapshot struct { + FlagKey string `json:"flagKey"` + VariantKey string `json:"variantKey"` + Reason of.Reason `json:"reason"` + AllocationKey string `json:"allocationKey,omitempty"` + DoLog bool `json:"doLog"` + SerialID *uint32 `json:"serialId,omitempty"` + FeaturesKey string `json:"featuresKey,omitempty"` + HookFeatures string `json:"hookFeatures,omitempty"` + CacheHit *bool `json:"cacheHit,omitempty"` +} + +type dependencyGraphError struct { + flagKey string + code of.ErrorCode + message string + cause error +} + +func (e *dependencyGraphError) Error() string { return e.message } +func (e *dependencyGraphError) Unwrap() error { return e.cause } + // evaluateFlag evaluates a feature flag with the given context. The caller supplies the // evaluation time (now) so a single timestamp is shared between the allocation time-window // checks here and the EVP eval-time metadata stamped by DatadogProvider.evaluate — avoiding a // second time.Now() on the evaluation path. // It returns the variant value, reason, and any error that occurred. func evaluateFlag(flag *flag, defaultValue any, context map[string]any, now time.Time, exclusion experimentationExclusion) evaluationResult { + return evaluateFlagWithResolver(flag, defaultValue, context, now, exclusion, nil) +} + +type dependencyResolver interface { + Resolve(*flagEvaluation) (string, error) + Checkpoint() dependencyCheckpoint + Rollback(dependencyCheckpoint) +} + +func evaluateFlagWithResolver( + flag *flag, + defaultValue any, + context map[string]any, + now time.Time, + exclusion experimentationExclusion, + resolver dependencyResolver, +) evaluationResult { if flag == nil { return evaluationResult{Value: defaultValue, Reason: of.DefaultReason} } @@ -84,8 +147,18 @@ func evaluateFlag(flag *flag, defaultValue any, context map[string]any, now time if exclusion.active() && exclusion.excludes(allocation) { continue } - split, matched, err := evaluateAllocation(allocation, context, now) + checkpoint := checkpointDependency(resolver) + split, matched, err := evaluateAllocationWithResolver(allocation, context, now, resolver) if err != nil { + rollbackDependency(resolver, checkpoint) + if graphErr, ok := err.(*dependencyGraphError); ok && graphErr.flagKey != flag.Key { + err = &dependencyGraphError{ + flagKey: flag.Key, + code: of.GeneralCode, + message: fmt.Sprintf("prerequisite flag %q failed: %s", graphErr.flagKey, graphErr.message), + cause: graphErr, + } + } return evaluationResult{ Value: defaultValue, Reason: of.ErrorReason, @@ -162,6 +235,7 @@ func evaluateFlag(flag *flag, defaultValue any, context map[string]any, now time Metadata: metadata, } } + rollbackDependency(resolver, checkpoint) } // No allocations matched, return default @@ -180,6 +254,71 @@ func evaluateConfiguredFlag( context map[string]any, now time.Time, exclusion experimentationExclusion, +) evaluationResult { + flag, exists := config.Flags[flagKey] + return evaluateConfiguredFlagLookedUp(config, flagKey, flag, exists, defaultValue, context, now, exclusion) +} + +func evaluateConfiguredFlagLookedUp( + config *universalFlagsConfiguration, + flagKey string, + flag *flag, + exists bool, + defaultValue any, + context map[string]any, + now time.Time, + exclusion experimentationExclusion, +) evaluationResult { + return evaluateConfiguredFlagLookedUpWithState(config, flagKey, flag, exists, defaultValue, context, now, exclusion, nil) +} + +func evaluateConfiguredFlagLookedUpWithState( + config *universalFlagsConfiguration, + flagKey string, + flag *flag, + exists bool, + defaultValue any, + context map[string]any, + now time.Time, + exclusion experimentationExclusion, + evaluatorState *dependencyEvaluatorState, +) evaluationResult { + if !exists || !flag.Enabled { + if exists && !(exclusion.mode == ExperimentationOptOutFutureExperimentsOnly && flag.invalidActivation) { + return evaluateFlagWithResolver(flag, defaultValue, context, now, exclusion, nil) + } + return evaluateConfiguredFlagOnce(config, flagKey, defaultValue, context, now, exclusion, nil) + } + resolver := &lazyDependencyResolver{ + config: config, + rootFlagKey: flagKey, + context: context, + now: now, + exclusion: exclusion, + evaluatorState: evaluatorState, + } + result := evaluateConfiguredFlagOnce(config, flagKey, defaultValue, context, now, exclusion, resolver) + if resolver.session == nil { + return result + } + result.DependencyEvaluations = cloneDependencyEvaluationRecords(resolver.session.evaluations) + if result.Error == nil && len(resolver.session.exposures) > 0 { + if result.Metadata == nil { + result.Metadata = make(map[string]any, 1) + } + result.Metadata[metadataDependencyExposuresKey] = encodeDependencyExposureCandidates(resolver.session.exposures) + } + return result +} + +func evaluateConfiguredFlagOnce( + config *universalFlagsConfiguration, + flagKey string, + defaultValue any, + context map[string]any, + now time.Time, + exclusion experimentationExclusion, + resolver dependencyResolver, ) evaluationResult { flag, exists := config.Flags[flagKey] if exists { @@ -190,7 +329,7 @@ func evaluateConfiguredFlag( Error: fmt.Errorf("%w: invalid randomizationActivatedAt for flag %q", errParseError, flagKey), } } - return evaluateFlag(flag, defaultValue, context, now, exclusion) + return evaluateFlagWithResolver(flag, defaultValue, context, now, exclusion, resolver) } if configErr, invalid := config.invalidFlags[flagKey]; invalid { return evaluationResult{ @@ -206,8 +345,77 @@ func evaluateConfiguredFlag( } } +func configuredMaxDependencyDepth(config *universalFlagsConfiguration) int { + depth, invalid := parseConfiguredMaxDependencyDepth(config) + if invalid { + logInvalidMaxDependencyDepth() + } + return depth +} + +func parseConfiguredMaxDependencyDepth(config *universalFlagsConfiguration) (depth int, invalid bool) { + if len(config.EvaluatorParams) == 0 { + return defaultMaxDependencyDepth, false + } + + var params map[string]json.RawMessage + if err := json.Unmarshal(config.EvaluatorParams, ¶ms); err != nil || params == nil { + return defaultMaxDependencyDepth, true + } + configuredDepth, present := params["maxDependencyDepth"] + if !present { + return defaultMaxDependencyDepth, false + } + depth, valid := parseMaxDependencyDepth(configuredDepth) + if !valid { + return defaultMaxDependencyDepth, true + } + return depth, false +} + +func logInvalidMaxDependencyDepth() { + containLoggerPanic(func() { + log.Error("openfeature: maxDependencyDepth must be an integer from 0 through 255; using default %d", defaultMaxDependencyDepth) //errtrack:ignore malformed customer configuration + }) +} + +// dependencyEvaluatorState owns evaluator-option state outside the immutable +// UFC data. A provider replaces it with each accepted configuration, and the +// first reached prerequisite resolves the option for all evaluations that use +// that configuration. +type dependencyEvaluatorState struct { + maxDependencyDepthOnce sync.Once + maxDependencyDepth int +} + +func (s *dependencyEvaluatorState) resolveMaxDependencyDepth(config *universalFlagsConfiguration) int { + if s == nil { + return configuredMaxDependencyDepth(config) + } + initialized, invalid := false, false + s.maxDependencyDepthOnce.Do(func() { + initialized = true + s.maxDependencyDepth, invalid = parseConfiguredMaxDependencyDepth(config) + }) + if initialized && invalid { + // Application loggers may evaluate through this same state. Emit only + // after Once is complete so that re-entry observes the cached depth. + logInvalidMaxDependencyDepth() + } + return s.maxDependencyDepth +} + // evaluateAllocation evaluates an allocation and returns the matching split if any. func evaluateAllocation(allocation *allocation, context map[string]any, currentTime time.Time) (*split, bool, error) { + return evaluateAllocationWithResolver(allocation, context, currentTime, nil) +} + +func evaluateAllocationWithResolver( + allocation *allocation, + context map[string]any, + currentTime time.Time, + resolver dependencyResolver, +) (*split, bool, error) { // Check time window constraints if allocation.StartAt != nil && currentTime.Before(*allocation.StartAt) { return nil, false, nil @@ -220,10 +428,17 @@ func evaluateAllocation(allocation *allocation, context map[string]any, currentT // If there are no rules, the allocation matches everyone ruleMatched := len(allocation.Rules) == 0 for _, rule := range allocation.Rules { - if evaluateRule(rule, context) { + checkpoint := checkpointDependency(resolver) + matched, err := evaluateRuleWithResolver(rule, context, resolver) + if err != nil { + rollbackDependency(resolver, checkpoint) + return nil, false, err + } + if matched { ruleMatched = true break } + rollbackDependency(resolver, checkpoint) } if !ruleMatched { @@ -246,16 +461,52 @@ func evaluateAllocation(allocation *allocation, context map[string]any, currentT // evaluateRule evaluates a rule by checking all conditions (AND logic). func evaluateRule(rule *rule, context map[string]any) bool { + matched, _ := evaluateRuleWithResolver(rule, context, nil) + return matched +} + +func evaluateRuleWithResolver(rule *rule, context map[string]any, resolver dependencyResolver) (bool, error) { for _, condition := range rule.Conditions { - if !evaluateCondition(condition, context) { - return false + matched, err := evaluateConditionWithResolver(condition, context, resolver) + if err != nil { + return false, err + } + if !matched { + return false, nil } } - return true + return true, nil } // evaluateCondition evaluates a single condition against the context. func evaluateCondition(condition *condition, context map[string]any) bool { + matched, _ := evaluateConditionWithResolver(condition, context, nil) + return matched +} + +func evaluateConditionWithResolver( + condition *condition, + context map[string]any, + resolver dependencyResolver, +) (bool, error) { + if condition.FlagEvaluation != nil { + if resolver == nil { + return false, nil + } + variantKey, err := resolver.Resolve(condition.FlagEvaluation) + if err != nil { + return false, err + } + switch condition.Operator { + case operatorOneOf: + return isOneOf(variantKey, condition.Value), nil + case operatorNotOneOf: + return !isOneOf(variantKey, condition.Value), nil + default: + return false, nil + } + } + attributeValue, exists := context[condition.Attribute] // Special handling for "id" attribute: if not explicitly provided, use targeting key @@ -271,30 +522,527 @@ func evaluateCondition(condition *condition, context map[string]any) bool { isNull := !exists || attributeValue == nil expectedNull, ok := condition.Value.(bool) if !ok { - return false + return false, nil } - return isNull == expectedNull + return isNull == expectedNull, nil } // For all other operators, attribute must exist if !exists || attributeValue == nil { - return false + return false, nil } switch condition.Operator { case operatorMatches: - return matchesRegex(attributeValue, condition.Value) + return matchesRegex(attributeValue, condition.Value), nil case operatorNotMatches: - return !matchesRegex(attributeValue, condition.Value) + return !matchesRegex(attributeValue, condition.Value), nil case operatorOneOf: - return isOneOf(attributeValue, condition.Value) + return isOneOf(attributeValue, condition.Value), nil case operatorNotOneOf: - return !isOneOf(attributeValue, condition.Value) + return !isOneOf(attributeValue, condition.Value), nil case operatorGT, operatorGTE, operatorLT, operatorLTE: - return evaluateNumericCondition(attributeValue, condition.Value, condition.Operator) + return evaluateNumericCondition(attributeValue, condition.Value, condition.Operator), nil case operatorSemverEQ, operatorSemverNEQ, operatorSemverLT, operatorSemverLTE, operatorSemverGT, operatorSemverGTE: - return evaluateSemverCondition(attributeValue, condition.semverComparand, condition.Operator) + return evaluateSemverCondition(attributeValue, condition.semverComparand, condition.Operator), nil + default: + return false, nil + } +} + +type dependencyCheckpoint struct { + exposureCount int + frameExposureCount int + hasFrame bool +} + +type dependencyFrame struct { + maxReachedDepth int + exposureTrace []dependencyExposureCandidate + exposureKeys map[string]struct{} +} + +type memoizedDependency struct { + result evaluationResult + descendantDepth int + exposureTrace []dependencyExposureCandidate +} + +type dependencyEvaluationSession struct { + config *universalFlagsConfiguration + context map[string]any + now time.Time + exclusion experimentationExclusion + maxDepth int + active map[string]bool + memo map[string]memoizedDependency + frames []*dependencyFrame + exposures []dependencyExposureCandidate + exposureKeys map[string]struct{} + evaluations []dependencyEvaluationRecord + evaluationIndexes map[string]int + // onEvaluate is a test seam for proving memoization deduplicates actual + // prerequisite evaluation, not merely the returned telemetry. + onEvaluate func(string) +} + +// lazyDependencyResolver keeps the dependency session and all of its maps off +// the ordinary evaluation path until a flagEvaluation condition is reached. +type lazyDependencyResolver struct { + config *universalFlagsConfiguration + rootFlagKey string + context map[string]any + now time.Time + exclusion experimentationExclusion + evaluatorState *dependencyEvaluatorState + session *dependencyEvaluationSession +} + +func (r *lazyDependencyResolver) Resolve(ref *flagEvaluation) (string, error) { + if r.session == nil { + r.session = &dependencyEvaluationSession{ + config: r.config, + context: r.context, + now: r.now, + exclusion: r.exclusion, + maxDepth: r.evaluatorState.resolveMaxDependencyDepth(r.config), + active: map[string]bool{r.rootFlagKey: true}, + memo: make(map[string]memoizedDependency), + exposureKeys: make(map[string]struct{}), + evaluationIndexes: make(map[string]int), + } + } + return r.session.Resolve(ref) +} + +func (r *lazyDependencyResolver) Checkpoint() dependencyCheckpoint { + if r.session == nil { + return dependencyCheckpoint{} + } + return r.session.Checkpoint() +} + +func (r *lazyDependencyResolver) Rollback(checkpoint dependencyCheckpoint) { + if r.session != nil { + r.session.Rollback(checkpoint) + } +} + +func checkpointDependency(resolver dependencyResolver) dependencyCheckpoint { + if resolver == nil { + return dependencyCheckpoint{} + } + return resolver.Checkpoint() +} + +func rollbackDependency(resolver dependencyResolver, checkpoint dependencyCheckpoint) { + if resolver != nil { + resolver.Rollback(checkpoint) + } +} + +func (s *dependencyEvaluationSession) Checkpoint() dependencyCheckpoint { + checkpoint := dependencyCheckpoint{exposureCount: len(s.exposures)} + if len(s.frames) > 0 { + checkpoint.hasFrame = true + checkpoint.frameExposureCount = len(s.frames[len(s.frames)-1].exposureTrace) + } + return checkpoint +} + +func (s *dependencyEvaluationSession) Rollback(checkpoint dependencyCheckpoint) { + if checkpoint.exposureCount <= len(s.exposures) { + truncateExposureTrace(&s.exposures, s.exposureKeys, checkpoint.exposureCount) + } + if checkpoint.hasFrame && len(s.frames) > 0 { + frame := s.frames[len(s.frames)-1] + if checkpoint.frameExposureCount <= len(frame.exposureTrace) { + truncateExposureTrace(&frame.exposureTrace, frame.exposureKeys, checkpoint.frameExposureCount) + } + } +} + +func (s *dependencyEvaluationSession) Resolve(ref *flagEvaluation) (string, error) { + return s.resolve(ref.Key, 1) +} + +func (s *dependencyEvaluationSession) resolve(flagKey string, depth int) (string, error) { + if depth > s.maxDepth { + graphErr := dependencyDepthError(flagKey) + _, memoized := s.memo[flagKey] + if !memoized && !s.active[flagKey] { + s.emitDepthError(flagKey, graphErr) + } + return "", graphErr + } + if s.active[flagKey] { + return "", &dependencyGraphError{flagKey: flagKey, code: of.GeneralCode, message: "flag dependency cycle detected"} + } + if memoized, ok := s.memo[flagKey]; ok { + if depth+memoized.descendantDepth > s.maxDepth { + return "", dependencyDepthError(flagKey) + } + s.recordReachedDepth(depth + memoized.descendantDepth) + s.recordExposureTrace(memoized.exposureTrace) + return memoized.result.VariantKey, nil + } + + flag, exists := s.config.Flags[flagKey] + defaultValue := dependencyDefaultValue(flag) + flagType := valueTypeBoolean + if flag != nil { + flagType = flag.VariationType + } + // Reserve the telemetry position at first reach, before descending into + // this prerequisite. Completion fills the slot without changing authored + // DFS/preorder, and memo reuse cannot append another record. + s.reserve(flagKey, flagType, defaultValue) + if !exists { + if configErr, invalid := s.config.invalidFlags[flagKey]; invalid { + result := evaluationResult{ + Value: defaultValue, + Reason: of.ErrorReason, + Error: fmt.Errorf("%w: invalid configuration for prerequisite flag %q: %w", errParseError, flagKey, configErr), + } + s.emit(flagKey, flagType, defaultValue, result) + return "", &dependencyGraphError{flagKey: flagKey, code: of.ParseErrorCode, message: result.Error.Error(), cause: result.Error} + } + cause := fmt.Errorf("%w: prerequisite flag %q is missing", errFlagNotFound, flagKey) + graphErr := &dependencyGraphError{ + flagKey: flagKey, + code: of.FlagNotFoundCode, + message: "prerequisite flag is missing", + cause: cause, + } + result := evaluationResult{ + Value: defaultValue, + Reason: of.ErrorReason, + Error: graphErr, + } + s.emit(flagKey, flagType, defaultValue, result) + return "", graphErr + } + + s.active[flagKey] = true + frame := &dependencyFrame{maxReachedDepth: depth, exposureKeys: make(map[string]struct{})} + s.frames = append(s.frames, frame) + if s.onEvaluate != nil { + s.onEvaluate(flagKey) + } + frameActive := true + defer func() { + if frameActive { + s.frames = s.frames[:len(s.frames)-1] + delete(s.active, flagKey) + } + }() + + result := evaluateConfiguredFlagOnce(s.config, flagKey, defaultValue, s.context, s.now, s.exclusion, + dependencyResolverAtDepth{session: s, depth: depth + 1}) + if result.Error != nil || result.Reason == of.ErrorReason { + graphErr := dependencyErrorFromResult(flagKey, result) + result.Value = defaultValue + result.Reason = of.ErrorReason + result.Error = graphErr + s.emit(flagKey, flag.VariationType, defaultValue, result) + return "", graphErr + } + if result.VariantKey == "" { + graphErr := &dependencyGraphError{flagKey: flagKey, code: of.GeneralCode, message: "prerequisite flag evaluation returned no variant"} + result.Value = defaultValue + result.Reason = of.ErrorReason + result.Error = graphErr + s.emit(flagKey, flag.VariationType, defaultValue, result) + return "", graphErr + } + + candidate := dependencyExposureCandidate{FlagKey: flagKey, Result: withoutEvaluationValue(result)} + appendExposureUnique(&frame.exposureTrace, frame.exposureKeys, candidate) + memoized := memoizedDependency{ + result: result, + descendantDepth: frame.maxReachedDepth - depth, + exposureTrace: append([]dependencyExposureCandidate(nil), frame.exposureTrace...), + } + s.memo[flagKey] = memoized + s.emit(flagKey, flag.VariationType, defaultValue, result) + s.frames = s.frames[:len(s.frames)-1] + delete(s.active, flagKey) + frameActive = false + s.recordReachedDepth(depth + memoized.descendantDepth) + s.recordExposureTrace(memoized.exposureTrace) + return result.VariantKey, nil +} + +func dependencyDepthError(flagKey string) *dependencyGraphError { + return &dependencyGraphError{ + flagKey: flagKey, + code: of.GeneralCode, + message: "maximum flag dependency depth exceeded", + } +} + +func (s *dependencyEvaluationSession) emitDepthError(flagKey string, graphErr *dependencyGraphError) { + flag := s.config.Flags[flagKey] + flagType := valueTypeBoolean + if flag != nil { + flagType = flag.VariationType + } + defaultValue := dependencyDefaultValue(flag) + s.emit(flagKey, flagType, defaultValue, evaluationResult{ + Value: defaultValue, + Reason: of.ErrorReason, + Error: graphErr, + }) +} + +type dependencyResolverAtDepth struct { + session *dependencyEvaluationSession + depth int +} + +func (r dependencyResolverAtDepth) Resolve(ref *flagEvaluation) (string, error) { + return r.session.resolve(ref.Key, r.depth) +} +func (r dependencyResolverAtDepth) Checkpoint() dependencyCheckpoint { return r.session.Checkpoint() } +func (r dependencyResolverAtDepth) Rollback(c dependencyCheckpoint) { r.session.Rollback(c) } + +func (s *dependencyEvaluationSession) recordReachedDepth(depth int) { + if len(s.frames) > 0 && depth > s.frames[len(s.frames)-1].maxReachedDepth { + s.frames[len(s.frames)-1].maxReachedDepth = depth + } +} + +func (s *dependencyEvaluationSession) recordExposureTrace(trace []dependencyExposureCandidate) { + for _, candidate := range trace { + appendExposureUnique(&s.exposures, s.exposureKeys, candidate) + if len(s.frames) > 0 { + frame := s.frames[len(s.frames)-1] + appendExposureUnique(&frame.exposureTrace, frame.exposureKeys, candidate) + } + } +} + +func appendExposureUnique(target *[]dependencyExposureCandidate, keys map[string]struct{}, candidate dependencyExposureCandidate) { + if _, exists := keys[candidate.FlagKey]; exists { + return + } + keys[candidate.FlagKey] = struct{}{} + *target = append(*target, candidate) +} + +func truncateExposureTrace(target *[]dependencyExposureCandidate, keys map[string]struct{}, count int) { + for _, candidate := range (*target)[count:] { + delete(keys, candidate.FlagKey) + } + *target = (*target)[:count] +} + +func withoutEvaluationValue(result evaluationResult) evaluationResult { + result.Value = nil + return result +} + +func (s *dependencyEvaluationSession) emit(flagKey string, flagType valueType, defaultValue any, result evaluationResult) { + index := s.reserve(flagKey, flagType, defaultValue) + if result.Metadata == nil { + result.Metadata = make(map[string]any, 4) + } + environmentID, environmentName := s.config.environmentMetadata() + result.Metadata[metadataEvalTimeKey] = s.now.UnixMilli() + result.Metadata[metadataObserveFullEvaluationDataKey] = s.config.ObserveFullEvaluationData + result.Metadata[metadataEnvironmentIDKey] = environmentID + result.Metadata[metadataEnvironmentNameKey] = environmentName + s.evaluations[index] = dependencyEvaluationRecord{ + FlagKey: flagKey, + FlagType: flagType, + DefaultValue: cloneTelemetryValue(defaultValue), + Result: cloneEvaluationResult(result), + } +} + +func (s *dependencyEvaluationSession) reserve(flagKey string, flagType valueType, defaultValue any) int { + if index, exists := s.evaluationIndexes[flagKey]; exists { + return index + } + index := len(s.evaluations) + s.evaluationIndexes[flagKey] = index + s.evaluations = append(s.evaluations, dependencyEvaluationRecord{ + FlagKey: flagKey, + FlagType: flagType, + DefaultValue: cloneTelemetryValue(defaultValue), + }) + return index +} + +func cloneDependencyEvaluationRecords(records []dependencyEvaluationRecord) []dependencyEvaluationRecord { + if len(records) == 0 { + return nil + } + cloned := make([]dependencyEvaluationRecord, len(records)) + for i, record := range records { + cloned[i] = dependencyEvaluationRecord{ + FlagKey: record.FlagKey, + FlagType: record.FlagType, + DefaultValue: cloneTelemetryValue(record.DefaultValue), + Result: cloneEvaluationResult(record.Result), + } + } + return cloned +} + +func cloneEvaluationResult(result evaluationResult) evaluationResult { + result.Value = cloneTelemetryValue(result.Value) + result.Metadata = cloneTelemetryMap(result.Metadata) + result.Error = cloneDependencyError(result.Error) + result.DependencyEvaluations = nil + return result +} + +func cloneDependencyError(err error) error { + graphErr, ok := err.(*dependencyGraphError) + if !ok || graphErr == nil { + return err + } + return &dependencyGraphError{ + flagKey: graphErr.flagKey, + code: graphErr.code, + message: graphErr.message, + cause: cloneDependencyError(graphErr.cause), + } +} + +func encodeDependencyExposureCandidates(candidates []dependencyExposureCandidate) string { + snapshots := make([]dependencyExposureSnapshot, 0, len(candidates)) + for _, candidate := range candidates { + metadata := candidate.Result.Metadata + allocationKey, _ := metadata[metadataAllocationKey].(string) + doLog, _ := metadata[metadataDoLogKey].(bool) + serialID, hasSerialID := metadata[metadataSplitSerialIDKey].(uint32) + var serialIDPtr *uint32 + if hasSerialID { + serialIDPtr = &serialID + } + cacheHit, hasCacheHit := metadata[metadataExposureCacheHitKey].(bool) + var cacheHitPtr *bool + if hasCacheHit { + cacheHitPtr = &cacheHit + } + snapshots = append(snapshots, dependencyExposureSnapshot{ + FlagKey: candidate.FlagKey, + VariantKey: candidate.Result.VariantKey, + Reason: candidate.Result.Reason, + AllocationKey: allocationKey, + DoLog: doLog, + SerialID: serialIDPtr, + FeaturesKey: featureValuesKey(metadata, metadataExposureFeaturesKey), + HookFeatures: encodeFeatureValues(splitFeatureValues(metadata, metadataHookFeaturePrefix)), + CacheHit: cacheHitPtr, + }) + } + encoded, err := json.Marshal(snapshots) + if err != nil { + return "" + } + return string(encoded) +} + +func decodeDependencyExposureCandidates(encoded string) []dependencyExposureCandidate { + if encoded == "" { + return nil + } + var snapshots []dependencyExposureSnapshot + if err := json.Unmarshal([]byte(encoded), &snapshots); err != nil { + return nil + } + candidates := make([]dependencyExposureCandidate, 0, len(snapshots)) + for _, snapshot := range snapshots { + metadata := map[string]any{ + metadataAllocationKey: snapshot.AllocationKey, + metadataDoLogKey: snapshot.DoLog, + } + if snapshot.SerialID != nil { + metadata[metadataSplitSerialIDKey] = *snapshot.SerialID + } + if snapshot.FeaturesKey != "" { + metadata[metadataExposureFeaturesKey] = snapshot.FeaturesKey + } + if snapshot.HookFeatures != "" { + var features map[string]any + if json.Unmarshal([]byte(snapshot.HookFeatures), &features) == nil { + for key, value := range features { + metadata[metadataHookFeaturePrefix+key] = value + } + } + } + if snapshot.CacheHit != nil { + metadata[metadataExposureCacheHitKey] = *snapshot.CacheHit + } + candidates = append(candidates, dependencyExposureCandidate{ + FlagKey: snapshot.FlagKey, + Result: evaluationResult{ + VariantKey: snapshot.VariantKey, + Reason: snapshot.Reason, + Metadata: metadata, + }, + }) + } + return candidates +} + +func cloneTelemetryMap(source map[string]any) map[string]any { + if source == nil { + return nil + } + cloned := make(map[string]any, len(source)) + for key, value := range source { + cloned[key] = cloneTelemetryValue(value) + } + return cloned +} + +func cloneTelemetryValue(value any) any { + switch value := value.(type) { + case map[string]any: + return cloneTelemetryMap(value) + case []any: + cloned := make([]any, len(value)) + for i, item := range value { + cloned[i] = cloneTelemetryValue(item) + } + return cloned + case []string: + return append([]string(nil), value...) + default: + return value + } +} + +func dependencyErrorFromResult(flagKey string, result evaluationResult) *dependencyGraphError { + code := errorCodeFor(result.Error) + if code == "" { + code = of.GeneralCode + } + message := "prerequisite flag evaluation failed" + if result.Error != nil { + message = result.Error.Error() + } + return &dependencyGraphError{flagKey: flagKey, code: code, message: message, cause: result.Error} +} + +func dependencyDefaultValue(flag *flag) any { + if flag == nil { + return false + } + switch flag.VariationType { + case valueTypeBoolean: + return false + case valueTypeInteger, valueTypeNumeric: + return 0 + case valueTypeString: + return "" + case valueTypeJSON: + return map[string]any{} default: return false } @@ -378,11 +1126,11 @@ func isOneOf(attributeValue any, conditionValue any) bool { case []any: conditionList = make([]string, len(cv)) for i, v := range cv { - if s, ok := v.(string); ok { - conditionList[i] = s - } else { - conditionList[i] = fmt.Sprintf("%v", v) + s, ok := v.(string) + if !ok { + return false } + conditionList[i] = s } default: return false diff --git a/openfeature/evaluator_test.go b/openfeature/evaluator_test.go index 38c646fd6ce..11ab4d1e32f 100644 --- a/openfeature/evaluator_test.go +++ b/openfeature/evaluator_test.go @@ -12,7 +12,9 @@ import ( "fmt" "maps" "os" + "os/exec" "path/filepath" + "strings" "testing" "time" @@ -108,6 +110,15 @@ func TestRegisteredEvaluatorWaitsForProvider(t *testing.T) { } } +func TestInternalAnyEvaluatorAcceptsScalarFlag(t *testing.T) { + h := newOptOutHarness(t, ProviderConfig{}) + evaluate := newAnyEvaluator(h.client) + + value, err := evaluate(context.Background(), "experiment", "subject", nil) + require.NoError(t, err) + require.Equal(t, true, value) +} + func TestEvaluateShard(t *testing.T) { t.Run("targeting key hashes to correct shard", func(t *testing.T) { targetingKey := "user-123" @@ -429,20 +440,149 @@ type fixtureEvaluationResult struct { } type fixtureEvaluationCase struct { - Flag string `json:"flag"` - DefaultValue any `json:"defaultValue"` - TargetingKey *string `json:"targetingKey"` - Attributes map[string]any `json:"attributes"` - Result fixtureEvaluationResult `json:"result"` - Capabilities map[string]fixtureEvaluationResult `json:"capabilities"` + Description string `json:"description"` + Flag string `json:"flag"` + DefaultValue any `json:"defaultValue"` + TargetingKey *string `json:"targetingKey"` + Attributes map[string]any `json:"attributes"` + VariationType string `json:"variationType"` + Result fixtureEvaluationResult `json:"result"` + Capabilities map[string]fixtureEvaluationResult `json:"capabilities"` + Expectations fixtureExpectations `json:"expectations"` } -func TestEvaluateFlag_JSONFixtures(t *testing.T) { - fixtureDir := "ffe-system-test-data" - configData, err := os.ReadFile(filepath.Join(fixtureDir, "ufc-config.json")) +type fixtureExpectations struct { + Exposures []fixtureExpectedExposure `json:"exposures"` + EvaluationEvents []fixtureExpectedEvaluationEvent `json:"evaluationEvents"` + NoUnmatchedEvents bool `json:"noUnmatchedEvents"` +} + +type fixtureExpectedExposure struct { + Count int `json:"_count"` + Allocation string `json:"allocation"` + Flag string `json:"flag"` + Variant string `json:"variant"` +} + +type fixtureExpectedEvaluationEvent struct { + Count int `json:"_count"` + Flag string `json:"flag"` + ErrorCode *string `json:"errorCode"` +} + +type fixtureCaseFile struct { + name string + cases []fixtureEvaluationCase +} + +type fixtureSuite struct { + name string + configurationPath string + casesPath string + assertTelemetry bool +} + +func loadFixtureSuite(t *testing.T, suite fixtureSuite) ([]fixtureCaseFile, []byte, int) { + t.Helper() + files, err := filepath.Glob(filepath.Join(suite.casesPath, "*.json")) + if err != nil { + t.Fatal(err) + } + if len(files) == 0 { + t.Fatal("no canonical FFE evaluation-case fixtures found (initialize them with `git submodule update --init --recursive`)") + } + + fixtureFiles := make([]fixtureCaseFile, 0, len(files)) + caseCount := 0 + for _, file := range files { + data, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + var cases []fixtureEvaluationCase + if err := json.Unmarshal(data, &cases); err != nil { + t.Fatalf("parse %s: %v", file, err) + } + caseCount += len(cases) + fixtureFiles = append(fixtureFiles, fixtureCaseFile{name: filepath.Base(file), cases: cases}) + } + if caseCount == 0 { + t.Fatal("no canonical FFE evaluation cases found") + } + configData, err := os.ReadFile(suite.configurationPath) if err != nil { t.Fatalf("read canonical FFE fixtures: %v (initialize them with `git submodule update --init --recursive`)", err) } + return fixtureFiles, configData, caseCount +} + +func fixtureRevision(fixtureDir string) (string, error) { + out, err := exec.Command("git", "-C", fixtureDir, "rev-parse", "--show-toplevel", "HEAD").Output() + if err != nil { + return "", fmt.Errorf("resolve fixture revision: %w", err) + } + lines := strings.Split(strings.TrimSpace(string(out)), "\n") + if len(lines) != 2 { + return "", fmt.Errorf("resolve fixture revision: expected repository root and revision, got %d lines", len(lines)) + } + fixtureInfo, err := os.Stat(fixtureDir) + if err != nil { + return "", fmt.Errorf("resolve fixture revision: stat fixture directory: %w", err) + } + repositoryRoot := strings.TrimSpace(lines[0]) + repositoryInfo, err := os.Stat(repositoryRoot) + if err != nil { + return "", fmt.Errorf("resolve fixture revision: stat repository root: %w", err) + } + if !os.SameFile(fixtureInfo, repositoryInfo) { + return "", fmt.Errorf("resolve fixture revision: fixture directory %q is not repository root %q", fixtureDir, repositoryRoot) + } + revision := strings.TrimSpace(lines[1]) + if revision == "" { + return "", errors.New("resolve fixture revision: empty revision") + } + return revision, nil +} + +func TestFixtureRevisionRejectsMissingGitMetadata(t *testing.T) { + _, err := fixtureRevision(t.TempDir()) + require.Error(t, err) +} + +func TestFixtureRevisionRejectsParentGitMetadata(t *testing.T) { + // The package directory is inside the superproject but is not itself a Git root. + _, err := fixtureRevision(".") + require.Error(t, err) +} + +func TestEvaluateFlag_JSONFixtures(t *testing.T) { + fixtureRoot := "ffe-system-test-data" + revision, err := fixtureRevision(fixtureRoot) + require.NoError(t, err) + for _, suite := range []fixtureSuite{ + { + name: "Core", + configurationPath: filepath.Join(fixtureRoot, "ufc-config.json"), + casesPath: filepath.Join(fixtureRoot, "evaluation-cases"), + }, + { + name: "Dependent", + configurationPath: filepath.Join(fixtureRoot, "evaluation-suites", "dependent-flags", "ufc-config.json"), + casesPath: filepath.Join(fixtureRoot, "evaluation-suites", "dependent-flags", "cases"), + assertTelemetry: true, + }, + } { + t.Run(suite.name, func(t *testing.T) { + runEvaluateFlagJSONFixtures(t, suite, revision) + }) + } +} + +func runEvaluateFlagJSONFixtures(t *testing.T, suite fixtureSuite, revision string) { + t.Helper() + fixtureFiles, configData, caseCount := loadFixtureSuite(t, suite) + t.Logf("canonical FFE fixtures suite=%s revision=%s cases=%d", suite.name, revision, caseCount) + var cfg universalFlagsConfiguration if err := json.Unmarshal(configData, &cfg); err != nil { t.Fatal(err) @@ -454,7 +594,6 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { if err := of.SetProviderAndWait(provider); err != nil { t.Fatalf("set provider: %v", err) } - client := of.NewClient("fixture-test") immediateProvider := newDatadogProvider(ProviderConfig{ ExperimentationOptOutMode: ExperimentationOptOutImmediate, }) @@ -473,7 +612,7 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { "experimentationOptOutFutureExperimentsOnly": futureProvider, } capabilityCases := make(map[string]int) - // Minimums pin each semantic family independently; additional cases are welcome. + // Pin each supported semantic family independently; additional cases are welcome. // A global capability count can hide a missing family behind another file. requiredFamilies := map[string]map[string]int{ "test-case-experimentation-opt-out.json": { @@ -486,39 +625,27 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { } familyCases := make(map[string]map[string]int) - files, err := filepath.Glob(filepath.Join(fixtureDir, "evaluation-cases", "*.json")) - if err != nil { - t.Fatal(err) - } - if len(files) == 0 { - t.Fatal("no canonical FFE evaluation-case fixtures found (initialize them with `git submodule update --init --recursive`)") - } - - for _, file := range files { - data, err := os.ReadFile(file) - if err != nil { - t.Fatal(err) - } - var cases []fixtureEvaluationCase - if err := json.Unmarshal(data, &cases); err != nil { - t.Fatalf("parse %s: %v", file, err) - } + for _, file := range fixtureFiles { // Count discovered cases, not selected subtests, so -run filters remain usable. counts := make(map[string]int) - familyCases[filepath.Base(file)] = counts - for _, tc := range cases { + familyCases[file.name] = counts + for _, tc := range file.cases { for capability := range tc.Capabilities { capabilityCases[capability]++ counts[capability]++ } } - t.Run(filepath.Base(file), func(t *testing.T) { - for i, tc := range cases { + t.Run(file.name, func(t *testing.T) { + for i, tc := range file.cases { tkLabel := "" if tc.TargetingKey != nil { tkLabel = *tc.TargetingKey } t.Run(fmt.Sprintf("case%d/%s", i, tkLabel), func(t *testing.T) { + if suite.assertTelemetry { + assertDependentFixtureCase(t, configData, tc) + return + } ctx := make(map[string]any, len(tc.Attributes)+1) maps.Copy(ctx, tc.Attributes) if tc.TargetingKey != nil { @@ -550,16 +677,12 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { assertFixtureFeatures(t, &cfg, tc, result) } if tc.Result.ErrorCode != "" { - evaluationContext := of.NewEvaluationContext("", tc.Attributes) - if tc.TargetingKey != nil { - evaluationContext = of.NewEvaluationContext(*tc.TargetingKey, tc.Attributes) - } - details, err := client.ObjectValueDetails(context.Background(), tc.Flag, tc.DefaultValue, evaluationContext) - if err == nil { + result := provider.evaluateAny(context.Background(), tc.Flag, tc.DefaultValue, ctx) + if result.Error == nil { t.Error("expected SDK evaluation error, got nil") } - if details.ErrorCode != of.ErrorCode(tc.Result.ErrorCode) { - t.Errorf("error code: got %q, want %q", details.ErrorCode, tc.Result.ErrorCode) + if code := errorCodeFor(result.Error); code != of.ErrorCode(tc.Result.ErrorCode) { + t.Errorf("error code: got %q, want %q", code, tc.Result.ErrorCode) } } for capability, expected := range tc.Capabilities { @@ -568,12 +691,12 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { continue } t.Run(capability, func(t *testing.T) { - result := p.ObjectEvaluation(context.Background(), tc.Flag, tc.DefaultValue, ctx) + result := p.evaluateAny(context.Background(), tc.Flag, tc.DefaultValue, ctx) assert.Equal(t, expected.Value, result.Value, "capability result value") if result.Reason != of.Reason(expected.Reason) { t.Errorf("reason: got %q, want %q", result.Reason, expected.Reason) } - if code := result.ResolutionDetail().ErrorCode; code != of.ErrorCode(expected.ErrorCode) { + if code := errorCodeFor(result.Error); code != of.ErrorCode(expected.ErrorCode) { t.Errorf("error code: got %q, want %q", code, expected.ErrorCode) } }) @@ -582,18 +705,183 @@ func TestEvaluateFlag_JSONFixtures(t *testing.T) { } }) } - for family, minimums := range requiredFamilies { - for capability, minimum := range minimums { - if count := familyCases[family][capability]; count < minimum { - t.Errorf("canonical fixture family %q has %d cases for capability %q; require at least %d", family, count, capability, minimum) + if !suite.assertTelemetry { + for family, minimums := range requiredFamilies { + for capability, minimum := range minimums { + if count := familyCases[family][capability]; count < minimum { + t.Errorf("canonical fixture family %q has %d cases for capability %q; require at least %d", family, count, capability, minimum) + } + } + } + for capability := range capabilityProviders { + if capabilityCases[capability] == 0 { + t.Errorf("no canonical fixture cases found for supported capability %q", capability) + } + } + } + t.Logf("canonical FFE fixture capabilities=%v", capabilityCases) +} + +type fixtureResolution struct { + value any + reason of.Reason + errorCode of.ErrorCode +} + +func assertDependentFixtureCase(t *testing.T, configData []byte, tc fixtureEvaluationCase) { + t.Helper() + var cfg universalFlagsConfiguration + require.NoError(t, json.Unmarshal(configData, &cfg)) + + // Each corpus case gets an isolated provider, cache, writers, and transport + // sink so no earlier subject or aggregation bucket can affect its events. + h := newOptOutHarness(t, ProviderConfig{}) + h.provider.mu.Lock() + h.provider.configuration = &cfg + h.provider.mu.Unlock() + + resolution := evaluateFixtureThroughClient(t, h.client, tc) + assert.Equal(t, fmt.Sprint(tc.Result.Value), fmt.Sprint(resolution.value), "result value") + if tc.Result.Reason != "" { + assert.Equal(t, of.Reason(tc.Result.Reason), resolution.reason, "result reason") + } + if tc.Result.ErrorCode != "" { + assert.Equal(t, of.ErrorCode(tc.Result.ErrorCode), resolution.errorCode, "result error code") + } + + h.provider.flagEvalLoggingWriter.drainAndFlush() + h.provider.exposureWriter.flush() + if tc.Expectations.Exposures != nil { + assertFixtureExpectedExposures(t, tc.Expectations, h.sink.exposures) + } + if tc.Expectations.EvaluationEvents != nil { + assertFixtureExpectedEvaluationEvents(t, tc.Expectations, h.sink.events) + } +} + +func evaluateFixtureThroughClient(t *testing.T, client *of.Client, tc fixtureEvaluationCase) fixtureResolution { + t.Helper() + targetingKey := "" + if tc.TargetingKey != nil { + targetingKey = *tc.TargetingKey + } + evaluationContext := of.NewEvaluationContext(targetingKey, tc.Attributes) + ctx := context.Background() + switch tc.VariationType { + case "BOOLEAN": + defaultValue, _ := tc.DefaultValue.(bool) + details, _ := client.BooleanValueDetails(ctx, tc.Flag, defaultValue, evaluationContext) + return fixtureResolution{value: details.Value, reason: details.Reason, errorCode: details.ErrorCode} + case "STRING": + defaultValue, _ := tc.DefaultValue.(string) + details, _ := client.StringValueDetails(ctx, tc.Flag, defaultValue, evaluationContext) + return fixtureResolution{value: details.Value, reason: details.Reason, errorCode: details.ErrorCode} + case "INTEGER": + defaultValue := fixtureInteger(tc.DefaultValue) + details, _ := client.IntValueDetails(ctx, tc.Flag, defaultValue, evaluationContext) + return fixtureResolution{value: details.Value, reason: details.Reason, errorCode: details.ErrorCode} + case "NUMERIC": + defaultValue := fixtureFloat(tc.DefaultValue) + details, _ := client.FloatValueDetails(ctx, tc.Flag, defaultValue, evaluationContext) + return fixtureResolution{value: details.Value, reason: details.Reason, errorCode: details.ErrorCode} + case "JSON": + details, _ := client.ObjectValueDetails(ctx, tc.Flag, tc.DefaultValue, evaluationContext) + return fixtureResolution{value: details.Value, reason: details.Reason, errorCode: details.ErrorCode} + default: + t.Fatalf("unsupported fixture variationType %q", tc.VariationType) + return fixtureResolution{} + } +} + +func fixtureInteger(value any) int64 { + switch value := value.(type) { + case int64: + return value + case int: + return int64(value) + case float64: + return int64(value) + default: + return 0 + } +} + +func fixtureFloat(value any) float64 { + switch value := value.(type) { + case float64: + return value + case int64: + return float64(value) + case int: + return float64(value) + default: + return 0 + } +} + +func fixtureExpectedCount(count int) int { + if count <= 0 { + return 1 + } + return count +} + +func assertFixtureExpectedExposures(t *testing.T, expectations fixtureExpectations, actual []exposureEvent) { + t.Helper() + remaining := append([]exposureEvent(nil), actual...) + for _, expected := range expectations.Exposures { + for range fixtureExpectedCount(expected.Count) { + match := -1 + for i, event := range remaining { + if event.Flag.Key != expected.Flag || + (expected.Allocation != "" && event.Allocation.Key != expected.Allocation) || + (expected.Variant != "" && event.Variant.Key != expected.Variant) { + continue + } + match = i + break } + require.NotEqual(t, -1, match, "missing expected exposure %+v; actual=%+v", expected, actual) + remaining = append(remaining[:match], remaining[match+1:]...) } } - for capability := range capabilityProviders { - if capabilityCases[capability] == 0 { - t.Errorf("no canonical fixture cases found for supported capability %q", capability) + if expectations.NoUnmatchedEvents { + assert.Empty(t, remaining, "unexpected exposures") + } +} + +func assertFixtureExpectedEvaluationEvents(t *testing.T, expectations fixtureExpectations, actual []flagEvalLoggingEvent) { + t.Helper() + remaining := make([]flagEvalLoggingEvent, 0, len(actual)) + for _, event := range actual { + for range max(int(event.EvaluationCount), 1) { + remaining = append(remaining, event) + } + } + for _, expected := range expectations.EvaluationEvents { + for range fixtureExpectedCount(expected.Count) { + match := -1 + for i, event := range remaining { + actualErrorCode := "" + if event.Error != nil { + actualErrorCode = event.Error.Message + } + expectedErrorCode := "" + if expected.ErrorCode != nil { + expectedErrorCode = *expected.ErrorCode + } + if event.Flag.Key == expected.Flag && actualErrorCode == expectedErrorCode { + match = i + break + } + } + require.NotEqual(t, -1, match, "missing expected evaluation event %+v; actual=%+v", expected, actual) + remaining = append(remaining[:match], remaining[match+1:]...) } } + if expectations.NoUnmatchedEvents { + assert.Empty(t, remaining, "unexpected evaluation events") + } } // assertFixtureFeatures runs every case declaring result.features through the @@ -626,11 +914,10 @@ func assertFixtureFeatures(t *testing.T, cfg *universalFlagsConfiguration, tc fi if tc.TargetingKey != nil { targetingKey = *tc.TargetingKey } - details, err := h.client.ObjectValueDetails(context.Background(), tc.Flag, tc.DefaultValue, - of.NewEvaluationContext(targetingKey, tc.Attributes)) + evaluate := newAnyEvaluator(h.client) + value, err := evaluate(context.Background(), tc.Flag, targetingKey, tc.Attributes) require.NoError(t, err) - assert.Equal(t, tc.Result.Value, details.Value) - assert.Equal(t, of.Reason(tc.Result.Reason), details.Reason) + assert.Equal(t, tc.Result.Value, value) require.Len(t, callbacks, 1) assertFeatures("HOOK", callbacks[0].Features()) if tc.Result.DoLog != nil { diff --git a/openfeature/exposure.go b/openfeature/exposure.go index c9e415dea17..4bcaa349b51 100644 --- a/openfeature/exposure.go +++ b/openfeature/exposure.go @@ -157,6 +157,21 @@ func (c *exposureLRUCache) add(key exposureCacheKey, value exposureCacheValue) b return true } +// isDuplicate reports an existing identical entry and refreshes its LRU +// position without changing the cached decision. +func (c *exposureLRUCache) isDuplicate(key exposureCacheKey, value exposureCacheValue) bool { + elem, exists := c.items[key] + if !exists { + return false + } + entry := elem.Value.(*exposureCacheEntry) + if entry.value != value { + return false + } + c.order.MoveToFront(elem) + return true +} + // evictOldest removes the least recently used entry func (c *exposureLRUCache) evictOldest() { elem := c.order.Back() @@ -258,16 +273,32 @@ func (w *exposureWriter) periodicFlush() { // append adds an exposure event to the buffer with deduplication func (w *exposureWriter) append(event exposureEvent) bool { - added, _ := w.appendWithDecision(event) + added, _ := w.appendWithDecisionAndAttributes(event, nil) + return added +} + +func (w *exposureWriter) appendWithAttributes(event exposureEvent, attributes func() map[string]any) bool { + added, _ := w.appendWithDecisionAndAttributes(event, attributes) return added } // appendWithDecision distinguishes a duplicate from an unavailable cache decision. func (w *exposureWriter) appendWithDecision(event exposureEvent) (added, known bool) { + return w.appendWithDecisionAndAttributes(event, nil) +} + +// appendWithDecisionAndAttributes checks the cache before building the detached +// subject attributes, then commits the decision after the snapshot succeeds. +// The lazy callback is shared by all events in one root evaluation, so cache +// hits do no context work and admitted events reuse one map. +func (w *exposureWriter) appendWithDecisionAndAttributes( + event exposureEvent, + attributes func() map[string]any, +) (added, known bool) { w.mu.Lock() - defer w.mu.Unlock() if w.stopped { + w.mu.Unlock() return false, false } @@ -285,18 +316,43 @@ func (w *exposureWriter) appendWithDecision(event exposureEvent) (added, known b cacheValue.hasSerialID = true } - // Check deduplication cache - returns true if this is a new or changed entry - if !w.cache.add(cacheKey, cacheValue) { + // An already committed duplicate needs no subject snapshot. New or changed + // entries are committed only after any application-provided String methods + // invoked while detaching the snapshot return successfully. + if w.cache.isDuplicate(cacheKey, cacheValue) { // Duplicate exposure - skip + w.mu.Unlock() return false, true } - if w.datadogLoggingEnabled { - if event.featuresKey != "" { - event.Features = w.featureValues.values(event.featuresKey) + if !w.datadogLoggingEnabled { + isNew := w.cache.add(cacheKey, cacheValue) + w.mu.Unlock() + return isNew, true + } + if attributes != nil { + // Caller attributes can invoke application String methods. Do not run them + // under the writer lock: a String method may re-enter flag evaluation. + w.mu.Unlock() + event.Subject.Attributes = attributes() + w.mu.Lock() + if w.stopped { + w.mu.Unlock() + return false, false } - w.buffer = append(w.buffer, event) } + // Another evaluation may have committed this decision while the writer was + // unlocked to build attributes. Recheck under the lock so concurrent + // identical evaluations still buffer exactly one exposure. + if !w.cache.add(cacheKey, cacheValue) { + w.mu.Unlock() + return false, true + } + if event.featuresKey != "" { + event.Features = w.featureValues.values(event.featuresKey) + } + w.buffer = append(w.buffer, event) + w.mu.Unlock() return true, true } diff --git a/openfeature/exposure_hook.go b/openfeature/exposure_hook.go index 17c09a93bfe..10b8a1a0ca9 100644 --- a/openfeature/exposure_hook.go +++ b/openfeature/exposure_hook.go @@ -96,6 +96,8 @@ func (h *exposureHook) Finally( if flagEvaluationDetails.ErrorCode != "" || flagEvaluationDetails.Reason == of.ErrorReason { return } + subject := newExposureSubjectSnapshot(hookContext.EvaluationContext()) + h.appendDependencyExposures(subject, flagEvaluationDetails.FlagMetadata) // The provider checks cancellation before resolving. Cancellation after a // successful resolution must not discard an exposure for the returned value. evaluation := ExposureEvaluation{Details: flagEvaluationDetails} @@ -104,52 +106,15 @@ func (h *exposureHook) Finally( return } - allocationKey, _ := evaluation.AllocationKey() // IsExposure established its presence. - var serialID *uint32 - if id, ok := evaluation.SplitSerialID(); ok { - serialID = new(id) - } - - // Get targeting key (subject ID) from evaluation context - evalContext := hookContext.EvaluationContext() - targetingKey := evalContext.TargetingKey() - - // Build flat context from evaluation context - flatContext := make(map[string]any) - flatContext[of.TargetingKey] = targetingKey - maps.Copy(flatContext, evalContext.Attributes()) - - // Flatten attributes for exposure event - flattenedAttrs := flattenContext(flatContext) - - // Extract only primitive attributes for the subject - subjectAttrs := extractPrimitiveAttributes(flattenedAttrs) - - // Create exposure event - event := exposureEvent{ - Timestamp: time.Now().UnixMilli(), - Allocation: exposureAllocation{ - Key: allocationKey, - }, - Flag: exposureFlag{ - Key: hookContext.FlagKey(), - }, - Variant: exposureVariant{ - Key: flagEvaluationDetails.Variant, - }, - Subject: exposureSubject{ - ID: targetingKey, - Type: "", // Type is optional - Attributes: subjectAttrs, // Flattened, primitive-only attributes - }, - SerialID: serialID, - featuresKey: featureValuesKey(flagEvaluationDetails.FlagMetadata, metadataExposureFeaturesKey), - } + event, _ := makeExposureEvent(hookContext.FlagKey(), flagEvaluationDetails.Variant, + flagEvaluationDetails.FlagMetadata, subject.targetingKey) + targetingKey := event.Subject.ID + allocationKey := event.Allocation.Key // Send to writer for buffering and eventual flushing // Decide once for all destinations. Customer hooks run after provider hooks // and read this stamp without consuming another cache entry. - isNew, known := h.writer.appendWithDecision(event) + isNew, known := h.writer.appendWithDecisionAndAttributes(event, subject.attributes) if known { flagEvaluationDetails.FlagMetadata[metadataExposureCacheHitKey] = !isNew } @@ -174,6 +139,75 @@ func (h *exposureHook) Finally( } } +func (h *exposureHook) appendDependencyExposures(subject *exposureSubjectSnapshot, metadata of.FlagMetadata) { + encoded, _ := metadata[metadataDependencyExposuresKey].(string) + candidates := decodeDependencyExposureCandidates(encoded) + if len(candidates) == 0 { + return + } + for i, candidate := range candidates { + event, eligible := makeExposureEvent(candidate.FlagKey, candidate.Result.VariantKey, + candidate.Result.Metadata, subject.targetingKey) + if eligible { + isNew, known := h.writer.appendWithDecisionAndAttributes(event, subject.attributes) + if known { + candidates[i].Result.Metadata[metadataExposureCacheHitKey] = !isNew + } + } + } + metadata[metadataDependencyExposuresKey] = encodeDependencyExposureCandidates(candidates) +} + +type exposureSubjectSnapshot struct { + targetingKey string + context of.EvaluationContext + detached map[string]any + ready bool +} + +func newExposureSubjectSnapshot(context of.EvaluationContext) *exposureSubjectSnapshot { + return &exposureSubjectSnapshot{targetingKey: context.TargetingKey(), context: context} +} + +func (s *exposureSubjectSnapshot) attributes() map[string]any { + if !s.ready { + flatContext := make(map[string]any, len(s.context.Attributes())+1) + flatContext[of.TargetingKey] = s.targetingKey + maps.Copy(flatContext, s.context.Attributes()) + s.detached = extractPrimitiveAttributes(flattenContext(flatContext)) + s.ready = true + } + return s.detached +} + +func makeExposureEvent( + flagKey string, + variantKey string, + metadata of.FlagMetadata, + targetingKey string, +) (exposureEvent, bool) { + allocationKey, hasAllocation := metadata[metadataAllocationKey].(string) + doLog, _ := metadata[metadataDoLogKey].(bool) + if !hasAllocation || !doLog || variantKey == "" { + return exposureEvent{}, false + } + var serialID *uint32 + if id, ok := metadata[metadataSplitSerialIDKey].(uint32); ok { + serialID = new(id) + } + return exposureEvent{ + Timestamp: time.Now().UnixMilli(), + Allocation: exposureAllocation{Key: allocationKey}, + Flag: exposureFlag{Key: flagKey}, + Variant: exposureVariant{Key: variantKey}, + Subject: exposureSubject{ + ID: targetingKey, + }, + SerialID: serialID, + featuresKey: featureValuesKey(metadata, metadataExposureFeaturesKey), + }, true +} + // ExposureEvaluation describes a completed evaluation. Its cache decision // is shared with Datadog's default exposure hook, even when Datadog logging is disabled. // It does not confirm delivery to Datadog or to a customer destination. @@ -225,8 +259,9 @@ func (e ExposureEvaluation) ShouldSend() bool { } // ExposureHook calls customer code after completed evaluations, including errors, -// non-exposures and cache hits. Register it with the OpenFeature API, a client, or -// an evaluation, retaining the provider's hooks. The callback runs synchronously: enqueue +// non-exposures and cache hits. A successful dependent evaluation calls the hook +// once per selected prerequisite before the root. Register it with the OpenFeature API, +// a client, or an evaluation, retaining the provider's hooks. The callback runs synchronously: enqueue // copied scalar fields for background delivery. It can run concurrently. // Treat Details.Value as read-only. JSON maps and slices can share provider state; // copy them before modification or background processing. @@ -254,7 +289,8 @@ func NewExposureHook(callback func(ExposureEvaluation)) *ExposureHook { return &ExposureHook{callback: callback} } -// Finally invokes the callback with the shared exposure decision. +// Finally invokes the callback for each transactionally selected prerequisite, +// followed by the root, using the shared exposure decisions. func (h *ExposureHook) Finally(_ context.Context, ctx of.HookContext, details of.InterfaceEvaluationDetails, _ of.HookHints) { if h.callback == nil { return @@ -265,20 +301,45 @@ func (h *ExposureHook) Finally(_ context.Context, ctx of.HookContext, details of }) return } + // TODO(open-feature/go-sdk#623): Remove normalization and marker cleanup when + // go.mod requires the fixed release; retain the metadata copy for isolation. + details = exposureFinalDetails(ctx, details) + if details.ErrorCode == "" && details.Reason != of.ErrorReason { + encoded, _ := details.FlagMetadata[metadataDependencyExposuresKey].(string) + for _, candidate := range decodeDependencyExposureCandidates(encoded) { + dependencyDetails := of.InterfaceEvaluationDetails{ + EvaluationDetails: of.EvaluationDetails{ + FlagKey: candidate.FlagKey, + ResolutionDetail: of.ResolutionDetail{ + Variant: candidate.Result.VariantKey, + Reason: candidate.Result.Reason, + FlagMetadata: maps.Clone(candidate.Result.Metadata), + }, + }, + } + h.invoke(ctx.EvaluationContext(), candidate.FlagKey, dependencyDetails) + } + } + + // Isolate metadata edits from the other callbacks and returned evaluation. + details.FlagMetadata = maps.Clone(details.FlagMetadata) + delete(details.FlagMetadata, metadataExposureAfterErrorKey) + h.invoke(ctx.EvaluationContext(), ctx.FlagKey(), details) +} + +func (h *ExposureHook) invoke(evaluationContext of.EvaluationContext, flagKey string, details of.InterfaceEvaluationDetails) { defer func() { if recover() != nil { if h.panicWarned.CompareAndSwap(false, true) { - log.Warn("openfeature: customer exposure callback panicked for flag %q; later panics are logged at debug level", ctx.FlagKey()) //errtrack:ignore customer callback + containLoggerPanic(func() { + log.Warn("openfeature: customer exposure callback panicked for flag %q; later panics are logged at debug level", flagKey) //errtrack:ignore customer callback + }) } else { - log.Debug("openfeature: customer exposure callback panicked for flag %q", ctx.FlagKey()) + containLoggerPanic(func() { + log.Debug("openfeature: customer exposure callback panicked for flag %q", flagKey) + }) } } }() - // TODO(open-feature/go-sdk#623): Remove normalization and marker cleanup when - // go.mod requires the fixed release; retain the metadata copy for isolation. - details = exposureFinalDetails(ctx, details) - // Isolate metadata edits from the other callbacks and returned evaluation. - details.FlagMetadata = maps.Clone(details.FlagMetadata) - delete(details.FlagMetadata, metadataExposureAfterErrorKey) - h.callback(ExposureEvaluation{Context: ctx.EvaluationContext(), Details: details}) + h.callback(ExposureEvaluation{Context: evaluationContext, Details: details}) } diff --git a/openfeature/exposure_test.go b/openfeature/exposure_test.go index 001cb4fde28..28afd93fff5 100644 --- a/openfeature/exposure_test.go +++ b/openfeature/exposure_test.go @@ -10,11 +10,77 @@ import ( "fmt" "sync" "testing" + "time" jsoniter "github.com/json-iterator/go" of "github.com/open-feature/go-sdk/openfeature" ) +type countingExposureStringer struct { + calls *int +} + +func (s countingExposureStringer) String() string { + (*s.calls)++ + return "counted" +} + +type reentrantExposureStringer struct { + writer *exposureWriter +} + +func (s reentrantExposureStringer) String() string { + s.writer.append(exposureEvent{ + Allocation: exposureAllocation{Key: "reentrant-allocation"}, + Flag: exposureFlag{Key: "reentrant"}, + Variant: exposureVariant{Key: "on"}, + Subject: exposureSubject{ID: "subject"}, + }) + return "reentrant" +} + +type panickingExposureStringer struct{} + +func (panickingExposureStringer) String() string { + panic("snapshot failed") +} + +func wideDependencyExposureMetadata(count int) of.FlagMetadata { + candidates := make([]dependencyExposureCandidate, 0, count) + for i := range count { + candidates = append(candidates, dependencyExposureCandidate{ + FlagKey: fmt.Sprintf("dependency-%d", i), + Result: evaluationResult{ + VariantKey: "on", + Metadata: map[string]any{ + metadataAllocationKey: fmt.Sprintf("allocation-%d", i), + metadataDoLogKey: true, + }, + }, + }) + } + return of.FlagMetadata{ + metadataAllocationKey: "root-allocation", + metadataDoLogKey: true, + metadataDependencyExposuresKey: encodeDependencyExposureCandidates(candidates), + } +} + +func wideExposureHookDetails(metadata of.FlagMetadata) of.InterfaceEvaluationDetails { + return of.InterfaceEvaluationDetails{ + Value: true, + EvaluationDetails: of.EvaluationDetails{ + FlagKey: "root", + FlagType: of.Boolean, + ResolutionDetail: of.ResolutionDetail{ + Variant: "on", + Reason: of.TargetingMatchReason, + FlagMetadata: metadata, + }, + }, + } +} + func TestLRUCache_NewEntry(t *testing.T) { cache := newExposureLRUCache(100) @@ -201,6 +267,275 @@ func TestExposureWriter_AppendCarriesSerialIDIntoCache(t *testing.T) { } } +func TestExposureHookWideDependenciesShareDetachedSubjectSnapshot(t *testing.T) { + const dependencyCount = 512 + calls := 0 + attributes := map[string]any{ + "counted": countingExposureStringer{calls: &calls}, + "profile": map[string]any{"tier": "paid"}, + } + evalCtx := of.NewEvaluationContext("subject", attributes) + hookCtx := of.NewHookContext( + "root", of.Boolean, false, of.NewClientMetadata(""), + of.Metadata{Name: datadogProviderName}, evalCtx, + ) + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, dependencyCount+1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + hook := newExposureHook(writer) + details := wideExposureHookDetails(wideDependencyExposureMetadata(dependencyCount)) + + hook.Finally(context.Background(), hookCtx, details, of.HookHints{}) + if calls != 1 { + t.Fatalf("context walks = %d, want 1 for %d dependency and root exposures", calls, dependencyCount) + } + if got := len(writer.buffer); got != dependencyCount+1 { + t.Fatalf("buffered exposures = %d, want %d", got, dependencyCount+1) + } + attributes["profile"].(map[string]any)["tier"] = "mutated" + for i, event := range writer.buffer { + if got := event.Subject.Attributes["counted"]; got != "counted" { + t.Fatalf("exposure %d counted attribute = %#v, want counted", i, got) + } + if got := event.Subject.Attributes["profile.tier"]; got != "paid" { + t.Fatalf("exposure %d retained caller mutation: got %#v, want paid", i, got) + } + } + + // Every event is now a cache hit. A fresh per-evaluation lazy snapshot must + // remain untouched because no event is admitted to the buffer. + hook.Finally(context.Background(), hookCtx, details, of.HookHints{}) + if calls != 1 { + t.Fatalf("cache-hit context walks = %d, want no additional walk", calls) + } + if got := len(writer.buffer); got != dependencyCount+1 { + t.Fatalf("cache hits appended exposures: buffer=%d", got) + } +} + +func TestExposureSubjectSnapshotDoesNotRunApplicationCodeUnderWriterLock(t *testing.T) { + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, 2), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + evalCtx := of.NewEvaluationContext("subject", map[string]any{ + "reentrant": reentrantExposureStringer{writer: writer}, + }) + hookCtx := of.NewHookContext( + "root", of.Boolean, false, of.NewClientMetadata(""), + of.Metadata{Name: datadogProviderName}, evalCtx, + ) + details := wideExposureHookDetails(of.FlagMetadata{ + metadataAllocationKey: "root-allocation", + metadataDoLogKey: true, + }) + + newExposureHook(writer).Finally(context.Background(), hookCtx, details, of.HookHints{}) + + if got := len(writer.buffer); got != 2 { + t.Fatalf("buffered exposures = %d, want reentrant and root events", got) + } + if got := writer.buffer[1].Subject.Attributes["reentrant"]; got != "reentrant" { + t.Fatalf("root reentrant attribute = %#v, want reentrant", got) + } +} + +func TestExposureSnapshotDoesNotBlockWriterStop(t *testing.T) { + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, 1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + stopChan: make(chan struct{}), + } + event := exposureEvent{ + Allocation: exposureAllocation{Key: "allocation"}, + Flag: exposureFlag{Key: "flag"}, + Variant: exposureVariant{Key: "on"}, + Subject: exposureSubject{ID: "subject"}, + } + entered := make(chan struct{}) + release := make(chan struct{}) + appendDone := make(chan struct{}) + go func() { + defer close(appendDone) + writer.appendWithAttributes(event, func() map[string]any { + close(entered) + <-release + return map[string]any{"detached": true} + }) + }() + <-entered + + stopDone := make(chan struct{}) + go func() { + defer close(stopDone) + writer.stop() + }() + select { + case <-stopDone: + case <-time.After(time.Second): + t.Fatal("writer stop blocked on application String work") + } + close(release) + select { + case <-appendDone: + case <-time.After(time.Second): + t.Fatal("exposure append did not observe stopped writer") + } + if got := len(writer.buffer); got != 0 { + t.Fatalf("buffered exposures after stop = %d, want 0", got) + } +} + +func TestExposureSnapshotPanicDoesNotConsumeCacheDecision(t *testing.T) { + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, 1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + hook := newExposureHook(writer) + details := wideExposureHookDetails(of.FlagMetadata{ + metadataAllocationKey: "root-allocation", + metadataDoLogKey: true, + }) + makeHookContext := func(attribute any) of.HookContext { + return of.NewHookContext( + "root", of.Boolean, false, of.NewClientMetadata(""), + of.Metadata{Name: datadogProviderName}, + of.NewEvaluationContext("subject", map[string]any{"attribute": attribute}), + ) + } + + panicked := false + func() { + defer func() { panicked = recover() != nil }() + hook.Finally(context.Background(), makeHookContext(panickingExposureStringer{}), details, of.HookHints{}) + }() + if !panicked { + t.Fatal("snapshot Stringer did not panic") + } + if got := len(writer.buffer); got != 0 { + t.Fatalf("buffered exposures after snapshot panic = %d, want 0", got) + } + + second := wideExposureHookDetails(of.FlagMetadata{ + metadataAllocationKey: "root-allocation", + metadataDoLogKey: true, + }) + hook.Finally(context.Background(), makeHookContext("safe"), second, of.HookHints{}) + if got := len(writer.buffer); got != 1 { + t.Fatalf("buffered exposures after retry = %d, want 1", got) + } + if !(&ExposureEvaluation{Details: second}).ShouldSend() { + t.Fatal("retry after snapshot panic was reported as a cache hit") + } +} + +func TestExposureSnapshotConcurrentDuplicatesCommitOnce(t *testing.T) { + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, 1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + event := exposureEvent{ + Allocation: exposureAllocation{Key: "allocation"}, + Flag: exposureFlag{Key: "flag"}, + Variant: exposureVariant{Key: "on"}, + Subject: exposureSubject{ID: "subject"}, + } + entered := make(chan struct{}, 2) + release := make(chan struct{}) + results := make(chan bool, 2) + attributes := func() map[string]any { + entered <- struct{}{} + <-release + return map[string]any{"detached": true} + } + + var wg sync.WaitGroup + for range 2 { + wg.Go(func() { + added, known := writer.appendWithDecisionAndAttributes(event, attributes) + results <- added && known + }) + } + <-entered + <-entered + close(release) + wg.Wait() + close(results) + + added := 0 + for result := range results { + if result { + added++ + } + } + if added != 1 { + t.Fatalf("successful concurrent appends = %d, want 1", added) + } + if got := len(writer.buffer); got != 1 { + t.Fatalf("buffered concurrent duplicate exposures = %d, want 1", got) + } +} + +func BenchmarkExposureHookWideDependenciesSharedSubject(b *testing.B) { + const dependencyCount = 512 + metadata := wideDependencyExposureMetadata(dependencyCount) + details := wideExposureHookDetails(metadata) + + b.Run("cache_miss", func(b *testing.B) { + calls := 0 + evalCtx := of.NewEvaluationContext("subject", map[string]any{ + "counted": countingExposureStringer{calls: &calls}, + "profile": map[string]any{"tier": "paid"}, + }) + hookCtx := of.NewHookContext( + "root", of.Boolean, false, of.NewClientMetadata(""), + of.Metadata{Name: datadogProviderName}, evalCtx, + ) + b.ReportAllocs() + for b.Loop() { + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, dependencyCount+1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + newExposureHook(writer).Finally(context.Background(), hookCtx, details, of.HookHints{}) + } + b.ReportMetric(float64(calls)/float64(b.N), "context_walks/op") + }) + + b.Run("cache_hit", func(b *testing.B) { + calls := 0 + evalCtx := of.NewEvaluationContext("subject", map[string]any{ + "counted": countingExposureStringer{calls: &calls}, + "profile": map[string]any{"tier": "paid"}, + }) + hookCtx := of.NewHookContext( + "root", of.Boolean, false, of.NewClientMetadata(""), + of.Metadata{Name: datadogProviderName}, evalCtx, + ) + writer := &exposureWriter{ + datadogLoggingEnabled: true, + buffer: make([]exposureEvent, 0, dependencyCount+1), + cache: newExposureLRUCache(defaultExposureCacheCapacity), + } + hook := newExposureHook(writer) + hook.Finally(context.Background(), hookCtx, details, of.HookHints{}) + calls = 0 + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + hook.Finally(context.Background(), hookCtx, details, of.HookHints{}) + } + b.ReportMetric(float64(calls)/float64(b.N), "context_walks/op") + }) +} + // TestExposureWriter_FlushReportsEventsStrandedByStop pins that flush reports // events left in a stopped writer's buffer as undelivered, not as nothing // pending, so shutdown does not drop them silently. diff --git a/openfeature/ffe-system-test-data b/openfeature/ffe-system-test-data index c8cc8da2393..ba0f36eb6dd 160000 --- a/openfeature/ffe-system-test-data +++ b/openfeature/ffe-system-test-data @@ -1 +1 @@ -Subproject commit c8cc8da239341748dc8c30c2145c0f0b5432c958 +Subproject commit ba0f36eb6ddd20483bf79759baedd7e6b67fc791 diff --git a/openfeature/flag_selection_test.go b/openfeature/flag_selection_test.go index 9b28d1801f5..775bc1c7320 100644 --- a/openfeature/flag_selection_test.go +++ b/openfeature/flag_selection_test.go @@ -239,6 +239,30 @@ func TestRequestURLWithFlagSelection_WholeURLLimit(t *testing.T) { assert.True(t, flagSelectionReportedFor(flagSelectionDroppedMetric, "too_many_values")) } +func TestAgentlessSource_FlagSelectionLimitIncludesCapabilities(t *testing.T) { + resetFlagSelectionReports(t) + + const base = "https://example.test/" + capability := "?cap_dependent-flags-variant-key=v1" + selectionParameter := "&selected_flag_tags=" + padding := flagSelectionMaxURLBytes - len(base) - len(capability) - len(selectionParameter) - len("t") + endpoint := base + strings.Repeat("p", padding) + + atLimit, err := newAgentlessSource(internalffe.Settings{AgentlessBaseURL: endpoint}, &FlagSelection{Tags: []string{"t"}}, func(*universalFlagsConfiguration) {}) + require.NoError(t, err) + assert.True(t, atLimit.selectionSent) + assert.Len(t, atLimit.endpoint, flagSelectionMaxURLBytes) + assert.Contains(t, atLimit.endpoint, capability) + assert.Contains(t, atLimit.endpoint, selectionParameter+"t") + + overLimit, err := newAgentlessSource(internalffe.Settings{AgentlessBaseURL: endpoint}, &FlagSelection{Tags: []string{"tt"}}, func(*universalFlagsConfiguration) {}) + require.NoError(t, err) + assert.False(t, overLimit.selectionSent) + assert.LessOrEqual(t, len(overLimit.endpoint), flagSelectionMaxURLBytes) + assert.Contains(t, overLimit.endpoint, capability) + assert.NotContains(t, overLimit.endpoint, "selected_flag_tags") +} + func TestCanonicalizeFlagSelection_InvalidUTF8IsMalformed(t *testing.T) { for name, selection := range map[string]FlagSelection{ "tag": {Tags: []string{"mobile", "\xff"}}, @@ -490,7 +514,16 @@ func (b *selectionBackend) handle(w http.ResponseWriter, r *http.Request) { func (b *selectionBackend) requests() (rawQueries, paths, ifNoneMatch []string) { b.mu.Lock() defer b.mu.Unlock() - return slices.Clone(b.rawQueries), slices.Clone(b.paths), slices.Clone(b.ifNoneMatch) + rawQueries = slices.Clone(b.rawQueries) + capability := url.QueryEscape(internalffe.DependentFlagsVariantKeyQueryParameter) + "=" + url.QueryEscape(internalffe.DependentFlagsVariantKeyQueryVersion) + for i, rawQuery := range rawQueries { + if rawQuery == capability { + rawQueries[i] = "" + continue + } + rawQueries[i] = strings.TrimPrefix(rawQuery, capability+"&") + } + return rawQueries, slices.Clone(b.paths), slices.Clone(b.ifNoneMatch) } func newSelectionSource(t *testing.T, baseURL string, selection *FlagSelection, apply func(*universalFlagsConfiguration)) *agentlessSource { @@ -541,9 +574,12 @@ func TestAgentlessSource_NoFlagSelectionLeavesTheRequestUnchanged(t *testing.T) backend := newSelectionBackend(t, selectionResponse{status: http.StatusOK, ignored: new("invalid_tag")}) plain, err := buildAgentlessEndpoint(backend.server.URL+"/rules?dd_env=test", "", "", "") require.NoError(t, err) + plainURL, err := url.Parse(plain.url) + require.NoError(t, err) + addEvaluatorCapabilities(plainURL, internalffe.EvaluatorCapabilities()) src := newSelectionSource(t, backend.server.URL+"/rules?dd_env=test", selection, nil) - assert.Equal(t, plain.url, src.endpoint) + assert.Equal(t, plainURL.String(), src.endpoint) outcome, _ := src.pollOnce(1) require.Equal(t, pollOutcomeSuccess, outcome) diff --git a/openfeature/flageval_logging.go b/openfeature/flageval_logging.go index 0429656e047..30d0d4011ea 100644 --- a/openfeature/flageval_logging.go +++ b/openfeature/flageval_logging.go @@ -358,6 +358,31 @@ type evalDetails struct { observeFullEvaluationData bool } +// dependencyEvaluationLoggingBatch holds the caller context only for the +// synchronous prerequisite-publication loop. Its bounded, detached snapshot is +// created lazily after the first record passes writer admission and then shared +// read-only by the admitted records in this root batch. +type dependencyEvaluationLoggingBatch struct { + targetingKey string + flatCtx of.FlattenedContext + contextAttrs map[string]any + truncReasons []string + snapshotReady bool +} + +func newDependencyEvaluationLoggingBatch(flatCtx of.FlattenedContext) dependencyEvaluationLoggingBatch { + targetingKey, _ := flatCtx[of.TargetingKey].(string) + return dependencyEvaluationLoggingBatch{targetingKey: targetingKey, flatCtx: flatCtx} +} + +func (b *dependencyEvaluationLoggingBatch) snapshot() (map[string]any, []string) { + if !b.snapshotReady { + b.contextAttrs, b.truncReasons = flattenAndPruneContextExcluding(b.flatCtx, of.TargetingKey) + b.snapshotReady = true + } + return b.contextAttrs, b.truncReasons +} + // newFlagEvalLoggingWriter creates a new flag evaluation writer. func newFlagEvalLoggingWriter(config ProviderConfig) *flagEvalLoggingWriter { return newFlagEvalLoggingWriterWithEVP(config, newEVPClient()) @@ -659,24 +684,10 @@ func baseFlagEvalLoggingEvent(flagKey string, e *evaluationEntry, flushTimeMs in // full check ever fires. Non-blocking on enqueue; failure paths bump split counters so an // undersized cap surfaces as pre-queue overflow rather than getting hidden in a race counter. func (w *flagEvalLoggingWriter) record(hookContext of.HookContext, details of.InterfaceEvaluationDetails) { - w.enqueueMu.RLock() - defer w.enqueueMu.RUnlock() - - // Post-stop no-op: after stop() the worker no longer drains w.events, so enqueuing would - // silently lose the event. Check the atomic gate lock-free (reading under the aggregator - // lock would add hot-path contention) and count the event as a closed drop (distinct from - // queue-overflow) so shutdown loss stays observable with its own reason tag. - if w.stopped.Load() { - w.closedDrop.Add(1) - return - } - if len(w.events) == cap(w.events) { - // Queue full at hook time — O(1) drop, no copy work. This is the hot signal for an - // undersized cap. Counted separately from the racy send-site loss below so the two - // causes stay distinguishable. - w.preQueueOverflow.Add(1) + if !w.admitContextSnapshot() { return } + d := extractEvalDetails(hookContext, details) evaluationTimeMs := d.evalTimeMs if evaluationTimeMs == 0 { @@ -689,13 +700,49 @@ func (w *flagEvalLoggingWriter) record(hookContext of.HookContext, details of.In if d.observeFullEvaluationData { // Bound the context ON THE EVALUATION THREAD, before the async queue. The worker // then only ever sees the pruned snapshot, and the caller's context reference is - // released as soon as record() returns. + // released as soon as record() returns. Application String methods run without + // enqueueMu held so they can safely re-enter evaluation while stop is pending. attrs, truncReasons := flattenAndPruneContext(hookContext.EvaluationContext().Attributes()) ev.contextAttrs = attrs for _, reason := range truncReasons { w.incContextTruncated(reason) } } + w.enqueueAfterSnapshot(ev) +} + +// admitContextSnapshot rejects work that is already known to be undeliverable +// before walking caller context. The lock is released before application String +// methods can run; enqueueAfterSnapshot performs the stop-safe final admission. +func (w *flagEvalLoggingWriter) admitContextSnapshot() bool { + w.enqueueMu.RLock() + defer w.enqueueMu.RUnlock() + + // Post-stop no-op: after stop() the worker no longer drains w.events, so enqueuing would + // silently lose the event. Check the atomic gate lock-free (reading under the aggregator + // lock would add hot-path contention) and count the event as a closed drop (distinct from + // queue-overflow) so shutdown loss stays observable with its own reason tag. + if w.stopped.Load() { + w.closedDrop.Add(1) + return false + } + if len(w.events) == cap(w.events) { + // Queue full at hook time — O(1) drop, no copy work. This is the hot signal for an + // undersized cap. Counted separately from the racy send-site loss below so the two + // causes stay distinguishable. + w.preQueueOverflow.Add(1) + return false + } + return true +} + +func (w *flagEvalLoggingWriter) enqueueAfterSnapshot(ev evalEvent) { + w.enqueueMu.RLock() + defer w.enqueueMu.RUnlock() + if w.stopped.Load() { + w.closedDrop.Add(1) + return + } select { case w.events <- ev: default: @@ -703,6 +750,33 @@ func (w *flagEvalLoggingWriter) record(hookContext of.HookContext, details of.In } } +// recordDependency admits a prerequisite record before touching its caller +// context. Admitted records share one bounded, detached context snapshot for +// the root batch; truncation counters still advance once per admitted record, +// matching record's per-event semantics. +func (w *flagEvalLoggingWriter) recordDependency( + batch *dependencyEvaluationLoggingBatch, + flagKey string, + details of.InterfaceEvaluationDetails, +) { + if !w.admitContextSnapshot() { + return + } + d := extractEvalDetailsFor(flagKey, batch.targetingKey, details) + evaluationTimeMs := d.evalTimeMs + if evaluationTimeMs == 0 { + evaluationTimeMs = time.Now().UnixMilli() + } + ev := evalEvent{d: d, evaluationTimeMs: evaluationTimeMs} + if d.observeFullEvaluationData { + ev.contextAttrs, _ = batch.snapshot() + for _, reason := range batch.truncReasons { + w.incContextTruncated(reason) + } + } + w.enqueueAfterSnapshot(ev) +} + // aggregate updates the aggregator. It runs only on the writer's single worker goroutine. // The caller's context has already been pruned on the evaluation thread (or omitted under // consent-off), so nothing else needs to happen to bound the queue's memory footprint here. @@ -762,21 +836,38 @@ func (w *flagEvalLoggingWriter) incContextTruncated(reason string) { // reviewer's recommendation and avoids the O(K log K) sort-then-trim that made the prior // implementation proportional to the caller's input. func flattenAndPruneContext(attrs map[string]any) (map[string]any, []string) { + return flattenAndPruneContextBounded(attrs, "", false) +} + +func flattenAndPruneContextExcluding(attrs map[string]any, excludedKey string) (map[string]any, []string) { + return flattenAndPruneContextBounded(attrs, excludedKey, true) +} + +func flattenAndPruneContextBounded(attrs map[string]any, excludedKey string, exclude bool) (map[string]any, []string) { if len(attrs) == 0 { return nil, nil } + fieldCount := len(attrs) + if exclude { + if _, exists := attrs[excludedKey]; exists { + fieldCount-- + } + } // Omit the entire context when the top-level map itself exceeds the field cap, so the // evaluation-thread cost is bounded by the cap rather than by the supplied width. Sorting // every key only to keep the first ≤256 would be O(K log K) in K. - if len(attrs) > maxContextFields { + if fieldCount > maxContextFields { return nil, []string{truncReasonMaxContextFields} } // Sort top-level keys so the field-count cap keeps a deterministic subset. Without this, // Go's randomized map iteration would keep a different 256-field subset each call and // fragment aggregation buckets. The sort is bounded to ≤ maxContextFields keys by the // check above. - keys := make([]string, 0, len(attrs)) + keys := make([]string, 0, fieldCount) for k := range attrs { + if exclude && k == excludedKey { + continue + } keys = append(keys, k) } sort.Strings(keys) @@ -1454,9 +1545,17 @@ func pruneContext(raw map[string]any) map[string]any { } // extractEvalDetails extracts EVP-relevant fields from hook context and evaluation details. -// This helper is used only by flagEvalLoggingHook — it does NOT replace the extraction in -// flageval_metrics.go (that file is left untouched to preserve the OTel path). +// The field-based helper also serves returned prerequisite batches; neither replaces the +// extraction in flageval_metrics.go (that file is left untouched to preserve the OTel path). func extractEvalDetails(hookContext of.HookContext, details of.InterfaceEvaluationDetails) evalDetails { + return extractEvalDetailsFor( + hookContext.FlagKey(), + hookContext.EvaluationContext().TargetingKey(), + details, + ) +} + +func extractEvalDetailsFor(flagKey, targetingKey string, details of.InterfaceEvaluationDetails) evalDetails { allocationKey, _ := details.FlagMetadata[metadataAllocationKey].(string) evalTimeMs, _ := details.FlagMetadata[metadataEvalTimeKey].(int64) environmentID, _ := details.FlagMetadata[metadataEnvironmentIDKey].(string) @@ -1483,10 +1582,10 @@ func extractEvalDetails(hookContext of.HookContext, details of.InterfaceEvaluati } return evalDetails{ environment: environment{ID: environmentID, Name: environmentName}, - flagKey: hookContext.FlagKey(), + flagKey: flagKey, variant: details.Variant, allocationKey: allocationKey, - targetingKey: hookContext.EvaluationContext().TargetingKey(), + targetingKey: targetingKey, errorMessage: errMsg, runtimeDefault: isRuntimeDefault(details), evalTimeMs: evalTimeMs, diff --git a/openfeature/flageval_logging_hook_test.go b/openfeature/flageval_logging_hook_test.go index 8eaa59564c6..7bad0abcaeb 100644 --- a/openfeature/flageval_logging_hook_test.go +++ b/openfeature/flageval_logging_hook_test.go @@ -7,6 +7,7 @@ package openfeature import ( "context" + "runtime" "testing" "time" @@ -68,6 +69,15 @@ func (panicStringer) String() string { panic("String must not be called when the queue is already full") } +type callbackFlagEvalStringer struct { + callback func() +} + +func (s callbackFlagEvalStringer) String() string { + s.callback() + return "reentered" +} + // TestIsRuntimeDefault verifies the runtime-default detection rule. // Signal: absent variant key. Our evaluator sets a variant ONLY on a matched // allocation (TARGETING_MATCH/SPLIT/STATIC); every DEFAULT/DISABLED/ERROR path @@ -350,3 +360,58 @@ func TestFlagEvaluationBackpressureDropsBeforeContextSnapshot(t *testing.T) { t.Fatalf("full queue length changed: got %d, want %d", got, cap(w.events)) } } + +func TestFlagEvaluationStringerCanReenterWhileStopIsPending(t *testing.T) { + w := setupTestWriter(t) + details := makeEvalDetails("on", of.TargetingMatchReason, "", of.FlagMetadata{ + metadataObserveFullEvaluationDataKey: true, + }) + inner := makeHookContext("inner", "subject", nil) + stopDone := make(chan struct{}) + outer := makeHookContext("outer", "subject", map[string]any{ + "reentrant": callbackFlagEvalStringer{callback: func() { + go func() { + defer close(stopDone) + w.stop() + }() + // Wait until stop either completes (the safe path) or its writer + // lock prevents a new reader. In the old lock scope, the latter + // made the recursive record wait behind stop while the outer + // record still held the read lock: a three-way deadlock. + for { + select { + case <-stopDone: + w.record(inner, details) + return + default: + } + if !w.enqueueMu.TryRLock() { + break + } + w.enqueueMu.RUnlock() + runtime.Gosched() + } + w.record(inner, details) + }}, + }) + + outerDone := make(chan struct{}) + go func() { + defer close(outerDone) + w.record(outer, details) + }() + + for name, done := range map[string]<-chan struct{}{ + "reentrant evaluation": outerDone, + "writer stop": stopDone, + } { + select { + case <-done: + case <-time.After(time.Second): + t.Fatalf("%s deadlocked", name) + } + } + if got := len(w.events); got != 0 { + t.Fatalf("events queued after stop = %d, want 0", got) + } +} diff --git a/openfeature/flageval_logging_test.go b/openfeature/flageval_logging_test.go index 1fdc3d6b26d..12643e770cf 100644 --- a/openfeature/flageval_logging_test.go +++ b/openfeature/flageval_logging_test.go @@ -1097,6 +1097,114 @@ func TestRecordAfterStopIsNoop(t *testing.T) { } } +func TestDependencyLoggingSnapshotsContextAfterAdmission(t *testing.T) { + details := of.InterfaceEvaluationDetails{ + Value: true, + EvaluationDetails: of.EvaluationDetails{ + FlagKey: "dependency", + FlagType: of.Boolean, + ResolutionDetail: of.ResolutionDetail{ + Variant: "on", + Reason: of.TargetingMatchReason, + FlagMetadata: of.FlagMetadata{ + metadataObserveFullEvaluationDataKey: true, + }, + }, + }, + } + + t.Run("full queue skips snapshot", func(t *testing.T) { + flatCtx := make(of.FlattenedContext, maxContextFields+2) + flatCtx[of.TargetingKey] = "subject" + for i := 0; i <= maxContextFields; i++ { + flatCtx[fmt.Sprintf("field-%03d", i)] = i + } + batch := newDependencyEvaluationLoggingBatch(flatCtx) + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.events = make(chan evalEvent, 1) + w.events <- evalEvent{} + + w.recordDependency(&batch, "dependency", details) + + if batch.snapshotReady { + t.Fatal("full queue must reject the record before walking the caller context") + } + if got := w.preQueueOverflow.Load(); got != 1 { + t.Fatalf("preQueueOverflow = %d, want 1", got) + } + }) + + t.Run("stopped writer skips snapshot", func(t *testing.T) { + flatCtx := of.FlattenedContext{ + of.TargetingKey: "subject", + "country": "CA", + } + batch := newDependencyEvaluationLoggingBatch(flatCtx) + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.stopped.Store(true) + + w.recordDependency(&batch, "dependency", details) + + if batch.snapshotReady { + t.Fatal("stopped writer must reject the record before walking the caller context") + } + if got := w.closedDrop.Load(); got != 1 { + t.Fatalf("closedDrop = %d, want 1", got) + } + }) + + t.Run("batch shares bounded detached snapshot", func(t *testing.T) { + flatCtx := make(of.FlattenedContext, maxContextFields+1) + flatCtx[of.TargetingKey] = "subject" + for i := range maxContextFields { + flatCtx[fmt.Sprintf("field-%03d", i)] = i + } + batch := newDependencyEvaluationLoggingBatch(flatCtx) + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.events = make(chan evalEvent, 2) + + w.recordDependency(&batch, "dependency-a", details) + flatCtx["field-000"] = "caller mutation" + w.recordDependency(&batch, "dependency-b", details) + + if !batch.snapshotReady { + t.Fatal("admitted consented record must create a bounded snapshot") + } + first, second := <-w.events, <-w.events + if got := len(first.contextAttrs); got != maxContextFields { + t.Fatalf("first context fields = %d, want %d", got, maxContextFields) + } + if got := first.contextAttrs["field-000"]; got != 0 { + t.Fatalf("snapshot retained caller mutation: got %#v, want 0", got) + } + if got := second.contextAttrs["field-000"]; got != 0 { + t.Fatalf("shared snapshot retained caller mutation: got %#v, want 0", got) + } + }) + + t.Run("truncation counter remains per admitted record", func(t *testing.T) { + flatCtx := make(of.FlattenedContext, maxContextFields+2) + flatCtx[of.TargetingKey] = "subject" + for i := 0; i <= maxContextFields; i++ { + flatCtx[fmt.Sprintf("field-%03d", i)] = i + } + batch := newDependencyEvaluationLoggingBatch(flatCtx) + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.events = make(chan evalEvent, 2) + + w.recordDependency(&batch, "dependency-a", details) + w.recordDependency(&batch, "dependency-b", details) + + counter, ok := w.contextTruncatedByReason.Load(truncReasonMaxContextFields) + if !ok || counter.(*atomic.Int64).Load() != 2 { + t.Fatalf("max-field truncation count = %v, want 2", counter) + } + if first, second := <-w.events, <-w.events; first.contextAttrs != nil || second.contextAttrs != nil { + t.Fatal("oversized contexts must be omitted from every queued record") + } + }) +} + // TestBuildFlagEvalPayloads covers the size-bounded payload splitter (the Go mirror of // Java's FlagEvaluationPayloads.buildPayloads): small flushes produce one payload, a flush // over payloadSizeLimitBytes is split into multiple payloads, a single oversized event is diff --git a/openfeature/flageval_pii_test.go b/openfeature/flageval_pii_test.go index 47a9a9bc3c9..3ff25b6d472 100644 --- a/openfeature/flageval_pii_test.go +++ b/openfeature/flageval_pii_test.go @@ -225,7 +225,7 @@ func TestProviderStampsConsentFromEvaluatedConfig(t *testing.T) { res := p.evaluate(context.Background(), "pii-flag", "fallback", of.FlattenedContext{ of.TargetingKey: piiCanonicalTargetingKey, - }) + }, "") got, ok := res.Metadata[metadataObserveFullEvaluationDataKey] if !ok { @@ -242,7 +242,7 @@ func TestProviderStampsConsentFromEvaluatedConfig(t *testing.T) { res := p.evaluate(context.Background(), "no-such-flag", "fallback", of.FlattenedContext{ of.TargetingKey: piiCanonicalTargetingKey, - }) + }, "") if res.Metadata[metadataObserveFullEvaluationDataKey] != true { t.Errorf("FLAG_NOT_FOUND must still carry consent, got %v", res.Metadata) } @@ -600,7 +600,7 @@ func TestConsentIsNotReReadAfterEvaluation(t *testing.T) { // provider would. res := p.evaluate(context.Background(), "pii-flag", "fallback", of.FlattenedContext{ of.TargetingKey: piiCanonicalTargetingKey, - }) + }, "") hookCtx := makeHookContext("pii-flag", piiCanonicalTargetingKey, map[string]any{"plan": "enterprise"}) details := makeEvalDetails(res.VariantKey, res.Reason, "", of.FlagMetadata(res.Metadata)) w.record(hookCtx, details) diff --git a/openfeature/provider.go b/openfeature/provider.go index a745798307d..90934f768e4 100644 --- a/openfeature/provider.go +++ b/openfeature/provider.go @@ -9,6 +9,7 @@ import ( "context" "errors" "fmt" + "math" "slices" "sync" "sync/atomic" @@ -96,11 +97,16 @@ type ProviderConfig struct { // using configuration received from Datadog, either via Remote Config or // Agentless polling depending on the resolved delivery source. type DatadogProvider struct { - experimentationOptOutMode ExperimentationOptOutMode + experimentationOptOutMode ExperimentationOptOutMode + evaluationTelemetryOptOutEnabled bool mu sync.RWMutex configuration *universalFlagsConfiguration - metadata openfeature.Metadata + // dependencyEvaluatorState resolves evaluator options lazily and at most + // once for the current immutable configuration. It is replaced together + // with configuration under mu. // +checklocks:mu + dependencyEvaluatorState *dependencyEvaluatorState + metadata openfeature.Metadata // configChange is closed and replaced with a fresh channel each time // updateConfiguration runs, so a waiter that reads it while p.mu is held @@ -130,9 +136,14 @@ type DatadogProvider struct { // rawDataWarned records that this provider warned that debug logs include // raw evaluation data. See warnRawDebugData. rawDataWarned *atomic.Bool + // dependencyPublisherPanicWarned deduplicates the best-effort telemetry warning. + dependencyPublisherPanicWarned atomic.Bool // source is fixed at construction. // +checklocks:mu source internalffe.Source + // remoteConfigToken identifies this provider's slow-path subscription or + // fast-path callback attachment. Zero means it owns neither. // +checklocks:mu + remoteConfigToken internalffe.ProviderToken // agentless stays nil unless tryRegisterAgentless registered a poller. // +checklocks:mu agentless *agentlessSource // shutdownCalled reports whether ShutdownWithContext has already run. // +checklocks:mu @@ -222,13 +233,23 @@ func newEvaluator(domain string) (internalffe.Evaluator, error) { } client = openfeature.NewClient(domain) } + return newAnyEvaluator(client), nil +} + +// anyEvaluationDefault marks the internal UFC adapter's type-agnostic path. +// It is intentionally private so public ObjectValueDetails calls always request +// a JSON flag. Its map representation also keeps the OpenFeature hook default +// value equivalent to the empty object used before this distinction existed. +type anyEvaluationDefault map[string]any + +func newAnyEvaluator(client *openfeature.Client) internalffe.Evaluator { return func(ctx context.Context, key, targetingKey string, attributes map[string]any) (any, error) { if err := waitForProvider(ctx, client); err != nil { return nil, err } - details, err := client.ObjectValueDetails(ctx, key, map[string]any{}, openfeature.NewEvaluationContext(targetingKey, attributes)) + details, err := client.ObjectValueDetails(ctx, key, anyEvaluationDefault{}, openfeature.NewEvaluationContext(targetingKey, attributes)) return details.Value, err - }, nil + } } func waitForProvider(ctx context.Context, client *openfeature.Client) error { @@ -349,7 +370,8 @@ func newDatadogProviderWithSourceAndEVP( hooks = append(hooks, newDebugLoggingHook(rawDataWarned)) p := &DatadogProvider{ - experimentationOptOutMode: config.ExperimentationOptOutMode, + experimentationOptOutMode: config.ExperimentationOptOutMode, + evaluationTelemetryOptOutEnabled: telemetryOptOutEnabled, metadata: openfeature.Metadata{ Name: datadogProviderName, }, @@ -437,6 +459,11 @@ func (p *DatadogProvider) setConfiguration(config *universalFlagsConfiguration) return readinessUnchanged } p.configuration = config + if config == nil { + p.dependencyEvaluatorState = nil + } else { + p.dependencyEvaluatorState = new(dependencyEvaluatorState) + } // Wake every waiter blocked on the current generation, then start a fresh // one for the next update: a closed channel cannot be reused as a signal. // configChange is nil on a DatadogProvider built as a bare struct literal @@ -470,6 +497,12 @@ func (p *DatadogProvider) getConfiguration() *universalFlagsConfiguration { return p.configuration } +func (p *DatadogProvider) getEvaluationConfiguration() (*universalFlagsConfiguration, *dependencyEvaluatorState) { + p.mu.RLock() + defer p.mu.RUnlock() + return p.configuration, p.dependencyEvaluatorState +} + // Metadata returns provider metadata including the provider name. func (p *DatadogProvider) Metadata() openfeature.Metadata { return p.metadata @@ -613,8 +646,11 @@ func (p *DatadogProvider) ShutdownWithContext(ctx context.Context) error { teardownDone := make(chan struct{}) p.teardownDone = teardownDone source := p.source + remoteConfigToken := p.remoteConfigToken + p.remoteConfigToken = 0 agentless := p.agentless p.configuration = nil + p.dependencyEvaluatorState = nil // Wake any Init parked on the current generation so it observes // shutdownCalled instead of waiting out its timeout. if p.configChange != nil { @@ -633,7 +669,7 @@ func (p *DatadogProvider) ShutdownWithContext(ctx context.Context) error { // An agentless provider never registered an RC capability, so it // must not unregister one. if source == internalffe.SourceRemoteConfig { - err = stopRemoteConfig() + err = stopRemoteConfig(remoteConfigToken) } if agentless != nil { if stopErr := agentless.Stop(ctx); stopErr != nil { @@ -706,7 +742,7 @@ func (p *DatadogProvider) BooleanEvaluation( defaultValue bool, flatCtx openfeature.FlattenedContext, ) openfeature.BoolResolutionDetail { - result := p.evaluate(ctx, flagKey, defaultValue, flatCtx) + result := p.evaluate(ctx, flagKey, defaultValue, flatCtx, valueTypeBoolean) // Convert result to boolean boolValue, ok := result.Value.(bool) @@ -736,7 +772,7 @@ func (p *DatadogProvider) StringEvaluation( defaultValue string, flatCtx openfeature.FlattenedContext, ) openfeature.StringResolutionDetail { - result := p.evaluate(ctx, flagKey, defaultValue, flatCtx) + result := p.evaluate(ctx, flagKey, defaultValue, flatCtx, valueTypeString) // Convert result to string strValue, ok := result.Value.(string) @@ -766,7 +802,7 @@ func (p *DatadogProvider) FloatEvaluation( defaultValue float64, flatCtx openfeature.FlattenedContext, ) openfeature.FloatResolutionDetail { - result := p.evaluate(ctx, flagKey, defaultValue, flatCtx) + result := p.evaluate(ctx, flagKey, defaultValue, flatCtx, valueTypeNumeric) // Convert result to float64 var floatValue float64 @@ -778,9 +814,9 @@ func (p *DatadogProvider) FloatEvaluation( case float32: floatValue = float64(v) case int: - floatValue = float64(v) + floatValue, conversionErr = exactFloat(flagKey, int64(v)) case int64: - floatValue = float64(v) + floatValue, conversionErr = exactFloat(flagKey, v) case int32: floatValue = float64(v) default: @@ -793,6 +829,8 @@ func (p *DatadogProvider) FloatEvaluation( if conversionErr != nil { result.Error = conversionErr + result.Reason = openfeature.ErrorReason + floatValue = defaultValue } detail := openfeature.FloatResolutionDetail{ @@ -815,7 +853,7 @@ func (p *DatadogProvider) IntEvaluation( defaultValue int64, flatCtx openfeature.FlattenedContext, ) openfeature.IntResolutionDetail { - result := p.evaluate(ctx, flagKey, defaultValue, flatCtx) + result := p.evaluate(ctx, flagKey, defaultValue, flatCtx, valueTypeInteger) // Convert result to int64 var intValue int64 @@ -833,11 +871,11 @@ func (p *DatadogProvider) IntEvaluation( case int8: intValue = int64(v) case float64: - // Accept float64 if it's a whole number (e.g., -5.0 → -5) - if v == float64(int64(v)) { + // Accept a whole number in int64 range (e.g., -5.0 → -5); reject lossy reads. + if v == math.Trunc(v) && v >= -(1<<63) && v < 1<<63 { intValue = int64(v) } else { - conversionErr = fmt.Errorf("%w: flag %q returned float with decimal part: %v", errTypeMismatch, flagKey, v) + conversionErr = fmt.Errorf("%w: flag %q returned a value that is not a whole int64: %v", errTypeMismatch, flagKey, v) } default: if result.Error == nil { @@ -849,6 +887,8 @@ func (p *DatadogProvider) IntEvaluation( if conversionErr != nil { result.Error = conversionErr + result.Reason = openfeature.ErrorReason + intValue = defaultValue } detail := openfeature.IntResolutionDetail{ @@ -871,7 +911,12 @@ func (p *DatadogProvider) ObjectEvaluation( defaultValue any, flatCtx openfeature.FlattenedContext, ) openfeature.InterfaceResolutionDetail { - result := p.evaluate(ctx, flagKey, defaultValue, flatCtx) + var result evaluationResult + if internalDefault, ok := defaultValue.(anyEvaluationDefault); ok { + result = p.evaluateAny(ctx, flagKey, map[string]any(internalDefault), flatCtx) + } else { + result = p.evaluate(ctx, flagKey, defaultValue, flatCtx, valueTypeJSON) + } detail := openfeature.InterfaceResolutionDetail{ Value: result.Value, @@ -886,6 +931,17 @@ func (p *DatadogProvider) ObjectEvaluation( return detail } +// evaluateAny is the private type-agnostic entrypoint used by the internal UFC +// adapter. Public OpenFeature object evaluation requires a JSON flag. +func (p *DatadogProvider) evaluateAny( + ctx context.Context, + flagKey string, + defaultValue any, + flatCtx openfeature.FlattenedContext, +) evaluationResult { + return p.evaluate(ctx, flagKey, defaultValue, flatCtx, "") +} + // Hooks returns hooks for one evaluation. func (p *DatadogProvider) Hooks() []openfeature.Hook { // TODO(open-feature/go-sdk#623): Return the shared hooks when go.mod requires @@ -909,6 +965,7 @@ func (p *DatadogProvider) evaluate( flagKey string, defaultValue any, flatCtx openfeature.FlattenedContext, + requestedType valueType, ) (res evaluationResult) { // Capture the evaluation time once, at evaluation entry. It is used for allocation // time-window checks and EVP first/last evaluation bounds. @@ -941,7 +998,7 @@ func (p *DatadogProvider) evaluate( default: } - config := p.getConfiguration() + config, dependencyEvaluatorState := p.getEvaluationConfiguration() // Check if configuration is loaded if config == nil { @@ -963,8 +1020,159 @@ func (p *DatadogProvider) evaluate( return evaluationResult{Value: defaultValue, Reason: openfeature.ErrorReason, Error: err} } - // Evaluate the flag, sharing the eval-time captured at entry. - return evaluateConfiguredFlag(config, flagKey, defaultValue, flatCtx, evalNow, exclusion) + // A malformed root activation is a configuration error in future-only mode, + // so it takes precedence over a caller type mismatch without traversing the + // dependency graph. + rootFlag, rootExists := config.Flags[flagKey] + if rootExists && + exclusion.mode == ExperimentationOptOutFutureExperimentsOnly && rootFlag.invalidActivation { + return evaluationResult{ + Value: defaultValue, + Reason: openfeature.ErrorReason, + Error: fmt.Errorf("%w: invalid randomizationActivatedAt for flag %q", errParseError, flagKey), + } + } + + // Reject a requested type that is incompatible with the configured root before + // traversing its dependency graph. Invalid and missing root flags continue + // through the evaluator so they retain their existing error precedence. + if requestedType != "" && rootExists && + !compatibleEvaluationType(rootFlag.VariationType, requestedType) { + return evaluationResult{ + Value: defaultValue, + Reason: openfeature.ErrorReason, + Error: fmt.Errorf("%w: flag %q is configured as %s, not %s", errTypeMismatch, + flagKey, rootFlag.VariationType, requestedType), + } + } + + // Complete the graph before publishing prerequisite telemetry. The evaluator's + // returned batch is detached from its memo and exposure state, and each record + // is cloned again before publication so a failed or mutating publisher cannot + // affect the root result or another record. + res = evaluateConfiguredFlagLookedUpWithState(config, flagKey, rootFlag, rootExists, defaultValue, + flatCtx, evalNow, exclusion, dependencyEvaluatorState) + p.publishDependencyEvaluations(ctx, flatCtx, res.DependencyEvaluations) + res.DependencyEvaluations = nil + return res +} + +// compatibleEvaluationType lets OpenFeature Number reads reach the lossless typed +// conversion while retaining strict checks for non-numeric type pairs. +func compatibleEvaluationType(configuredType, requestedType valueType) bool { + return configuredType == requestedType || + isNumericValueType(configuredType) && isNumericValueType(requestedType) +} + +func isNumericValueType(t valueType) bool { + return t == valueTypeNumeric || t == valueTypeInteger +} + +func exactFloat(flagKey string, value int64) (float64, error) { + converted := float64(value) + if converted >= 1<<63 || int64(converted) != value { + return 0, fmt.Errorf("%w: flag %q value %d is not exactly representable as float64", errTypeMismatch, flagKey, value) + } + return converted, nil +} + +func (p *DatadogProvider) publishDependencyEvaluations( + ctx context.Context, + flatCtx openfeature.FlattenedContext, + records []dependencyEvaluationRecord, +) { + loggingBatch := newDependencyEvaluationLoggingBatch(flatCtx) + dropped := publishDependencyEvaluationBatch(records, func(record dependencyEvaluationRecord) { + p.recordDependencyEvaluation(ctx, record.FlagKey, record.FlagType, + flatCtx, record.Result, &loggingBatch) + }) + p.reportDependencyPublisherPanics(dropped) +} + +func (p *DatadogProvider) reportDependencyPublisherPanics(dropped int64) { + if dropped > 0 { + countMetric(metricFlagEvalDropped, dropped, "publisher_panic") + if p.dependencyPublisherPanicWarned.CompareAndSwap(false, true) { + containLoggerPanic(func() { + log.Warn("openfeature: dependency evaluation publisher panicked; dropped %d evaluation(s) (best-effort telemetry)", dropped) //errtrack:ignore recovered telemetry publisher panic + }) + } + } +} + +func publishDependencyEvaluationBatch(records []dependencyEvaluationRecord, publish func(dependencyEvaluationRecord)) (dropped int64) { + for _, record := range records { + record := dependencyEvaluationRecord{ + FlagKey: record.FlagKey, + FlagType: record.FlagType, + DefaultValue: cloneTelemetryValue(record.DefaultValue), + Result: cloneEvaluationResult(record.Result), + } + func() { + defer func() { + if recover() != nil { + dropped++ + } + }() + publish(record) + }() + } + return dropped +} + +func (p *DatadogProvider) recordDependencyEvaluation( + ctx context.Context, + flagKey string, + flagType valueType, + flatCtx openfeature.FlattenedContext, + result evaluationResult, + loggingBatch *dependencyEvaluationLoggingBatch, +) { + if p.evaluationTelemetryOptOutEnabled { + if optedOut, _ := flatCtx["dd_evaluation_telemetry_opt_out"].(bool); optedOut { + return + } + } + + details := openfeature.InterfaceEvaluationDetails{ + Value: result.Value, + EvaluationDetails: openfeature.EvaluationDetails{ + FlagKey: flagKey, + FlagType: openFeatureType(flagType), + ResolutionDetail: openfeature.ResolutionDetail{ + Variant: result.VariantKey, + Reason: result.Reason, + ErrorCode: errorCodeFor(result.Error), + FlagMetadata: result.Metadata, + }, + }, + } + if result.Error != nil { + details.ErrorMessage = result.Error.Error() + } + if p.flagEvalMetricsHook != nil && p.flagEvalMetricsHook.metrics != nil { + p.flagEvalMetricsHook.metrics.record(ctx, flagKey, details) + } + if p.flagEvalLoggingWriter != nil { + p.flagEvalLoggingWriter.recordDependency(loggingBatch, flagKey, details) + } +} + +func openFeatureType(flagType valueType) openfeature.Type { + switch flagType { + case valueTypeBoolean: + return openfeature.Boolean + case valueTypeString: + return openfeature.String + case valueTypeInteger: + return openfeature.Int + case valueTypeNumeric: + return openfeature.Float + case valueTypeJSON: + return openfeature.Object + default: + return openfeature.Boolean + } } // toResolutionError converts a Go error to an OpenFeature ResolutionError. @@ -975,6 +1183,18 @@ func toResolutionError(err error) openfeature.ResolutionError { } errMsg := err.Error() + if graphErr, ok := errors.AsType[*dependencyGraphError](err); ok { + switch graphErr.code { + case openfeature.FlagNotFoundCode: + return openfeature.NewFlagNotFoundResolutionError(errMsg) + case openfeature.ParseErrorCode: + return openfeature.NewParseErrorResolutionError(errMsg) + case openfeature.TypeMismatchCode: + return openfeature.NewTypeMismatchResolutionError(errMsg) + default: + return openfeature.NewGeneralResolutionError(errMsg) + } + } // Check for wrapped sentinel errors using errors.Is switch { @@ -994,3 +1214,28 @@ func toResolutionError(err error) openfeature.ResolutionError { return openfeature.NewGeneralResolutionError(errMsg) } } + +func errorCodeFor(err error) openfeature.ErrorCode { + if err == nil { + return "" + } + if graphErr, ok := errors.AsType[*dependencyGraphError](err); ok { + return graphErr.code + } + switch { + case errors.Is(err, errFlagNotFound): + return openfeature.FlagNotFoundCode + case errors.Is(err, errTypeMismatch): + return openfeature.TypeMismatchCode + case errors.Is(err, errParseError): + return openfeature.ParseErrorCode + case errors.Is(err, errNoConfiguration): + return openfeature.ProviderNotReadyCode + case errors.Is(err, errTargetingKeyMissing): + return openfeature.TargetingKeyMissingCode + case errors.Is(err, errInvalidContext): + return openfeature.InvalidContextCode + default: + return openfeature.GeneralCode + } +} diff --git a/openfeature/provider_bench_test.go b/openfeature/provider_bench_test.go index 04d26c92965..7f295b0126b 100644 --- a/openfeature/provider_bench_test.go +++ b/openfeature/provider_bench_test.go @@ -122,6 +122,60 @@ func BenchmarkBooleanEvaluationOptOut(b *testing.B) { } } +func BenchmarkDependencyEvaluationLoggingBatch(b *testing.B) { + details := openfeature.InterfaceEvaluationDetails{ + EvaluationDetails: openfeature.EvaluationDetails{ + ResolutionDetail: openfeature.ResolutionDetail{ + Variant: "on", + Reason: openfeature.TargetingMatchReason, + FlagMetadata: openfeature.FlagMetadata{ + metadataObserveFullEvaluationDataKey: true, + }, + }, + }, + } + + b.Run("full_queue_skips_oversized_context", func(b *testing.B) { + flatCtx := make(openfeature.FlattenedContext, maxContextFields+2) + flatCtx[openfeature.TargetingKey] = "user-123" + for i := 0; i <= maxContextFields; i++ { + flatCtx[fmt.Sprintf("field-%03d", i)] = i + } + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.events = make(chan evalEvent, 1) + w.events <- evalEvent{} + b.ReportAllocs() + for b.Loop() { + batch := newDependencyEvaluationLoggingBatch(flatCtx) + w.recordDependency(&batch, "dependency", details) + if batch.snapshotReady { + b.Fatal("full queue unexpectedly copied context") + } + } + }) + + b.Run("eight_dependencies_share_snapshot", func(b *testing.B) { + flatCtx := make(openfeature.FlattenedContext, maxContextFields+1) + flatCtx[openfeature.TargetingKey] = "user-123" + for i := range maxContextFields { + flatCtx[fmt.Sprintf("field-%03d", i)] = i + } + w := newFlagEvalLoggingWriter(ProviderConfig{}) + w.events = make(chan evalEvent, 8) + b.ReportAllocs() + b.ReportMetric(8, "dependencies/op") + for b.Loop() { + batch := newDependencyEvaluationLoggingBatch(flatCtx) + for i := range 8 { + w.recordDependency(&batch, fmt.Sprintf("dependency-%d", i), details) + } + for range 8 { + <-w.events + } + } + }) +} + // BenchmarkStringEvaluation benchmarks string flag evaluation func BenchmarkStringEvaluation(b *testing.B) { provider := newDatadogProvider(ProviderConfig{}) diff --git a/openfeature/rc_subscription.go b/openfeature/rc_subscription.go index 80243978a74..f0a816b62b2 100644 --- a/openfeature/rc_subscription.go +++ b/openfeature/rc_subscription.go @@ -14,5 +14,12 @@ import ( // FFE_FLAGS, it replays any buffered config and returns true. Otherwise // returns false, meaning the caller should fall back to its own RC subscription. func attachProvider(p *DatadogProvider) bool { - return internalffe.AttachCallback(p.rcCallback) + token, attached := internalffe.AttachCallback(p.rcCallback) + if !attached { + return false + } + p.mu.Lock() + p.remoteConfigToken = token + p.mu.Unlock() + return true } diff --git a/openfeature/rc_subscription_test.go b/openfeature/rc_subscription_test.go index c2fbd23e9f5..32eb212f7e5 100644 --- a/openfeature/rc_subscription_test.go +++ b/openfeature/rc_subscription_test.go @@ -6,10 +6,12 @@ package openfeature import ( + "context" "encoding/json" "testing" "time" + rc "github.com/DataDog/datadog-agent/pkg/remoteconfig/state" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -121,9 +123,10 @@ func TestStartWithRemoteConfigFastPath(t *testing.T) { // without touching global remoteconfig state. provider := newDatadogProvider(ProviderConfig{}) cleanupProvider(t, provider) - tracerOwnsSubscription, err := internalffe.SubscribeProvider(provider.rcCallback) + tracerOwnsSubscription, token, err := internalffe.SubscribeProvider(provider.rcCallback) require.NoError(t, err) require.True(t, tracerOwnsSubscription, "SubscribeProvider should report tracer subscribed") + assert.Zero(t, token) // Attach the provider, which replays the buffered config. attached := attachProvider(provider) @@ -154,3 +157,224 @@ func TestStartWithRemoteConfig_ConfiguresAgentEVP(t *testing.T) { assert.Nil(t, evp.directURL) assert.Nil(t, evp.directClient) } + +func TestRemoteConfigSlowPathShutdownRemovesEvaluatorCapabilities(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + + provider, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + + for _, capability := range []remoteconfig.Capability{ + remoteconfig.FFEFlagEvaluation, + remoteconfig.FFEFlagDependentFlagVariantKeyV1, + } { + has, err := remoteconfig.HasCapability(capability) + require.NoError(t, err) + require.True(t, has, "slow-path subscription should register capability %d", capability) + } + + require.NoError(t, provider.ShutdownWithContext(context.Background())) + hasProduct, err := remoteconfig.HasProduct(internalffe.FFEProductName) + require.NoError(t, err) + assert.False(t, hasProduct) + for _, capability := range []remoteconfig.Capability{ + remoteconfig.FFEFlagEvaluation, + remoteconfig.FFEFlagDependentFlagVariantKeyV1, + } { + has, err := remoteconfig.HasCapability(capability) + require.NoError(t, err) + assert.False(t, has, "slow-path shutdown should remove capability %d", capability) + } +} + +func TestRemoteConfigSlowPathShutdownAfterRCRestartWithoutTracerFFESubscription(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + + provider, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + + remoteconfig.Stop() + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + _, err = remoteconfig.Subscribe( + "APM_TRACING", + func(remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { return nil }, + remoteconfig.APMTracingSampleRate, + ) + require.NoError(t, err) + + require.NoError(t, provider.ShutdownWithContext(context.Background())) + has, err := remoteconfig.HasProduct("APM_TRACING") + require.NoError(t, err) + assert.True(t, has, "a stale FFE token must not remove another product") + has, err = remoteconfig.HasProduct(internalffe.FFEProductName) + require.NoError(t, err) + assert.False(t, has, "the replacement client did not select the FFE source") +} + +func TestRemoteConfigSlowPathShutdownAfterRCStop(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + + provider, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + remoteconfig.Stop() + + assert.NoError(t, provider.ShutdownWithContext(context.Background())) +} + +func TestRemoteConfigFastPathShutdownKeepsTracerCapabilities(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + require.NoError(t, internalffe.SubscribeRC()) + provider, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/first": remoteConfigTestPayload(t, "first-flag"), + }) + firstConfig := provider.getConfiguration() + require.NotNil(t, firstConfig) + require.Contains(t, firstConfig.Flags, "first-flag") + + require.NoError(t, provider.ShutdownWithContext(context.Background())) + internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/buffered": remoteConfigTestPayload(t, "buffered-flag"), + }) + assert.Nil(t, provider.getConfiguration(), "stopped provider must not receive buffered updates") + require.NotNil(t, internalffe.GetBufferedForTest(), "update should buffer while no provider is attached") + + replacement, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + bufferedConfig := replacement.getConfiguration() + require.NotNil(t, bufferedConfig) + require.Contains(t, bufferedConfig.Flags, "buffered-flag") + assert.Nil(t, internalffe.GetBufferedForTest(), "replacement should drain the buffered update") + + internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/live": remoteConfigTestPayload(t, "live-flag"), + }) + liveConfig := replacement.getConfiguration() + require.NotNil(t, liveConfig) + require.Contains(t, liveConfig.Flags, "live-flag") + assert.Nil(t, provider.getConfiguration(), "live updates must not reach the stopped provider") + require.NoError(t, replacement.ShutdownWithContext(context.Background())) + + hasProduct, err := remoteconfig.HasProduct(internalffe.FFEProductName) + require.NoError(t, err) + assert.True(t, hasProduct, "provider shutdown must not remove the tracer-owned subscription") + for _, capability := range []remoteconfig.Capability{ + remoteconfig.FFEFlagEvaluation, + remoteconfig.FFEFlagDependentFlagVariantKeyV1, + } { + has, err := remoteconfig.HasCapability(capability) + require.NoError(t, err) + assert.True(t, has, "provider shutdown must keep tracer capability %d", capability) + } +} + +func TestRemoteConfigFastPathReplacementWithoutNewUpdate(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + require.NoError(t, internalffe.SubscribeRC()) + + first, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/ffe": remoteConfigTestPayload(t, "live-flag"), + }) + require.NotNil(t, first.getConfiguration()) + require.NoError(t, first.ShutdownWithContext(context.Background())) + + replacement, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + t.Cleanup(replacement.Shutdown) + config := replacement.getConfiguration() + require.NotNil(t, config, "replacement must be seeded with the last delivered state") + assert.Contains(t, config.Flags, "live-flag") +} + +func TestRemoteConfigFastPathReplacementReplaysOnlyAcknowledgedState(t *testing.T) { + internalffe.ResetForTest() + remoteconfig.Reset() + t.Cleanup(func() { + internalffe.ResetForTest() + remoteconfig.Reset() + }) + require.NoError(t, remoteconfig.Start(remoteconfig.DefaultClientConfig())) + require.NoError(t, internalffe.SubscribeRC()) + + first, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + statuses := internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/ffe": remoteConfigTestPayload(t, "last-good-flag"), + }) + require.Equal(t, rc.ApplyStateAcknowledged, statuses["path/ffe"].State) + require.Contains(t, first.getConfiguration().Flags, "last-good-flag") + + statuses = internalffe.ForwardForTest(remoteconfig.ProductUpdate{ + "path/ffe": []byte(`{"flags":`), + }) + require.Equal(t, rc.ApplyStateError, statuses["path/ffe"].State) + require.Contains(t, first.getConfiguration().Flags, "last-good-flag", + "a rejected update must not replace the active configuration") + require.NoError(t, first.ShutdownWithContext(context.Background())) + + replacement, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + require.Contains(t, replacement.getConfiguration().Flags, "last-good-flag", + "replacement must receive the last acknowledged configuration") + statuses = internalffe.ForwardForTest(remoteconfig.ProductUpdate{"path/ffe": nil}) + require.Equal(t, rc.ApplyStateAcknowledged, statuses["path/ffe"].State) + require.Nil(t, replacement.getConfiguration()) + require.NoError(t, replacement.ShutdownWithContext(context.Background())) + + afterRemoval, err := startWithRemoteConfig(ProviderConfig{}) + require.NoError(t, err) + t.Cleanup(afterRemoval.Shutdown) + require.Nil(t, afterRemoval.getConfiguration(), + "an acknowledged removal must also remove the replayable configuration") +} + +func remoteConfigTestPayload(t *testing.T, flagKey string) []byte { + t.Helper() + data, err := json.Marshal(universalFlagsConfiguration{ + Format: "SERVER", + Flags: map[string]*flag{ + flagKey: { + Key: flagKey, + Enabled: true, + VariationType: valueTypeBoolean, + Variations: map[string]*variant{ + "on": {Key: "on", Value: true}, + }, + Allocations: []*allocation{}, + }, + }, + }) + require.NoError(t, err) + return data +} diff --git a/openfeature/remoteconfig.go b/openfeature/remoteconfig.go index 2f5a9ddc1d5..6063fc3af12 100644 --- a/openfeature/remoteconfig.go +++ b/openfeature/remoteconfig.go @@ -32,12 +32,15 @@ func startWithRemoteConfig(config ProviderConfig) (*DatadogProvider, error) { // Subscribe via the internal package, which serializes with tracer subscription // and starts RC only if needed (slow path). - tracerOwnsSubscription, err := internalffe.SubscribeProvider(provider.rcCallback) + tracerOwnsSubscription, token, err := internalffe.SubscribeProvider(provider.rcCallback) if err != nil { return nil, fmt.Errorf("failed to subscribe to Remote Config: %w", err) } if !tracerOwnsSubscription { + provider.mu.Lock() + provider.remoteConfigToken = token + provider.mu.Unlock() log.Debug("openfeature: successfully subscribed to Remote Config updates") return provider, nil } @@ -221,6 +224,24 @@ func validateFlag(flagKey string, flag *flag) error { flagKey, i, condition.Operator) } + hasAttribute := condition.attributePresent || condition.Attribute != "" + hasFlagEvaluation := condition.flagEvaluationPresent || condition.FlagEvaluation != nil + if hasAttribute == hasFlagEvaluation { + return fmt.Errorf("flag %q allocation %d rule condition must define exactly one of attribute or flagEvaluation", flagKey, i) + } + if hasFlagEvaluation { + if condition.FlagEvaluation == nil { + return fmt.Errorf("flag %q allocation %d rule has invalid flag evaluation", flagKey, i) + } + if condition.FlagEvaluation.Key == "" { + return fmt.Errorf("flag %q allocation %d rule has flag evaluation with empty key", flagKey, i) + } + if condition.Operator != operatorOneOf && condition.Operator != operatorNotOneOf { + return fmt.Errorf("flag %q allocation %d rule has flag evaluation with unsupported operator %q", + flagKey, i, condition.Operator) + } + } + switch condition.Operator { case operatorLT, operatorLTE, operatorGT, operatorGTE: if _, ok := internal.ToFloat64(condition.Value); !ok { @@ -238,11 +259,9 @@ func validateFlag(flagKey string, flag *flag) error { flagKey, i, regex, err) } case operatorOneOf, operatorNotOneOf: - if _, ok := condition.Value.([]any); !ok { - if _, ok := condition.Value.([]string); !ok { - return fmt.Errorf("flag %q allocation %d rule has condition with operator %q that requires array value", - flagKey, i, condition.Operator) - } + if !isStringList(condition.Value) { + return fmt.Errorf("flag %q allocation %d rule has condition with operator %q that requires an array of strings", + flagKey, i, condition.Operator) } case operatorIsNull: if _, ok := condition.Value.(bool); !ok { @@ -269,17 +288,32 @@ func validateFlag(flagKey string, flag *flag) error { return nil } +func isStringList(value any) bool { + switch values := value.(type) { + case []string: + return true + case []any: + for _, value := range values { + if _, ok := value.(string); !ok { + return false + } + } + return true + default: + return false + } +} + // stopRemoteConfig unsubscribes from Remote Config updates. // This should be called when shutting down the application or when // the OpenFeature provider is no longer needed. // -// Note: In the slow path, this package discards the subscription token from -// Subscribe(), so we cannot call Unsubscribe(). Instead we unregister the -// capability which stops updates. In the fast path (tracer subscribed), -// the subscription is owned by the tracer. -func stopRemoteConfig() error { +// The internal bridge removes ownership identified by token. This detaches a +// matching fast-path provider callback without removing the tracer-owned +// subscription, or removes a matching slow-path subscription and its exact +// capability set. +func stopRemoteConfig(token internalffe.ProviderToken) error { // Called from the shutdown teardown goroutine. containLoggerPanic(func() { log.Debug("openfeature: unregistered from Remote Config") }) - _ = remoteconfig.UnregisterCapability(remoteconfig.FFEFlagEvaluation) - return nil + return internalffe.UnsubscribeProvider(token) } diff --git a/openfeature/types.go b/openfeature/types.go index 823f0f82f35..e459529bbe6 100644 --- a/openfeature/types.go +++ b/openfeature/types.go @@ -6,7 +6,9 @@ package openfeature import ( + "bytes" "encoding/json" + "errors" "sync" "sync/atomic" "time" @@ -26,6 +28,9 @@ type universalFlagsConfiguration struct { // root, as a sibling of Environment. Plain bool (no omitempty, no pointer) so an absent // or malformed value fails closed to false. ObserveFullEvaluationData bool `json:"observeFullEvaluationData"` + // EvaluatorParams contains optional, extensible evaluator configuration. + // It stays raw so unknown fields survive the configuration lifecycle. + EvaluatorParams json.RawMessage `json:"evaluatorParams,omitempty"` // Flags is a map of feature flag keys to their configurations Flags map[string]*flag `json:"flags"` // invalidFlags contains errors for flags that could not be parsed or validated. @@ -61,6 +66,7 @@ func (config *universalFlagsConfiguration) UnmarshalJSON(data []byte) error { Format string `json:"format"` Environment environment `json:"environment"` ObserveFullEvaluationData json.RawMessage `json:"observeFullEvaluationData"` + EvaluatorParams json.RawMessage `json:"evaluatorParams"` Flags map[string]json.RawMessage `json:"flags"` } if err := json.Unmarshal(data, &raw); err != nil { @@ -73,6 +79,7 @@ func (config *universalFlagsConfiguration) UnmarshalJSON(data []byte) error { // Decoding into a reused object must also discard its previous metadata cache. config.environmentMetadataOnce = sync.Once{} config.ObserveFullEvaluationData = parseLenientBool(raw.ObserveFullEvaluationData) + config.EvaluatorParams = raw.EvaluatorParams config.Flags = make(map[string]*flag, len(raw.Flags)) config.invalidFlags = make(map[string]error) @@ -100,6 +107,151 @@ func (config *universalFlagsConfiguration) UnmarshalJSON(data []byte) error { return nil } +// parseMaxDependencyDepth parses one JSON number without floating-point +// rounding or big-number exponent expansion. It scans O(len(raw)) bytes and +// materializes at most the three integer digits needed for the 0..255 range. +func parseMaxDependencyDepth(raw []byte) (int, bool) { + number := bytes.TrimSpace(raw) + if len(number) == 0 { + return 0, false + } + i := 0 + negative := false + if number[i] == '-' { + negative = true + i++ + if i == len(number) { + return 0, false + } + } + + integerStart := i + switch { + case number[i] == '0': + i++ + case number[i] >= '1' && number[i] <= '9': + for i < len(number) && number[i] >= '0' && number[i] <= '9' { + i++ + } + default: + return 0, false + } + integerEnd := i + + fractionStart, fractionEnd := i, i + if i < len(number) && number[i] == '.' { + i++ + fractionStart = i + for i < len(number) && number[i] >= '0' && number[i] <= '9' { + i++ + } + fractionEnd = i + if fractionStart == fractionEnd { + return 0, false + } + } + + exponent, exponentNegative := 0, false + if i < len(number) && (number[i] == 'e' || number[i] == 'E') { + i++ + if i < len(number) && (number[i] == '+' || number[i] == '-') { + exponentNegative = number[i] == '-' + i++ + } + exponentStart := i + // Saturating at the input length is sufficient: the fraction and + // significand contain fewer digits, so a larger exponent cannot alter + // an in-range decision and never needs to be represented exactly. + limit := len(number) + for i < len(number) && number[i] >= '0' && number[i] <= '9' { + digit := int(number[i] - '0') + if exponent > limit/10 || exponent == limit/10 && digit > limit%10 { + exponent = limit + } else { + exponent = exponent*10 + digit + } + i++ + } + if exponentStart == i { + return 0, false + } + } + if i != len(number) { + return 0, false + } + + totalDigits := integerEnd - integerStart + fractionEnd - fractionStart + leadingZeros, trailingZeros := 0, 0 + nonzero := false + visitDigits := func(visit func(byte) bool) { + for _, bounds := range [][2]int{{integerStart, integerEnd}, {fractionStart, fractionEnd}} { + for j := bounds[0]; j < bounds[1]; j++ { + if !visit(number[j]) { + return + } + } + } + } + visitDigits(func(digit byte) bool { + if !nonzero && digit == '0' { + leadingZeros++ + } + if digit == '0' { + trailingZeros++ + } else { + nonzero = true + trailingZeros = 0 + } + return true + }) + if !nonzero { + return 0, true // Preserve accepted negative and exponentiated zero forms. + } + if negative { + return 0, false + } + + significantDigits := totalDigits - leadingZeros + fractionDigits := fractionEnd - fractionStart + removeTrailing, appendZeros := 0, 0 + if exponentNegative { + if fractionDigits > trailingZeros || exponent > trailingZeros-fractionDigits { + return 0, false + } + removeTrailing = fractionDigits + exponent + } else if exponent < fractionDigits { + removeTrailing = fractionDigits - exponent + if removeTrailing > trailingZeros { + return 0, false + } + } else { + appendZeros = exponent - fractionDigits + } + + keptDigits := significantDigits - removeTrailing + if keptDigits <= 0 || keptDigits > 3 || appendZeros > 3-keptDigits { + return 0, false + } + value, remaining := 0, keptDigits + seenNonzero := false + visitDigits(func(digit byte) bool { + if !seenNonzero && digit == '0' { + return true + } + seenNonzero = true + if remaining == 0 { + return false + } + value = value*10 + int(digit-'0') + remaining-- + return remaining > 0 + }) + for range appendZeros { + value *= 10 + } + return value, value <= maxMaxDependencyDepth +} + // environment represents environment information for the configuration. type environment struct { ID string `json:"id,omitempty"` @@ -262,10 +414,50 @@ type condition struct { // - List operators (ONE_OF, NOT_ONE_OF): []any or []string // - Null check (IS_NULL): bool Value any `json:"value"` + // FlagEvaluation selects another flag's variant key as the condition input. + // It is mutually exclusive with Attribute in authored UFC. + FlagEvaluation *flagEvaluation `json:"flagEvaluation,omitempty"` + attributePresent bool + flagEvaluationPresent bool // semverComparand is the validated, parsed SemVer condition value. semverComparand *parsedSemver } +func (c *condition) UnmarshalJSON(data []byte) error { + type plain condition + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *c = condition(decoded) + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + _, c.attributePresent = fields["attribute"] + _, c.flagEvaluationPresent = fields["flagEvaluation"] + return nil +} + +type flagEvaluation struct { + Key string `json:"key"` +} + +func (evaluation *flagEvaluation) UnmarshalJSON(data []byte) error { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + keyJSON, ok := fields["key"] + if !ok { + return errors.New("flagEvaluation must contain key") + } + if err := json.Unmarshal(keyJSON, &evaluation.Key); err != nil || evaluation.Key == "" { + return errors.New("flagEvaluation.key must be a non-empty string") + } + return nil +} + // split defines how traffic should be distributed for a specific variant. type split struct { // Shards define the traffic segments this split applies to