From 91a209a972fd71043abab2817dc6254d0cb88eb7 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Mon, 9 Nov 2026 10:19:05 +0000 Subject: [PATCH 01/20] feat(core): implement the terminal resolve operator A targeting rule can now end with resolve to select a variant and optionally override the reason and flag metadata. flagd rejects the operator at load unless it is the whole rule or an if/?: result. Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 10 + core/pkg/evaluator/resolve.go | 400 ++++++++++++++++++ core/pkg/evaluator/resolve_test.go | 260 ++++++++++++ .../custom-operations/resolve-operation.md | 76 ++++ docs/reference/flag-definitions.md | 2 + mkdocs.yml | 1 + 6 files changed, 749 insertions(+) create mode 100644 core/pkg/evaluator/resolve.go create mode 100644 core/pkg/evaluator/resolve_test.go create mode 100644 docs/reference/custom-operations/resolve-operation.md diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 95ef96027..1526c324f 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -170,6 +170,7 @@ func NewResolver(store store.IStore, logger *logger.Logger, jsonEvalTracer trace jsonlogic.AddOperator(StartsWithEvaluationName, NewStringComparisonEvaluator(logger).StartsWithEvaluation) jsonlogic.AddOperator(EndsWithEvaluationName, NewStringComparisonEvaluator(logger).EndsWithEvaluation) jsonlogic.AddOperator(SemVerEvaluationName, NewSemVerComparison(logger).SemVerEvaluation) + jsonlogic.AddOperator(ResolveEvaluationName, NewResolveEvaluator(logger).Evaluate) return Resolver{store: store, Logger: logger, tracer: jsonEvalTracer} } @@ -466,6 +467,12 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return flag.DefaultVariant, flag.Variants, model.DefaultReason, metadata, nil } + if variant, reason, metadata, err, handled := je.applyResolveResult( + reqID, flagKey, flag, metadata, trimmed, + ); handled { + return variant, flag.Variants, reason, metadata, err + } + // strip whitespace and quotes from the variant variant = strings.ReplaceAll(trimmed, "\"", "") @@ -584,6 +591,9 @@ func (je *JSON) configToFlagDefinition(config string, definition *Definition) er definition.Flags = flags } je.warnUnsafeNumericVariants(definition) + if err := validateResolveOperators(definition); err != nil { + return err + } return validateDefaultVariants(definition) } diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go new file mode 100644 index 000000000..9829533a6 --- /dev/null +++ b/core/pkg/evaluator/resolve.go @@ -0,0 +1,400 @@ +package evaluator + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/open-feature/flagd/core/pkg/logger" + "github.com/open-feature/flagd/core/pkg/model" + "go.uber.org/zap" +) + +const ( + ResolveEvaluationName = "resolve" + // resolveResultMarker wraps the operator result so evaluateVariant can tell it + // apart from a plain variant string after JsonLogic serializes the rule output. + // The companion key keeps the object multi-key: JsonLogic treats a one-key object + // as an operator call, and if/?: re-applies its result. + resolveResultMarker = "$flagd.resolve" + resolveResultTerminal = "$flagd.resolve.terminal" +) + +// resolveResult is the payload carried under resolveResultMarker. +// A nil Reason keeps TARGETING_MATCH. Error is set when evaluated arguments are malformed. +type resolveResult struct { + Variant string `json:"variant,omitempty"` + Reason *string `json:"reason"` + Metadata map[string]any `json:"metadata,omitempty"` + Error string `json:"error,omitempty"` +} + +// ResolveEvaluator implements the terminal resolve operator. +// It selects a variant and optionally overrides the evaluation reason and metadata. +type ResolveEvaluator struct { + Logger *logger.Logger +} + +func NewResolveEvaluator(log *logger.Logger) *ResolveEvaluator { + return &ResolveEvaluator{Logger: log} +} + +// Evaluate returns a marked resolve result. Arguments are already evaluated by JsonLogic. +// Invalid evaluated arguments produce an error result rather than null, because a null +// targeting result would silently fall through to the default variant. +func (re *ResolveEvaluator) Evaluate(values, _ any) any { + parsed, err := parseEvaluatedResolve(values) + if err != nil { + re.Logger.Debug("resolve evaluation failed", zap.Error(err)) + parsed = resolveResult{Error: err.Error()} + } + return map[string]any{ + resolveResultMarker: parsed, + resolveResultTerminal: true, + } +} + +func parseEvaluatedResolve(values any) (resolveResult, error) { + args, ok := values.([]any) + if !ok || len(args) < 1 || len(args) > 3 { + return resolveResult{}, errors.New("resolve arguments must be an array of 1 to 3 items") + } + + variant, ok := args[0].(string) + if !ok { + return resolveResult{}, errors.New("resolve variant must be a string") + } + parsed := resolveResult{Variant: variant} + + if len(args) >= 2 && args[1] != nil { + reason, ok := args[1].(string) + if !ok { + return resolveResult{}, errors.New("resolve reason must be a string or null") + } + parsed.Reason = &reason + } + + if len(args) == 3 && args[2] != nil { + metadata, err := parseEvaluatedMetadata(args[2]) + if err != nil { + return resolveResult{}, err + } + parsed.Metadata = metadata + } + return parsed, nil +} + +func parseEvaluatedMetadata(value any) (map[string]any, error) { + pairs, ok := value.([]any) + if !ok { + return nil, errors.New("resolve metadata must be an array of [key, value] pairs") + } + metadata := make(map[string]any, len(pairs)) + for _, pair := range pairs { + key, raw, err := metadataPair(pair) + if err != nil { + return nil, err + } + primitive, ok := metadataPrimitive(raw) + if !ok { + return nil, errors.New("resolve metadata value must be a string, number, or boolean") + } + metadata[key] = primitive + } + if len(metadata) == 0 { + return nil, nil + } + return metadata, nil +} + +func metadataPair(pair any) (string, any, error) { + items, ok := pair.([]any) + if !ok || len(items) != 2 { + return "", nil, errors.New("resolve metadata pair must be a [key, value] array") + } + key, ok := items[0].(string) + if !ok { + return "", nil, errors.New("resolve metadata key must be a string") + } + return key, items[1], nil +} + +func metadataPrimitive(value any) (any, bool) { + switch n := value.(type) { + case string, bool: + return n, true + case float64: + return n, true + case float32: + return float64(n), true + case int: + return float64(n), true + case int32: + return float64(n), true + case int64: + return float64(n), true + case uint: + return float64(n), true + case uint32: + return float64(n), true + case uint64: + return float64(n), true + default: + return nil, false + } +} + +func parseResolveResult(trimmed string) (resolveResult, bool) { + if !strings.HasPrefix(trimmed, "{") { + return resolveResult{}, false + } + var wrapper map[string]json.RawMessage + if err := json.Unmarshal([]byte(trimmed), &wrapper); err != nil { + return resolveResult{}, false + } + raw, ok := wrapper[resolveResultMarker] + if !ok { + return resolveResult{}, false + } + var parsed resolveResult + if err := json.Unmarshal(raw, &parsed); err != nil { + return resolveResult{}, false + } + return parsed, true +} + +func (je *Resolver) applyResolveResult( + reqID, flagKey string, flag model.Flag, metadata map[string]any, trimmed string, +) (variant, reason string, meta map[string]any, err error, handled bool) { + parsed, ok := parseResolveResult(trimmed) + if !ok { + return "", "", metadata, nil, false + } + if metadata == nil { + metadata = map[string]any{} + } + if parsed.Error != "" { + je.Logger.ErrorWithID(reqID, fmt.Sprintf("resolve failed for flag %s: %s", flagKey, parsed.Error)) + return "", model.ErrorReason, metadata, errors.New(model.ParseErrorCode), true + } + if _, exists := flag.Variants[parsed.Variant]; !exists { + je.Logger.ErrorWithID(reqID, fmt.Sprintf( + "invalid or missing variant: %s for flagKey: %s, variant is not valid", parsed.Variant, flagKey)) + return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode), true + } + for key, value := range parsed.Metadata { + metadata[key] = value + } + reason = model.TargetingMatchReason + if parsed.Reason != nil { + reason = *parsed.Reason + } + return parsed.Variant, reason, metadata, nil, true +} + +// validateResolveOperators rejects resolve outside a terminal position and malformed literal arguments. +// Terminal means the operator is the whole targeting rule, or a result branch of if / ?: whose own +// result is terminal. Its value must reach the resolver unchanged. +func validateResolveOperators(definition *Definition) error { + for _, flag := range definition.Flags { + if len(flag.Targeting) == 0 || string(flag.Targeting) == "null" { + continue + } + var node any + if err := json.Unmarshal(flag.Targeting, &node); err != nil { + return fmt.Errorf("flag %q: invalid targeting: %w", flag.Key, err) + } + if err := walkResolve(node, true, flag.Key); err != nil { + return err + } + } + return nil +} + +func walkResolve(node any, terminal bool, flagKey string) error { + rule, ok := node.(map[string]any) + if !ok { + // Arrays do not pass a nested resolve through as the targeting result. + items, isArray := node.([]any) + if !isArray { + return nil + } + for _, item := range items { + if err := walkResolve(item, false, flagKey); err != nil { + return err + } + } + return nil + } + if len(rule) != 1 { + for _, value := range rule { + if err := walkResolve(value, false, flagKey); err != nil { + return err + } + } + return nil + } + + operator, args := onlyRuleEntry(rule) + if operator == ResolveEvaluationName { + if !terminal { + return fmt.Errorf("flag %q: resolve is only valid as the targeting result or an if/?: result", flagKey) + } + return validateResolveArguments(args, flagKey) + } + if operator == "if" || operator == "?:" { + return walkConditional(args, terminal, flagKey) + } + return walkResolve(args, false, flagKey) +} + +func walkConditional(args any, parentTerminal bool, flagKey string) error { + clauses, ok := args.([]any) + if !ok { + return walkResolve(args, false, flagKey) + } + length := len(clauses) + for i, clause := range clauses { + terminal := false + // if/?: results are the then-branches (odd indexes) and, when the length is odd, the final else. + // A single clause is only a condition: a falsy value becomes null, so it is not terminal. + if length > 1 && (i%2 == 1 || (length%2 == 1 && i == length-1)) { + terminal = parentTerminal + } + if err := walkResolve(clause, terminal, flagKey); err != nil { + return err + } + } + return nil +} + +func validateResolveArguments(args any, flagKey string) error { + items, ok := args.([]any) + if !ok || len(items) < 1 || len(items) > 3 { + return fmt.Errorf("flag %q: resolve arguments must be an array of 1 to 3 items", flagKey) + } + if err := validateResolveVariant(items[0], flagKey); err != nil { + return err + } + if len(items) >= 2 { + if err := validateResolveReason(items[1], flagKey); err != nil { + return err + } + } + if len(items) == 3 { + return validateResolveMetadata(items[2], flagKey) + } + return nil +} + +func validateResolveVariant(node any, flagKey string) error { + if isJSONLogicRule(node) { + return walkResolve(node, false, flagKey) + } + if _, ok := node.(string); ok { + return nil + } + return fmt.Errorf("flag %q: resolve variant must be a string", flagKey) +} + +func validateResolveReason(node any, flagKey string) error { + if node == nil { + return nil + } + if isJSONLogicRule(node) { + return walkResolve(node, false, flagKey) + } + if _, ok := node.(string); ok { + return nil + } + return fmt.Errorf("flag %q: resolve reason must be a string or null", flagKey) +} + +func validateResolveMetadata(node any, flagKey string) error { + if isJSONLogicRule(node) { + return walkResolve(node, false, flagKey) + } + pairs, ok := node.([]any) + if !ok { + return fmt.Errorf("flag %q: resolve metadata must be an array of [key, value] pairs", flagKey) + } + for _, pair := range pairs { + if isJSONLogicRule(pair) { + if err := walkResolve(pair, false, flagKey); err != nil { + return err + } + continue + } + if err := validateMetadataPair(pair, flagKey); err != nil { + return err + } + } + return nil +} + +func validateMetadataPair(pair any, flagKey string) error { + items, ok := pair.([]any) + if !ok || len(items) != 2 { + return fmt.Errorf("flag %q: resolve metadata pair must be a [key, value] array", flagKey) + } + if err := validateMetadataKey(items[0], flagKey); err != nil { + return err + } + return validateMetadataValue(items[1], flagKey) +} + +func validateMetadataKey(node any, flagKey string) error { + if isJSONLogicRule(node) { + return walkResolve(node, false, flagKey) + } + if _, ok := node.(string); ok { + return nil + } + return fmt.Errorf("flag %q: resolve metadata key must be a string", flagKey) +} + +func validateMetadataValue(node any, flagKey string) error { + if isJSONLogicRule(node) { + return walkResolve(node, false, flagKey) + } + switch node.(type) { + case string, float64, bool: + return nil + default: + return fmt.Errorf("flag %q: resolve metadata value must be a string, number, or boolean", flagKey) + } +} + +func isJSONLogicRule(node any) bool { + rule, ok := node.(map[string]any) + if !ok || len(rule) != 1 { + return false + } + operator, _ := onlyRuleEntry(rule) + return knownTargetingOperator(operator) +} + +// knownTargetingOperators are the operators JsonLogic will call. +// Any other single-key object is data, not a computed argument. +var knownTargetingOperators = map[string]struct{}{ + ResolveEvaluationName: {}, FractionEvaluationName: {}, + StartsWithEvaluationName: {}, EndsWithEvaluationName: {}, SemVerEvaluationName: {}, + "and": {}, "or": {}, "filter": {}, "map": {}, "reduce": {}, "all": {}, "none": {}, "some": {}, + "in": {}, "missing": {}, "missing_some": {}, "var": {}, "set": {}, "cat": {}, "substr": {}, "merge": {}, + "if": {}, "?:": {}, "max": {}, "min": {}, "+": {}, "-": {}, "*": {}, "/": {}, "%": {}, "abs": {}, + "!": {}, "!!": {}, "===": {}, "!==": {}, "==": {}, "!=": {}, "<": {}, "<=": {}, ">": {}, ">=": {}, + "contains_all": {}, "contains_any": {}, "contains_none": {}, +} + +func knownTargetingOperator(operator string) bool { + _, ok := knownTargetingOperators[operator] + return ok +} + +func onlyRuleEntry(rule map[string]any) (string, any) { + for operator, args := range rule { + return operator, args + } + return "", nil +} diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go new file mode 100644 index 000000000..9ac2cef44 --- /dev/null +++ b/core/pkg/evaluator/resolve_test.go @@ -0,0 +1,260 @@ +package evaluator + +import ( + "context" + "errors" + "testing" + + "github.com/open-feature/flagd/core/pkg/logger" + "github.com/open-feature/flagd/core/pkg/model" + "github.com/open-feature/flagd/core/pkg/store" + "github.com/open-feature/flagd/core/pkg/sync" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveEvaluation(t *testing.T) { + const source = "testSource" + ctx := context.Background() + + tests := map[string]struct { + flags string + metadata model.Metadata + flagKey string + context map[string]any + value string + variant string + reason string + meta map[string]any + err error + }{ + "whole rule selects variant and keeps targeting match": { + flags: resolveFlag(`{"resolve": ["red"]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + }, + "custom reason": { + flags: resolveFlag(`{"resolve": ["blue", "ALLOWLIST"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: "ALLOWLIST", + }, + "null reason keeps targeting match and merges metadata": { + flags: resolveFlag(`{"resolve": ["green", null, [["details", "pilot"]]]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "pilot"}, + }, + "rule metadata wins over flag and flag set": { + flags: `{ + "metadata": {"details": "set", "owner": "set"}, + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "blue": "#0000FF", "green": "#00FF00", "yellow": "#FFFF00"}, + "metadata": {"details": "flag", "version": "flag"}, + "targeting": {"resolve": ["red", "ALLOWLIST", [["details", "rule"], ["onlyRule", true]]]} + } + } + }`, + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{ + "details": "rule", + "owner": "set", + "version": "flag", + "onlyRule": true, + }, + }, + "nested if branches stay distinguishable": { + flags: resolveFlag(`{ + "if": [ + {"==": [{"var": "id"}, "a"]}, + {"resolve": ["red", "ALLOWLIST", [["details", "customer-a"]]]}, + {"==": [{"var": "id"}, "b"]}, + {"resolve": ["red", "SPLIT", [["details", "customer-b"]]]}, + {"resolve": ["blue", "FALLTHROUGH", [["details", "else"]]]} + ] + }`), + flagKey: "color", + context: map[string]any{"id": "b"}, + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"details": "customer-b"}, + }, + "ternary result is terminal": { + flags: resolveFlag(`{ + "?:": [ + {"==": [{"var": "id"}, "a"]}, + {"resolve": ["green", "ALLOWLIST"]}, + {"resolve": ["yellow", "FALLTHROUGH"]} + ] + }`), + flagKey: "color", + context: map[string]any{"id": "z"}, + value: "#FFFF00", + variant: "yellow", + reason: "FALLTHROUGH", + }, + "computed variant reason and details": { + flags: resolveFlag(`{ + "resolve": [ + {"if": [true, "red", "blue"]}, + {"cat": ["ALLOW", "LIST"]}, + [["details", {"cat": ["us-", {"var": "bucket"}]}]] + ] + }`), + flagKey: "color", + context: map[string]any{"bucket": "10pct"}, + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{"details": "us-10pct"}, + }, + "numeric and boolean metadata": { + flags: resolveFlag(`{"resolve": ["red", "SPLIT", [["percent", 10], ["enabled", false]]]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"percent": float64(10), "enabled": false}, + }, + "missing variant matches a plain string miss": { + flags: resolveFlag(`{"resolve": ["missing"]}`), + flagKey: "color", + reason: model.ErrorReason, + err: errors.New(model.GeneralErrorCode), + }, + "computed non-string variant is a parse error": { + flags: resolveFlag(`{"resolve": [{"var": "pick"}]}`), + flagKey: "color", + context: map[string]any{"pick": 1}, + reason: model.ErrorReason, + err: errors.New(model.ParseErrorCode), + }, + "shared evaluator inlines a terminal resolve": { + flags: `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "blue": "#0000FF", "green": "#00FF00", "yellow": "#FFFF00"}, + "targeting": {"$ref": "picked"} + } + }, + "$evaluators": {"picked": {"resolve": ["blue", "ALLOWLIST"]}} + }`, + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: "ALLOWLIST", + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{source}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: tt.flags, Source: source})) + + value, variant, reason, metadata, err := je.ResolveStringValue(ctx, "default", tt.flagKey, tt.context) + assert.Equal(t, tt.value, value) + assert.Equal(t, tt.variant, variant) + assert.Equal(t, tt.reason, reason) + assert.Equal(t, tt.err, err) + for key, want := range tt.meta { + assert.Equal(t, want, metadata[key]) + } + }) + } +} + +func TestResolveRejectedAtLoad(t *testing.T) { + tests := map[string]string{ + "inside equality": `{"==": [{"resolve": ["red"]}, "red"]}`, + "inside cat": `{"cat": [{"resolve": ["red"]}, "x"]}`, + "if condition": `{"if": [{"resolve": ["red"]}, "red", "blue"]}`, + "consumed by outer if": `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`, + "inside fractional": `{"fractional": ["key", [{"resolve": ["red"]}, 1], ["blue", 1]]}`, + "nested in resolve arg": `{"resolve": [{"resolve": ["red"]}]}`, + "result array": `{"if": [true, [{"resolve": ["red"]}], "blue"]}`, + "no arguments": `{"resolve": []}`, + "too many arguments": `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`, + "non-string variant": `{"resolve": [true]}`, + "non-string reason": `{"resolve": ["red", 1]}`, + "metadata object": `{"resolve": ["red", null, {"details": "x"}]}`, + "short pair": `{"resolve": ["red", null, [["details"]]]}`, + "non-primitive value": `{"resolve": ["red", null, [["details", {"nested": true}]]]}`, + "non-string key": `{"resolve": ["red", null, [[1, "x"]]]}`, + "inlined bad evaluator": "", + } + + for name, targeting := range tests { + t.Run(name, func(t *testing.T) { + flags := resolveFlag(targeting) + if name == "inlined bad evaluator" { + flags = `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "yellow": "#FFFF00"}, + "targeting": {"==": [{"$ref": "bad"}, "red"]} + } + }, + "$evaluators": {"bad": {"resolve": ["red"]}} + }` + } + log := logger.NewLogger(nil, false) + je := NewJSON(log, store.NewFlags()) + err := je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "color") + }) + } +} + +func TestParseEvaluatedResolve(t *testing.T) { + reason := "ALLOWLIST" + parsed, err := parseEvaluatedResolve([]any{"red", reason, []any{[]any{"details", "x"}, []any{"n", 2}}}) + require.NoError(t, err) + assert.Equal(t, "red", parsed.Variant) + require.NotNil(t, parsed.Reason) + assert.Equal(t, reason, *parsed.Reason) + assert.Equal(t, map[string]any{"details": "x", "n": float64(2)}, parsed.Metadata) + + _, err = parseEvaluatedResolve([]any{"red", nil, "nope"}) + require.Error(t, err) +} + +func resolveFlag(targeting string) string { + if targeting == "" { + targeting = "null" + } + return `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": { + "red": "#FF0000", + "blue": "#0000FF", + "green": "#00FF00", + "yellow": "#FFFF00" + }, + "targeting": ` + targeting + ` + } + } + }` +} diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md new file mode 100644 index 000000000..e745ea281 --- /dev/null +++ b/docs/reference/custom-operations/resolve-operation.md @@ -0,0 +1,76 @@ +--- +description: flagd resolve custom operation +--- + +# Resolve Operation + +`resolve` ends a targeting rule with a variant, and optionally a custom reason and metadata for the branch that fired. + +`"red"` and `{ "resolve": ["red"] }` select the same variant. + +A missing or null reason keeps `TARGETING_MATCH`. + +Metadata is a shallow list of `[key, value]` pairs. + +Values are strings, numbers, or booleans. + +Rule metadata overwrites flag metadata, which overwrites flag-set metadata. + +`resolve` is terminal. + +It is valid as the whole targeting rule, or as a result of `if` / `?:`. + +flagd rejects a flag at load time when `resolve` appears anywhere else, including inside `==`, `cat`, or an `if` condition. + +Arguments may be computed with other operators, such as `var` or `cat`. + +Older flagd binaries do not know this operator. + +Upgrade flagd before a configuration starts using `resolve`. + +```json +{ + "resolve": [ + "on", + "SPLIT_RANDOM", + [["details", "us-10pct-rollout"]] + ] +} +``` + +## Example + +```json +{ + "flags": { + "acceptable-feature-stability": { + "state": "ENABLED", + "defaultVariant": "ga", + "variants": { + "alpha": "alpha", + "beta": "beta", + "ga": "ga" + }, + "targeting": { + "if": [ + { "===": [{ "var": "customerId" }, "customer-A"] }, + { + "resolve": [ + "alpha", + "TARGETING_MATCH", + [["details", "explicit allowlist for enterprise pilot"]] + ] + }, + { "in": [{ "var": "customerId" }, ["customer-B1", "customer-B2"]] }, + { "resolve": ["beta", "TARGETING_MATCH"] }, + { "resolve": ["ga", "FALLTHROUGH"] } + ] + } + } + } +} +``` + +The `alpha` and `beta` branches both say why they matched. + +The final branch selects `ga` with reason `FALLTHROUGH`. diff --git a/docs/reference/flag-definitions.md b/docs/reference/flag-definitions.md index f2408993f..50aba5166 100644 --- a/docs/reference/flag-definitions.md +++ b/docs/reference/flag-definitions.md @@ -392,11 +392,13 @@ Consistent with built-in JsonLogic operators, flagd's custom operators return fa | `starts_with` | Attribute starts with the specified value | string | Logic: `#!json { "starts_with" : [ "192.168.0.1", "192.168"] }`
Result: `true`

Logic: `#!json { "starts_with" : [ "10.0.0.1", "192.168"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `ends_with` | Attribute ends with the specified value | string | Logic: `#!json { "ends_with" : [ "noreply@example.com", "@example.com"] }`
Result: `true`

Logic: `#!json { ends_with" : [ "noreply@example.com", "@test.com"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `sem_ver` | Attribute matches a semantic versioning condition | string (valid [semver](https://semver.org/)) | Logic: `#!json {"sem_ver": ["1.1.2", ">=", "1.0.0"]}`
Result: `true`

Additional documentation can be found [here](./custom-operations/semver-operation.md). | +| `resolve` | Ends targeting with a variant, optional reason, and metadata | string variant; reason string or null; metadata pairs of string, number, or boolean | Logic: `#!json {"resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]]}`
Result: variant `on`, reason `SPLIT_RANDOM`, metadata `details`

Additional documentation can be found [here](./custom-operations/resolve-operation.md). | !!! info "Error handling in custom operations" flagd's custom operations return `null` on invalid or unexpected inputs, consistent with how built-in JsonLogic operations represent no-value returns, for example how `var` treats missing keys. When used inside an `if`, `null` is falsy, so evaluation falls through to the else branch rather than producing a false positive match. + `resolve` is the exception: it is only valid in a terminal position, and flagd rejects the flag when that configuration is loaded. #### Targeting key diff --git a/mkdocs.yml b/mkdocs.yml index 6317f7213..d65a6e7b1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -108,6 +108,7 @@ nav: - 'Definition Overview': 'reference/flag-definitions.md' - 'Custom Operations': - 'Fractional': 'reference/custom-operations/fractional-operation.md' + - 'Resolve': 'reference/custom-operations/resolve-operation.md' - 'Semantic Version': 'reference/custom-operations/semver-operation.md' - 'String Comparison': 'reference/custom-operations/string-comparison-operation.md' - 'Schema': 'reference/schema.md' From d7994b7b83cd12094c010770b267083cadb586fe Mon Sep 17 00:00:00 2001 From: marcozabel Date: Mon, 9 Nov 2026 13:33:14 +0100 Subject: [PATCH 02/20] fix(core): return an unforgeable resolve result The operator returned a marker object that was serialized and parsed back, so a rule returning {"var": ...} let the caller supply a resolve result, with any reason and metadata, through the evaluation context. The operator now returns a private Go value, read through jsonlogic.ApplyInterface. No JSON input decodes to it. Other results are still encoded as before. Since the resolve result is no longer JSON-encoded during evaluation, computed metadata must be checked to be finite. A value like 1/0 (+Inf) or 0/0 (NaN) now returns PARSE_ERROR instead of breaking OFREP and Connect JSON responses, including bulk ones. Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 36 +++++++--- core/pkg/evaluator/resolve.go | 105 +++++++++++------------------ core/pkg/evaluator/resolve_test.go | 87 ++++++++++++++++++++++-- 3 files changed, 148 insertions(+), 80 deletions(-) diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 1526c324f..5aebacdb1 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -1,7 +1,6 @@ package evaluator import ( - "bytes" "context" "encoding/json" "errors" @@ -443,16 +442,27 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ErrorReason) } - var result bytes.Buffer // evaluate JsonLogic rules to determine the variant - err = jsonlogic.Apply(bytes.NewReader(targetingBytes), bytes.NewReader(b), &result) + output, err := applyTargeting(targetingBytes, b) + if err != nil { + je.Logger.ErrorWithID(reqID, fmt.Sprintf("error applying targeting rules: %s", err)) + return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) + } + + // a Go value no JSON input can produce, so context data cannot forge it + if resolved, ok := output.(*resolveResult); ok { + variant, reason, metadata, err := je.applyResolveResult(reqID, flagKey, flag, metadata, resolved) + return variant, flag.Variants, reason, metadata, err + } + + result, err := json.Marshal(output) if err != nil { je.Logger.ErrorWithID(reqID, fmt.Sprintf("error applying targeting rules: %s", err)) return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) } // check if string is "null" before we strip quotes, so we can differentiate between JSON null and "null" - trimmed := strings.TrimSpace(result.String()) + trimmed := strings.TrimSpace(string(result)) if trimmed == "null" { if flag.DefaultVariant == "" { @@ -467,12 +477,6 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return flag.DefaultVariant, flag.Variants, model.DefaultReason, metadata, nil } - if variant, reason, metadata, err, handled := je.applyResolveResult( - reqID, flagKey, flag, metadata, trimmed, - ); handled { - return variant, flag.Variants, reason, metadata, err - } - // strip whitespace and quotes from the variant variant = strings.ReplaceAll(trimmed, "\"", "") @@ -496,6 +500,18 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return flag.DefaultVariant, flag.Variants, model.StaticReason, metadata, nil } +// applyTargeting is jsonlogic.Apply without the final encode, so operators can return Go values +func applyTargeting(rule, data []byte) (any, error) { + var parsedRule, parsedData any + if err := json.Unmarshal(rule, &parsedRule); err != nil { + return nil, err + } + if err := json.Unmarshal(data, &parsedData); err != nil { + return nil, err + } + return jsonlogic.ApplyInterface(parsedRule, parsedData) +} + func setFlagdProperties( log *logger.Logger, context map[string]any, diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 9829533a6..5234b1a63 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -4,30 +4,23 @@ import ( "encoding/json" "errors" "fmt" - "strings" + "math" "github.com/open-feature/flagd/core/pkg/logger" "github.com/open-feature/flagd/core/pkg/model" "go.uber.org/zap" ) -const ( - ResolveEvaluationName = "resolve" - // resolveResultMarker wraps the operator result so evaluateVariant can tell it - // apart from a plain variant string after JsonLogic serializes the rule output. - // The companion key keeps the object multi-key: JsonLogic treats a one-key object - // as an operator call, and if/?: re-applies its result. - resolveResultMarker = "$flagd.resolve" - resolveResultTerminal = "$flagd.resolve.terminal" -) +const ResolveEvaluationName = "resolve" -// resolveResult is the payload carried under resolveResultMarker. -// A nil Reason keeps TARGETING_MATCH. Error is set when evaluated arguments are malformed. +// resolveResult is what the operator returns. JsonLogic passes it through if/?: untouched (it only +// re-applies maps), and since no JSON input decodes to it, context data cannot forge one. +// A nil reason keeps TARGETING_MATCH. err is set when evaluated arguments are malformed. type resolveResult struct { - Variant string `json:"variant,omitempty"` - Reason *string `json:"reason"` - Metadata map[string]any `json:"metadata,omitempty"` - Error string `json:"error,omitempty"` + variant string + reason *string + metadata map[string]any + err error } // ResolveEvaluator implements the terminal resolve operator. @@ -40,47 +33,44 @@ func NewResolveEvaluator(log *logger.Logger) *ResolveEvaluator { return &ResolveEvaluator{Logger: log} } -// Evaluate returns a marked resolve result. Arguments are already evaluated by JsonLogic. +// Evaluate returns a *resolveResult. Arguments are already evaluated by JsonLogic. // Invalid evaluated arguments produce an error result rather than null, because a null // targeting result would silently fall through to the default variant. func (re *ResolveEvaluator) Evaluate(values, _ any) any { parsed, err := parseEvaluatedResolve(values) if err != nil { re.Logger.Debug("resolve evaluation failed", zap.Error(err)) - parsed = resolveResult{Error: err.Error()} - } - return map[string]any{ - resolveResultMarker: parsed, - resolveResultTerminal: true, + return &resolveResult{err: err} } + return parsed } -func parseEvaluatedResolve(values any) (resolveResult, error) { +func parseEvaluatedResolve(values any) (*resolveResult, error) { args, ok := values.([]any) if !ok || len(args) < 1 || len(args) > 3 { - return resolveResult{}, errors.New("resolve arguments must be an array of 1 to 3 items") + return nil, errors.New("resolve arguments must be an array of 1 to 3 items") } variant, ok := args[0].(string) if !ok { - return resolveResult{}, errors.New("resolve variant must be a string") + return nil, errors.New("resolve variant must be a string") } - parsed := resolveResult{Variant: variant} + parsed := &resolveResult{variant: variant} if len(args) >= 2 && args[1] != nil { reason, ok := args[1].(string) if !ok { - return resolveResult{}, errors.New("resolve reason must be a string or null") + return nil, errors.New("resolve reason must be a string or null") } - parsed.Reason = &reason + parsed.reason = &reason } if len(args) == 3 && args[2] != nil { metadata, err := parseEvaluatedMetadata(args[2]) if err != nil { - return resolveResult{}, err + return nil, err } - parsed.Metadata = metadata + parsed.metadata = metadata } return parsed, nil } @@ -98,7 +88,7 @@ func parseEvaluatedMetadata(value any) (map[string]any, error) { } primitive, ok := metadataPrimitive(raw) if !ok { - return nil, errors.New("resolve metadata value must be a string, number, or boolean") + return nil, errors.New("resolve metadata value must be a string, finite number, or boolean") } metadata[key] = primitive } @@ -120,14 +110,16 @@ func metadataPair(pair any) (string, any, error) { return key, items[1], nil } +// metadataPrimitive rejects NaN and ±Inf (e.g. a computed 1/0): JSON can't encode them, so OFREP and Connect +// JSON responses would fail, taking a whole bulk response with them func metadataPrimitive(value any) (any, bool) { switch n := value.(type) { case string, bool: return n, true case float64: - return n, true + return n, isFinite(n) case float32: - return float64(n), true + return float64(n), isFinite(float64(n)) case int: return float64(n), true case int32: @@ -145,52 +137,33 @@ func metadataPrimitive(value any) (any, bool) { } } -func parseResolveResult(trimmed string) (resolveResult, bool) { - if !strings.HasPrefix(trimmed, "{") { - return resolveResult{}, false - } - var wrapper map[string]json.RawMessage - if err := json.Unmarshal([]byte(trimmed), &wrapper); err != nil { - return resolveResult{}, false - } - raw, ok := wrapper[resolveResultMarker] - if !ok { - return resolveResult{}, false - } - var parsed resolveResult - if err := json.Unmarshal(raw, &parsed); err != nil { - return resolveResult{}, false - } - return parsed, true +func isFinite(f float64) bool { + return !math.IsNaN(f) && !math.IsInf(f, 0) } func (je *Resolver) applyResolveResult( - reqID, flagKey string, flag model.Flag, metadata map[string]any, trimmed string, -) (variant, reason string, meta map[string]any, err error, handled bool) { - parsed, ok := parseResolveResult(trimmed) - if !ok { - return "", "", metadata, nil, false - } + reqID, flagKey string, flag model.Flag, metadata map[string]any, parsed *resolveResult, +) (variant, reason string, meta map[string]any, err error) { if metadata == nil { metadata = map[string]any{} } - if parsed.Error != "" { - je.Logger.ErrorWithID(reqID, fmt.Sprintf("resolve failed for flag %s: %s", flagKey, parsed.Error)) - return "", model.ErrorReason, metadata, errors.New(model.ParseErrorCode), true + if parsed.err != nil { + je.Logger.ErrorWithID(reqID, fmt.Sprintf("resolve failed for flag %s: %s", flagKey, parsed.err)) + return "", model.ErrorReason, metadata, errors.New(model.ParseErrorCode) } - if _, exists := flag.Variants[parsed.Variant]; !exists { + if _, exists := flag.Variants[parsed.variant]; !exists { je.Logger.ErrorWithID(reqID, fmt.Sprintf( - "invalid or missing variant: %s for flagKey: %s, variant is not valid", parsed.Variant, flagKey)) - return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode), true + "invalid or missing variant: %s for flagKey: %s, variant is not valid", parsed.variant, flagKey)) + return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode) } - for key, value := range parsed.Metadata { + for key, value := range parsed.metadata { metadata[key] = value } reason = model.TargetingMatchReason - if parsed.Reason != nil { - reason = *parsed.Reason + if parsed.reason != nil { + reason = *parsed.reason } - return parsed.Variant, reason, metadata, nil, true + return parsed.variant, reason, metadata, nil } // validateResolveOperators rejects resolve outside a terminal position and malformed literal arguments. diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 9ac2cef44..ea1574913 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -2,6 +2,7 @@ package evaluator import ( "context" + "encoding/json" "errors" "testing" @@ -225,14 +226,92 @@ func TestResolveRejectedAtLoad(t *testing.T) { } } +func TestResolveRuntimeErrors(t *testing.T) { + tests := map[string]struct { + targeting string + context map[string]any + err error + }{ + // context data shaped like an operator result must not be treated as one + "context cannot forge a resolve result": { + targeting: `{"var": "pick"}`, + context: map[string]any{"pick": map[string]any{ + "variant": "red", "reason": "INJECTED", "metadata": map[string]any{"flagSetId": "spoofed"}, + }}, + err: errors.New(model.GeneralErrorCode), + }, + "computed +Inf metadata": { + targeting: nonFiniteMetadataRule, + context: map[string]any{"hits": 1, "total": 0}, + err: errors.New(model.ParseErrorCode), + }, + "computed NaN metadata": { + targeting: nonFiniteMetadataRule, + context: map[string]any{"hits": 0, "total": 0}, + err: errors.New(model.ParseErrorCode), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(tt.targeting), Source: "testSource"})) + + _, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", tt.context) + assert.Empty(t, variant) + assert.Equal(t, model.ErrorReason, reason) + assert.Equal(t, tt.err, err) + assert.NotContains(t, metadata, "flagSetId") + _, encodeErr := json.Marshal(metadata) + assert.NoError(t, encodeErr, "metadata must stay JSON-encodable") + }) + } +} + +// a computed ratio that is +Inf for total 0 and NaN for 0/0 +const nonFiniteMetadataRule = `{"resolve": ["red", "SPLIT", [["share", {"/": [{"var": "hits"}, {"var": "total"}]}]]]}` + +// one flag with non-finite computed metadata must not break encoding of a bulk evaluation +func TestResolveNonFiniteMetadataInBulk(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + flags := `{"flags": { + "ratio": {"state": "ENABLED", "defaultVariant": "red", "variants": {"red": "#FF0000"}, + "targeting": ` + nonFiniteMetadataRule + `}, + "sibling": {"state": "ENABLED", "defaultVariant": "on", "variants": {"on": true, "off": false}} + }}` + require.NoError(t, je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"})) + + values, _, err := je.ResolveAllValues(context.Background(), "default", map[string]any{"hits": 1, "total": 0}) + require.NoError(t, err) + require.Len(t, values, 2) + + _, err = json.Marshal(values) + require.NoError(t, err) + for _, value := range values { + if value.FlagKey == "sibling" { + assert.Equal(t, true, value.Value) + assert.NoError(t, value.Error) + } + if value.FlagKey == "ratio" { + assert.Equal(t, errors.New(model.ParseErrorCode), value.Error) + } + } +} + func TestParseEvaluatedResolve(t *testing.T) { reason := "ALLOWLIST" parsed, err := parseEvaluatedResolve([]any{"red", reason, []any{[]any{"details", "x"}, []any{"n", 2}}}) require.NoError(t, err) - assert.Equal(t, "red", parsed.Variant) - require.NotNil(t, parsed.Reason) - assert.Equal(t, reason, *parsed.Reason) - assert.Equal(t, map[string]any{"details": "x", "n": float64(2)}, parsed.Metadata) + assert.Equal(t, "red", parsed.variant) + require.NotNil(t, parsed.reason) + assert.Equal(t, reason, *parsed.reason) + assert.Equal(t, map[string]any{"details": "x", "n": float64(2)}, parsed.metadata) _, err = parseEvaluatedResolve([]any{"red", nil, "nope"}) require.Error(t, err) From b80d06ff81218c3fc6022eb95c8a7296f978826d Mon Sep 17 00:00:00 2001 From: marcozabel Date: Mon, 9 Nov 2026 13:34:03 +0100 Subject: [PATCH 03/20] fix(core): mark only the misused resolve flag invalid A misplaced or malformed resolve failed configToFlagDefinition, so SetState dropped the whole payload and every other flag from that source. Load now marks only the offending flag invalid, using a new Invalid field on model.Flag that is not serialized, and logs a warning. Evaluating that flag returns PARSE_ERROR, like other broken targeting. Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 10 +- core/pkg/evaluator/resolve.go | 32 +++--- core/pkg/evaluator/resolve_test.go | 102 +++++++++++------- core/pkg/model/flag.go | 2 + .../custom-operations/resolve-operation.md | 4 +- docs/reference/flag-definitions.md | 2 +- 6 files changed, 94 insertions(+), 58 deletions(-) diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 5aebacdb1..65a728685 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -420,6 +420,12 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return "", nil, model.DisabledReason, metadata, nil } + if flag.Invalid != "" { + // already warned at load, so per-evaluation logging stays at debug + je.Logger.DebugWithID(reqID, fmt.Sprintf("flag %s is invalid: %s", flagKey, flag.Invalid)) + return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) + } + // get the targeting logic, if any targeting := flag.Targeting @@ -607,9 +613,7 @@ func (je *JSON) configToFlagDefinition(config string, definition *Definition) er definition.Flags = flags } je.warnUnsafeNumericVariants(definition) - if err := validateResolveOperators(definition); err != nil { - return err - } + je.markInvalidResolveFlags(definition) return validateDefaultVariants(definition) } diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 5234b1a63..574312d49 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -166,23 +166,29 @@ func (je *Resolver) applyResolveResult( return parsed.variant, reason, metadata, nil } -// validateResolveOperators rejects resolve outside a terminal position and malformed literal arguments. +// markInvalidResolveFlags marks flags that use resolve outside a terminal position or with malformed literal +// arguments. Only the offending flag is invalid; the rest of the payload still loads. // Terminal means the operator is the whole targeting rule, or a result branch of if / ?: whose own // result is terminal. Its value must reach the resolver unchanged. -func validateResolveOperators(definition *Definition) error { - for _, flag := range definition.Flags { - if len(flag.Targeting) == 0 || string(flag.Targeting) == "null" { - continue - } - var node any - if err := json.Unmarshal(flag.Targeting, &node); err != nil { - return fmt.Errorf("flag %q: invalid targeting: %w", flag.Key, err) - } - if err := walkResolve(node, true, flag.Key); err != nil { - return err +func (je *JSON) markInvalidResolveFlags(definition *Definition) { + for i := range definition.Flags { + flag := &definition.Flags[i] + if err := validateResolveTargeting(*flag); err != nil { + flag.Invalid = err.Error() + je.Logger.Warn(fmt.Sprintf("%s; evaluating the flag returns %s", err, model.ParseErrorCode)) } } - return nil +} + +func validateResolveTargeting(flag model.Flag) error { + if len(flag.Targeting) == 0 || string(flag.Targeting) == "null" { + return nil + } + var node any + if err := json.Unmarshal(flag.Targeting, &node); err != nil { + return fmt.Errorf("flag %q: invalid targeting: %w", flag.Key, err) + } + return walkResolve(node, true, flag.Key) } func walkResolve(node any, terminal bool, flagKey string) error { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index ea1574913..6ec36127a 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -181,47 +181,50 @@ func TestResolveEvaluation(t *testing.T) { } } -func TestResolveRejectedAtLoad(t *testing.T) { - tests := map[string]string{ - "inside equality": `{"==": [{"resolve": ["red"]}, "red"]}`, - "inside cat": `{"cat": [{"resolve": ["red"]}, "x"]}`, - "if condition": `{"if": [{"resolve": ["red"]}, "red", "blue"]}`, - "consumed by outer if": `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`, - "inside fractional": `{"fractional": ["key", [{"resolve": ["red"]}, 1], ["blue", 1]]}`, - "nested in resolve arg": `{"resolve": [{"resolve": ["red"]}]}`, - "result array": `{"if": [true, [{"resolve": ["red"]}], "blue"]}`, - "no arguments": `{"resolve": []}`, - "too many arguments": `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`, - "non-string variant": `{"resolve": [true]}`, - "non-string reason": `{"resolve": ["red", 1]}`, - "metadata object": `{"resolve": ["red", null, {"details": "x"}]}`, - "short pair": `{"resolve": ["red", null, [["details"]]]}`, - "non-primitive value": `{"resolve": ["red", null, [["details", {"nested": true}]]]}`, - "non-string key": `{"resolve": ["red", null, [[1, "x"]]]}`, - "inlined bad evaluator": "", +func TestResolveInvalidFlagAtLoad(t *testing.T) { + tests := map[string]struct { + targeting string + evaluators string + }{ + "inside equality": {targeting: `{"==": [{"resolve": ["red"]}, "red"]}`}, + "inside cat": {targeting: `{"cat": [{"resolve": ["red"]}, "x"]}`}, + "if condition": {targeting: `{"if": [{"resolve": ["red"]}, "red", "blue"]}`}, + "consumed by outer if": {targeting: `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`}, + "inside fractional": {targeting: `{"fractional": ["key", [{"resolve": ["red"]}, 1], ["blue", 1]]}`}, + "nested in resolve arg": {targeting: `{"resolve": [{"resolve": ["red"]}]}`}, + "result array": {targeting: `{"if": [true, [{"resolve": ["red"]}], "blue"]}`}, + "no arguments": {targeting: `{"resolve": []}`}, + "too many arguments": {targeting: `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`}, + "non-string variant": {targeting: `{"resolve": [true]}`}, + "non-string reason": {targeting: `{"resolve": ["red", 1]}`}, + "metadata object": {targeting: `{"resolve": ["red", null, {"details": "x"}]}`}, + "short pair": {targeting: `{"resolve": ["red", null, [["details"]]]}`}, + "non-primitive value": {targeting: `{"resolve": ["red", null, [["details", {"nested": true}]]]}`}, + "non-string key": {targeting: `{"resolve": ["red", null, [[1, "x"]]]}`}, + "inlined bad evaluator": { + targeting: `{"==": [{"$ref": "bad"}, "red"]}`, + evaluators: `{"bad": {"resolve": ["red"]}}`, + }, } - for name, targeting := range tests { + for name, tt := range tests { t.Run(name, func(t *testing.T) { - flags := resolveFlag(targeting) - if name == "inlined bad evaluator" { - flags = `{ - "flags": { - "color": { - "state": "ENABLED", - "defaultVariant": "yellow", - "variants": {"red": "#FF0000", "yellow": "#FFFF00"}, - "targeting": {"==": [{"$ref": "bad"}, "red"]} - } - }, - "$evaluators": {"bad": {"resolve": ["red"]}} - }` - } log := logger.NewLogger(nil, false) - je := NewJSON(log, store.NewFlags()) - err := je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"}) - require.Error(t, err) - assert.Contains(t, err.Error(), "color") + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + flags := resolveFlagWithSibling(tt.targeting, tt.evaluators) + require.NoError(t, je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"})) + + _, _, reason, _, err := je.ResolveStringValue(context.Background(), "default", "color", nil) + assert.Equal(t, model.ErrorReason, reason) + assert.Equal(t, errors.New(model.ParseErrorCode), err) + + // the rest of the payload still loads + value, _, reason, _, err := je.ResolveBooleanValue(context.Background(), "default", "sibling", nil) + require.NoError(t, err) + assert.True(t, value) + assert.Equal(t, model.StaticReason, reason) }) } } @@ -317,10 +320,29 @@ func TestParseEvaluatedResolve(t *testing.T) { require.Error(t, err) } -func resolveFlag(targeting string) string { - if targeting == "" { - targeting = "null" +func resolveFlagWithSibling(targeting, evaluators string) string { + if evaluators == "" { + evaluators = "{}" } + return `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "blue": "#0000FF", "yellow": "#FFFF00"}, + "targeting": ` + targeting + ` + }, + "sibling": { + "state": "ENABLED", + "defaultVariant": "on", + "variants": {"on": true, "off": false} + } + }, + "$evaluators": ` + evaluators + ` + }` +} + +func resolveFlag(targeting string) string { return `{ "flags": { "color": { diff --git a/core/pkg/model/flag.go b/core/pkg/model/flag.go index 228470e9a..dc43a5877 100644 --- a/core/pkg/model/flag.go +++ b/core/pkg/model/flag.go @@ -17,6 +17,8 @@ type Flag struct { Targeting json.RawMessage `json:"targeting,omitempty"` Source string `json:"source"` Metadata Metadata `json:"metadata,omitempty"` + // Invalid is set at load when the targeting cannot be evaluated; evaluating the flag returns PARSE_ERROR + Invalid string `json:"-"` } type Evaluators struct { diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index e745ea281..0c0ee186a 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -20,7 +20,9 @@ Rule metadata overwrites flag metadata, which overwrites flag-set metadata. It is valid as the whole targeting rule, or as a result of `if` / `?:`. -flagd rejects a flag at load time when `resolve` appears anywhere else, including inside `==`, `cat`, or an `if` condition. +flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, or an `if` condition, or when its literal arguments are malformed. + +Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same configuration still load. Arguments may be computed with other operators, such as `var` or `cat`. diff --git a/docs/reference/flag-definitions.md b/docs/reference/flag-definitions.md index 50aba5166..7ac7b058f 100644 --- a/docs/reference/flag-definitions.md +++ b/docs/reference/flag-definitions.md @@ -398,7 +398,7 @@ Consistent with built-in JsonLogic operators, flagd's custom operators return fa flagd's custom operations return `null` on invalid or unexpected inputs, consistent with how built-in JsonLogic operations represent no-value returns, for example how `var` treats missing keys. When used inside an `if`, `null` is falsy, so evaluation falls through to the else branch rather than producing a false positive match. - `resolve` is the exception: it is only valid in a terminal position, and flagd rejects the flag when that configuration is loaded. + `resolve` is the exception: it is only valid in a terminal position. flagd marks a flag that misuses it invalid at load, and evaluating that flag returns `PARSE_ERROR`. #### Targeting key From 5efaf01ad13d4cefc417e195d667d90b01cd603f Mon Sep 17 00:00:00 2001 From: marcozabel Date: Tue, 10 Nov 2026 15:59:16 +0100 Subject: [PATCH 04/20] fix: let a resolve reason be any string without changing the result The ADR makes the resolve reason free-form, but the evaluator, OFREP and gRPC v2 treated FALLBACK and DISABLED as signals to drop the value and variant. A rule using either reason served a zero value or looked disabled. Those checks now also require an empty variant, which flagd's own fallback and disabled results always have. Variant keys are never empty, so a resolve that names an empty variant fails with GENERAL like any other missing variant, and every reason passes through with its value and variant. Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 5 +-- core/pkg/evaluator/resolve.go | 4 ++- core/pkg/evaluator/resolve_test.go | 32 +++++++++++++++++++ core/pkg/service/ofrep/models.go | 7 ++-- core/pkg/service/ofrep/models_test.go | 25 +++++++++++++++ .../custom-operations/resolve-operation.md | 2 ++ .../flag-evaluation/flag_evaluator_v2.go | 7 ++-- .../flag-evaluation/flag_evaluator_v2_test.go | 30 +++++++++++++++++ 8 files changed, 103 insertions(+), 9 deletions(-) diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 65a728685..bca31609a 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -373,12 +373,13 @@ func resolve[T constraints](ctx context.Context, reqID string, key string, conte return value, variant, reason, metadata, err } - if reason == model.FallbackReason { + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + if reason == model.FallbackReason && variant == "" { var zero T return zero, variant, model.FallbackReason, metadata, nil } - if reason == model.DisabledReason { + if reason == model.DisabledReason && variant == "" { var zero T return zero, "", model.DisabledReason, metadata, nil } diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 574312d49..36aa5375f 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -151,7 +151,9 @@ func (je *Resolver) applyResolveResult( je.Logger.ErrorWithID(reqID, fmt.Sprintf("resolve failed for flag %s: %s", flagKey, parsed.err)) return "", model.ErrorReason, metadata, errors.New(model.ParseErrorCode) } - if _, exists := flag.Variants[parsed.variant]; !exists { + // variant keys are non-empty, and an empty variant is how flagd marks its own fallback and disabled + // results, so an empty one is always missing + if _, exists := flag.Variants[parsed.variant]; !exists || parsed.variant == "" { je.Logger.ErrorWithID(reqID, fmt.Sprintf( "invalid or missing variant: %s for flagKey: %s, variant is not valid", parsed.variant, flagKey)) return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode) diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 6ec36127a..2c3d7a596 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -43,6 +43,28 @@ func TestResolveEvaluation(t *testing.T) { variant: "blue", reason: "ALLOWLIST", }, + // the reason is free-form; flagd's own reason names must not change the value or variant + "FALLBACK reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "FALLBACK"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.FallbackReason, + }, + "DISABLED reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "DISABLED"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.DisabledReason, + }, + "ERROR reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "ERROR"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.ErrorReason, + }, "null reason keeps targeting match and merges metadata": { flags: resolveFlag(`{"resolve": ["green", null, [["details", "pilot"]]]}`), flagKey: "color", @@ -235,6 +257,16 @@ func TestResolveRuntimeErrors(t *testing.T) { context map[string]any err error }{ + // an empty variant fails like any missing variant, so a FALLBACK reason cannot make it look like flagd's own + "empty variant": { + targeting: `{"resolve": ["", "FALLBACK"]}`, + err: errors.New(model.GeneralErrorCode), + }, + "computed empty variant": { + targeting: `{"resolve": [{"var": "pick"}, "FALLBACK"]}`, + context: map[string]any{"pick": ""}, + err: errors.New(model.GeneralErrorCode), + }, // context data shaped like an operator result must not be treated as one "context cannot forge a resolve result": { targeting: `{"var": "pick"}`, diff --git a/core/pkg/service/ofrep/models.go b/core/pkg/service/ofrep/models.go index 2f656ae2e..93d85d9d3 100644 --- a/core/pkg/service/ofrep/models.go +++ b/core/pkg/service/ofrep/models.go @@ -78,8 +78,9 @@ func BulkEvaluationResponseFrom(resolutions []evaluator.AnyValue, metadata model } func SuccessResponseFrom(result evaluator.AnyValue) EvaluationSuccess { - // if reason is fallback, we want to omit the value and variant from the response, and set reason to default - if result.Reason == model.FallbackReason { + // if reason is fallback, we want to omit the value and variant from the response, and set reason to default. + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + if result.Reason == model.FallbackReason && result.Variant == "" { return EvaluationSuccess{ Value: nil, // not marshalled due to omitempty Key: result.FlagKey, @@ -89,7 +90,7 @@ func SuccessResponseFrom(result evaluator.AnyValue) EvaluationSuccess { } } // if reason is disabled, we want to omit the value and variant from the response - if result.Reason == model.DisabledReason { + if result.Reason == model.DisabledReason && result.Variant == "" { return EvaluationSuccess{ Value: nil, // not marshalled due to omitempty Key: result.FlagKey, diff --git a/core/pkg/service/ofrep/models_test.go b/core/pkg/service/ofrep/models_test.go index a8dfdc0a8..dcd8eb01d 100644 --- a/core/pkg/service/ofrep/models_test.go +++ b/core/pkg/service/ofrep/models_test.go @@ -442,3 +442,28 @@ func TestZeroValuesAreMarshaled(t *testing.T) { }) } } + +// a resolve rule may return flagd's own reason names; with a variant set, the result is returned as-is +func TestSuccessResultRuleReasonWithVariant(t *testing.T) { + for _, reason := range []string{model.FallbackReason, model.DisabledReason} { + t.Run(reason, func(t *testing.T) { + success := SuccessResponseFrom(evaluator.AnyValue{ + Value: "#0000FF", + Variant: "blue", + Reason: reason, + FlagKey: "color", + Metadata: map[string]interface{}{}, + }) + + if success.Value != "#0000FF" { + t.Errorf("expected value #0000FF, got %v", success.Value) + } + if success.Variant != "blue" { + t.Errorf("expected variant blue, got %v", success.Variant) + } + if success.Reason != reason { + t.Errorf("expected reason %v, got %v", reason, success.Reason) + } + }) + } +} diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 0c0ee186a..98b65add9 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -10,6 +10,8 @@ description: flagd resolve custom operation A missing or null reason keeps `TARGETING_MATCH`. +The reason is free-form: any string is passed through as the evaluation reason, including flagd's own reasons such as `FALLBACK` or `DISABLED`. + Metadata is a shallow list of `[key, value]` pairs. Values are strings, numbers, or booleans. diff --git a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go index 1a3d68bd3..b29d3ff32 100644 --- a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go +++ b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go @@ -273,13 +273,14 @@ func resolveV2[T constraints](ctx context.Context, logger *logger.Logger, resolv spanFromContext := trace.SpanFromContext(ctx) spanFromContext.SetAttributes(telemetry.SemConvFeatureFlagAttributes(flagKey, variant)...) - switch reason { - case model.FallbackReason: + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + switch { + case reason == model.FallbackReason && variant == "": if err := setReasonOnlyV2(resp, model.DefaultReason, metadata); err != nil { logger.ErrorWithID(reqID, err.Error()) return fmt.Errorf("error setting fallback response: %w", err) } - case model.DisabledReason: + case reason == model.DisabledReason && variant == "": if err := setReasonOnlyV2(resp, model.DisabledReason, metadata); err != nil { logger.ErrorWithID(reqID, err.Error()) return fmt.Errorf("error setting disabled response: %w", err) diff --git a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go index 9e543614b..06a2339c4 100644 --- a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go +++ b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go @@ -124,6 +124,36 @@ func TestFlagEvaluationServiceV2_Fallback(t *testing.T) { } } +// TestFlagEvaluationServiceV2_RuleReasonWithVariant tests that a resolve rule may return flagd's own +// reason names: with a variant set, the result is returned as-is instead of as a fallback or disabled flag. +func TestFlagEvaluationServiceV2_RuleReasonWithVariant(t *testing.T) { + for _, reason := range []string{model.FallbackReason, model.DisabledReason} { + t.Run(reason, func(t *testing.T) { + ctrl := gomock.NewController(t) + eval := mock.NewMockIEvaluator(ctrl) + metrics, _ := getMetricReader() + s := NewFlagEvaluationServiceV2( + logger.NewLogger(nil, false), eval, &eventingConfiguration{}, + metrics, nil, nil, 0, + ) + eval.EXPECT().ResolveBooleanValue(gomock.Any(), gomock.Any(), "flag", gomock.Any()).Return( + true, "on", reason, metadata, nil, + ) + + got, err := s.ResolveBoolean(context.Background(), connect.NewRequest(&evalV2.ResolveBooleanRequest{ + FlagKey: "flag", Context: &structpb.Struct{}, + })) + + require.NoError(t, err) + require.NotNil(t, got.Msg.Value) + require.True(t, *got.Msg.Value) + require.NotNil(t, got.Msg.Variant) + require.Equal(t, "on", *got.Msg.Variant) + require.Equal(t, reason, got.Msg.Reason) + }) + } +} + func TestInvalidSelector_FlagEvaluationServiceV2(t *testing.T) { ctrl := gomock.NewController(t) eval := mock.NewMockIEvaluator(ctrl) From 517e8676ab988490d605a86e1d64f1ee1ecaed18 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Wed, 11 Nov 2026 16:14:25 +0100 Subject: [PATCH 05/20] fix(core): fall back to the default variant on malformed computed resolve arguments A computed resolve argument that was malformed, such as a null or non-string variant or a NaN metadata number, returned PARSE_ERROR. The other custom operators return null on error so the default variant is selected (#1874), and a plain computed string that yields null does the same. resolve now returns null in those cases, and logs the failure at debug, as request-driven failures must (#2018). Signed-off-by: marcozabel --- core/pkg/evaluator/hot_path_logging_test.go | 8 +++ core/pkg/evaluator/resolve.go | 17 ++---- core/pkg/evaluator/resolve_test.go | 58 +++++++++++++------ .../custom-operations/resolve-operation.md | 2 + 4 files changed, 56 insertions(+), 29 deletions(-) diff --git a/core/pkg/evaluator/hot_path_logging_test.go b/core/pkg/evaluator/hot_path_logging_test.go index 124072695..ca001fba3 100644 --- a/core/pkg/evaluator/hot_path_logging_test.go +++ b/core/pkg/evaluator/hot_path_logging_test.go @@ -51,6 +51,14 @@ func TestHotPathLoggingIsDebugOnly(t *testing.T) { targeting: `{"fractional": [["on", 50], ["off", 50]]}`, context: map[string]any{"targetingKey": ""}, }, + "resolve absent variant property": { + targeting: `{"resolve": [{"var": "variant"}]}`, + context: map[string]any{}, + }, + "resolve non-finite metadata": { + targeting: `{"resolve": ["on", null, [["share", {"/": [{"var": "hits"}, 0]}]]]}`, + context: map[string]any{"hits": 1}, + }, "$flagd in context": { targeting: `{"if": [{"==": [{"var": "email"}, "abc"]}, "on", "off"]}`, context: map[string]any{"$flagd": map[string]any{"flagKey": "spoofed"}}, diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 36aa5375f..a24c25763 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -15,12 +15,11 @@ const ResolveEvaluationName = "resolve" // resolveResult is what the operator returns. JsonLogic passes it through if/?: untouched (it only // re-applies maps), and since no JSON input decodes to it, context data cannot forge one. -// A nil reason keeps TARGETING_MATCH. err is set when evaluated arguments are malformed. +// A nil reason keeps TARGETING_MATCH. type resolveResult struct { variant string reason *string metadata map[string]any - err error } // ResolveEvaluator implements the terminal resolve operator. @@ -34,13 +33,13 @@ func NewResolveEvaluator(log *logger.Logger) *ResolveEvaluator { } // Evaluate returns a *resolveResult. Arguments are already evaluated by JsonLogic. -// Invalid evaluated arguments produce an error result rather than null, because a null -// targeting result would silently fall through to the default variant. +// Malformed evaluated arguments return null, like the other custom operators, so the flag falls back to its +// default variant. func (re *ResolveEvaluator) Evaluate(values, _ any) any { parsed, err := parseEvaluatedResolve(values) if err != nil { re.Logger.Debug("resolve evaluation failed", zap.Error(err)) - return &resolveResult{err: err} + return nil } return parsed } @@ -110,8 +109,8 @@ func metadataPair(pair any) (string, any, error) { return key, items[1], nil } -// metadataPrimitive rejects NaN and ±Inf (e.g. a computed 1/0): JSON can't encode them, so OFREP and Connect -// JSON responses would fail, taking a whole bulk response with them +// metadataPrimitive rejects NaN and ±Inf (e.g. a computed 1/0): JSON can't encode them, so returning them would +// fail OFREP and Connect JSON responses, taking a whole bulk response with them func metadataPrimitive(value any) (any, bool) { switch n := value.(type) { case string, bool: @@ -147,10 +146,6 @@ func (je *Resolver) applyResolveResult( if metadata == nil { metadata = map[string]any{} } - if parsed.err != nil { - je.Logger.ErrorWithID(reqID, fmt.Sprintf("resolve failed for flag %s: %s", flagKey, parsed.err)) - return "", model.ErrorReason, metadata, errors.New(model.ParseErrorCode) - } // variant keys are non-empty, and an empty variant is how flagd marks its own fallback and disabled // results, so an empty one is always missing if _, exists := flag.Variants[parsed.variant]; !exists || parsed.variant == "" { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 2c3d7a596..1c522d563 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -157,13 +157,6 @@ func TestResolveEvaluation(t *testing.T) { reason: model.ErrorReason, err: errors.New(model.GeneralErrorCode), }, - "computed non-string variant is a parse error": { - flags: resolveFlag(`{"resolve": [{"var": "pick"}]}`), - flagKey: "color", - context: map[string]any{"pick": 1}, - reason: model.ErrorReason, - err: errors.New(model.ParseErrorCode), - }, "shared evaluator inlines a terminal resolve": { flags: `{ "flags": { @@ -275,16 +268,6 @@ func TestResolveRuntimeErrors(t *testing.T) { }}, err: errors.New(model.GeneralErrorCode), }, - "computed +Inf metadata": { - targeting: nonFiniteMetadataRule, - context: map[string]any{"hits": 1, "total": 0}, - err: errors.New(model.ParseErrorCode), - }, - "computed NaN metadata": { - targeting: nonFiniteMetadataRule, - context: map[string]any{"hits": 0, "total": 0}, - err: errors.New(model.ParseErrorCode), - }, } for name, tt := range tests { @@ -306,6 +289,43 @@ func TestResolveRuntimeErrors(t *testing.T) { } } +// malformed computed arguments return null like the other custom operators, so the default variant is selected +func TestResolveMalformedComputedArguments(t *testing.T) { + tests := map[string]struct { + targeting string + context map[string]any + }{ + "null variant": {targeting: `{"resolve": [{"var": "pick"}]}`}, + "non-string variant": {targeting: `{"resolve": [{"var": "pick"}]}`, context: map[string]any{"pick": 1}}, + "non-string reason": {targeting: `{"resolve": ["red", {"var": "why"}]}`, context: map[string]any{"why": 1}}, + "non-primitive metadata": { + targeting: `{"resolve": ["red", null, [["details", {"var": "obj"}]]]}`, + context: map[string]any{"obj": map[string]any{"a": 1}}, + }, + "inside an if result": {targeting: `{"if": [true, {"resolve": [{"var": "pick"}]}, "blue"]}`}, + "+Inf metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 1, "total": 0}}, + "NaN metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 0, "total": 0}}, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(tt.targeting), Source: "testSource"})) + + value, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", tt.context) + require.NoError(t, err) + assert.Equal(t, "#FFFF00", value) + assert.Equal(t, "yellow", variant) + assert.Equal(t, model.DefaultReason, reason) + assert.NotContains(t, metadata, "share") + assert.NotContains(t, metadata, "details") + }) + } +} + // a computed ratio that is +Inf for total 0 and NaN for 0/0 const nonFiniteMetadataRule = `{"resolve": ["red", "SPLIT", [["share", {"/": [{"var": "hits"}, {"var": "total"}]}]]]}` @@ -334,7 +354,9 @@ func TestResolveNonFiniteMetadataInBulk(t *testing.T) { assert.NoError(t, value.Error) } if value.FlagKey == "ratio" { - assert.Equal(t, errors.New(model.ParseErrorCode), value.Error) + assert.NoError(t, value.Error) + assert.Equal(t, model.DefaultReason, value.Reason) + assert.NotContains(t, value.Metadata, "share") } } } diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 98b65add9..828bf1eeb 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -28,6 +28,8 @@ Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same config Arguments may be computed with other operators, such as `var` or `cat`. +When a computed argument is malformed, such as a variant that is not a string or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. + Older flagd binaries do not know this operator. Upgrade flagd before a configuration starts using `resolve`. From 66a6dddb76d4c187ea0d36c5a3ccb5aa9ae6552e Mon Sep 17 00:00:00 2001 From: marcozabel Date: Thu, 12 Nov 2026 11:30:03 +0100 Subject: [PATCH 06/20] test(core): check every branch of a nested resolve if Signed-off-by: marcozabel --- core/pkg/evaluator/resolve_test.go | 40 ++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 1c522d563..d2e5131fa 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -17,6 +17,15 @@ import ( func TestResolveEvaluation(t *testing.T) { const source = "testSource" ctx := context.Background() + nestedBranches := resolveFlag(`{ + "if": [ + {"==": [{"var": "id"}, "a"]}, + {"resolve": ["red", "ALLOWLIST", [["details", "customer-a"]]]}, + {"==": [{"var": "id"}, "b"]}, + {"resolve": ["red", "SPLIT", [["details", "customer-b"]]]}, + {"resolve": ["blue", "FALLTHROUGH", [["details", "else"]]]} + ] + }`) tests := map[string]struct { flags string @@ -97,16 +106,18 @@ func TestResolveEvaluation(t *testing.T) { "onlyRule": true, }, }, - "nested if branches stay distinguishable": { - flags: resolveFlag(`{ - "if": [ - {"==": [{"var": "id"}, "a"]}, - {"resolve": ["red", "ALLOWLIST", [["details", "customer-a"]]]}, - {"==": [{"var": "id"}, "b"]}, - {"resolve": ["red", "SPLIT", [["details", "customer-b"]]]}, - {"resolve": ["blue", "FALLTHROUGH", [["details", "else"]]]} - ] - }`), + // the first two branches serve the same variant, so only the reason and details tell them apart + "nested if first branch": { + flags: nestedBranches, + flagKey: "color", + context: map[string]any{"id": "a"}, + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{"details": "customer-a"}, + }, + "nested if second branch": { + flags: nestedBranches, flagKey: "color", context: map[string]any{"id": "b"}, value: "#FF0000", @@ -114,6 +125,15 @@ func TestResolveEvaluation(t *testing.T) { reason: "SPLIT", meta: map[string]any{"details": "customer-b"}, }, + "nested if else branch": { + flags: nestedBranches, + flagKey: "color", + context: map[string]any{"id": "z"}, + value: "#0000FF", + variant: "blue", + reason: "FALLTHROUGH", + meta: map[string]any{"details": "else"}, + }, "ternary result is terminal": { flags: resolveFlag(`{ "?:": [ From ac0464491c548cd6160b1c63c3bc85fbae7ac27e Mon Sep 17 00:00:00 2001 From: marcozabel Date: Thu, 12 Nov 2026 11:30:03 +0100 Subject: [PATCH 07/20] docs: show how to tag a fractional split with resolve Signed-off-by: marcozabel --- .../custom-operations/resolve-operation.md | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 828bf1eeb..cad61cdc8 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -22,10 +22,14 @@ Rule metadata overwrites flag metadata, which overwrites flag-set metadata. It is valid as the whole targeting rule, or as a result of `if` / `?:`. -flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, or an `if` condition, or when its literal arguments are malformed. +flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, an `if` condition, or a `fractional` bucket, or when its literal arguments are malformed. Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same configuration still load. +`fractional` buckets can't carry a reason or metadata yet. + +To tag a split, compare the `fractional` result in an `if` condition and use `resolve` in its branches, as in the [example below](#fractional-split). + Arguments may be computed with other operators, such as `var` or `cat`. When a computed argument is malformed, such as a variant that is not a string or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. @@ -80,3 +84,22 @@ Upgrade flagd before a configuration starts using `resolve`. The `alpha` and `beta` branches both say why they matched. The final branch selects `ga` with reason `FALLTHROUGH`. + +## Fractional split + +```json +{ + "if": [ + { + "==": [ + { "fractional": [{ "var": "targetingKey" }, ["on", 10], ["off", 90]] }, + "on" + ] + }, + { "resolve": ["on", "SPLIT_RANDOM", [["details", "10pct-rollout"]]] }, + { "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "holdback"]]] } + ] +} +``` + +Both buckets of the split now report which one fired. From 4aea53f6130b7b3ce3f2dc6311debc2b66d33996 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Fri, 13 Nov 2026 10:06:00 +0100 Subject: [PATCH 08/20] fix(core): reject resolve forms the targeting schema doesn't allow Align the load-time check with open-feature/flagd-schemas#238: the metadata list, its pairs and their keys must be literal, and resolve must be the only key in its object. Only the variant, the reason and metadata values may be computed. Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 27 +++++-------------- core/pkg/evaluator/resolve_test.go | 5 ++++ .../custom-operations/resolve-operation.md | 4 ++- 3 files changed, 14 insertions(+), 22 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index a24c25763..6c875bfc9 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -204,6 +204,9 @@ func walkResolve(node any, terminal bool, flagKey string) error { return nil } if len(rule) != 1 { + if _, ok := rule[ResolveEvaluationName]; ok { + return fmt.Errorf("flag %q: resolve must be the only key in its object", flagKey) + } for _, value := range rule { if err := walkResolve(value, false, flagKey); err != nil { return err @@ -287,21 +290,13 @@ func validateResolveReason(node any, flagKey string) error { return fmt.Errorf("flag %q: resolve reason must be a string or null", flagKey) } +// validateResolveMetadata follows the targeting schema: the pairs and their keys are literal, only values may be computed func validateResolveMetadata(node any, flagKey string) error { - if isJSONLogicRule(node) { - return walkResolve(node, false, flagKey) - } pairs, ok := node.([]any) if !ok { return fmt.Errorf("flag %q: resolve metadata must be an array of [key, value] pairs", flagKey) } for _, pair := range pairs { - if isJSONLogicRule(pair) { - if err := walkResolve(pair, false, flagKey); err != nil { - return err - } - continue - } if err := validateMetadataPair(pair, flagKey); err != nil { return err } @@ -314,22 +309,12 @@ func validateMetadataPair(pair any, flagKey string) error { if !ok || len(items) != 2 { return fmt.Errorf("flag %q: resolve metadata pair must be a [key, value] array", flagKey) } - if err := validateMetadataKey(items[0], flagKey); err != nil { - return err + if _, ok := items[0].(string); !ok { + return fmt.Errorf("flag %q: resolve metadata key must be a string", flagKey) } return validateMetadataValue(items[1], flagKey) } -func validateMetadataKey(node any, flagKey string) error { - if isJSONLogicRule(node) { - return walkResolve(node, false, flagKey) - } - if _, ok := node.(string); ok { - return nil - } - return fmt.Errorf("flag %q: resolve metadata key must be a string", flagKey) -} - func validateMetadataValue(node any, flagKey string) error { if isJSONLogicRule(node) { return walkResolve(node, false, flagKey) diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index d2e5131fa..96aa0e343 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -236,6 +236,11 @@ func TestResolveInvalidFlagAtLoad(t *testing.T) { "short pair": {targeting: `{"resolve": ["red", null, [["details"]]]}`}, "non-primitive value": {targeting: `{"resolve": ["red", null, [["details", {"nested": true}]]]}`}, "non-string key": {targeting: `{"resolve": ["red", null, [[1, "x"]]]}`}, + // the targeting schema only lets metadata values be computed + "computed metadata": {targeting: `{"resolve": ["red", null, {"var": "meta"}]}`}, + "computed pair": {targeting: `{"resolve": ["red", null, [{"var": "pair"}]]}`}, + "computed key": {targeting: `{"resolve": ["red", null, [[{"var": "key"}, "x"]]]}`}, + "extra operator": {targeting: `{"resolve": ["red"], "if": [true, "red"]}`}, "inlined bad evaluator": { targeting: `{"==": [{"$ref": "bad"}, "red"]}`, evaluators: `{"bad": {"resolve": ["red"]}}`, diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index cad61cdc8..7411ae4e8 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -30,7 +30,9 @@ Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same config To tag a split, compare the `fractional` result in an `if` condition and use `resolve` in its branches, as in the [example below](#fractional-split). -Arguments may be computed with other operators, such as `var` or `cat`. +The variant, the reason, and metadata values may be computed with other operators, such as `var` or `cat`. + +The metadata list, its pairs, and their keys must be literal. When a computed argument is malformed, such as a variant that is not a string or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. From d379961830acb0dbf01f20c74270eea65c8f53dd Mon Sep 17 00:00:00 2001 From: marcozabel Date: Mon, 16 Nov 2026 10:45:49 +0100 Subject: [PATCH 09/20] fix(core): treat a single if clause as a terminal result JsonLogic returns the sole clause of a one-clause if as its result, so a resolve there reaches the resolver unchanged and is valid. Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 4 ++-- core/pkg/evaluator/resolve_test.go | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 6c875bfc9..22376129f 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -237,8 +237,8 @@ func walkConditional(args any, parentTerminal bool, flagKey string) error { for i, clause := range clauses { terminal := false // if/?: results are the then-branches (odd indexes) and, when the length is odd, the final else. - // A single clause is only a condition: a falsy value becomes null, so it is not terminal. - if length > 1 && (i%2 == 1 || (length%2 == 1 && i == length-1)) { + // A single clause is that else: JsonLogic returns it as the result. + if i%2 == 1 || (length%2 == 1 && i == length-1) { terminal = parentTerminal } if err := walkResolve(clause, terminal, flagKey); err != nil { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 96aa0e343..0bc4f4c8f 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -148,6 +148,13 @@ func TestResolveEvaluation(t *testing.T) { variant: "yellow", reason: "FALLTHROUGH", }, + "single if clause is terminal": { + flags: resolveFlag(`{"if": [{"resolve": ["green", "ALLOWLIST"]}]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: "ALLOWLIST", + }, "computed variant reason and details": { flags: resolveFlag(`{ "resolve": [ From 92b156139960cceb2e6c1874c09b4cbc0c3c6b74 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Mon, 16 Nov 2026 10:48:24 +0100 Subject: [PATCH 10/20] feat(core): allow resolve as a fractional bucket variant A bucket's variant is now a terminal position, like an if/?: result, so each bucket of a split can carry its own reason and metadata. The bucketing value and the weights stay consumed. The bucket a user lands in depends only on the bucketing value and the weights, so wrapping a variant in resolve doesn't move anyone. The ADR moves fractional buckets from deferred to supported. Signed-off-by: marcozabel --- core/pkg/evaluator/fractional.go | 10 ++- core/pkg/evaluator/resolve.go | 35 +++++++++- core/pkg/evaluator/resolve_test.go | 70 ++++++++++++++----- .../targeting-variant-metadata.md | 26 ++----- .../custom-operations/fractional-operation.md | 1 + .../custom-operations/resolve-operation.md | 24 +++---- 6 files changed, 108 insertions(+), 58 deletions(-) diff --git a/core/pkg/evaluator/fractional.go b/core/pkg/evaluator/fractional.go index 8059395e2..24042807f 100644 --- a/core/pkg/evaluator/fractional.go +++ b/core/pkg/evaluator/fractional.go @@ -32,7 +32,7 @@ type fractionalEvaluationDistribution struct { } type fractionalEvaluationVariant struct { - variant any // string, bool, number or nil + variant any // string, bool, number, nil or *resolveResult weight int32 } @@ -212,7 +212,8 @@ func parseFractionalEvaluationDistributions(values []any, data any, logger *logg } // JSONLogic pre-evaluates all arguments before they reach fractional. - // Pre-evaluated operators become primitive values (strings, numbers, etc.), never map[string]any nodes. + // Pre-evaluated operators become primitive values (strings, numbers, etc.) or a resolve result, + // never map[string]any nodes. var variant any switch v := distributionArray[0].(type) { case string: @@ -223,8 +224,11 @@ func parseFractionalEvaluationDistributions(values []any, data any, logger *logg variant = v case nil: variant = nil + case *resolveResult: + variant = v default: - return nil, fmt.Errorf("flag %q: first element of distribution element must be a string, bool, number, or nil", flagKey) + return nil, fmt.Errorf( + "flag %q: first element of distribution element must be a string, bool, number, nil, or resolve", flagKey) } weight := int64(1) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 22376129f..e68f58f65 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -165,8 +165,8 @@ func (je *Resolver) applyResolveResult( // markInvalidResolveFlags marks flags that use resolve outside a terminal position or with malformed literal // arguments. Only the offending flag is invalid; the rest of the payload still loads. -// Terminal means the operator is the whole targeting rule, or a result branch of if / ?: whose own -// result is terminal. Its value must reach the resolver unchanged. +// Terminal means the operator is the whole targeting rule, or a result branch of if / ?: or a fractional bucket +// variant whose own result is terminal. Its value must reach the resolver unchanged. func (je *JSON) markInvalidResolveFlags(definition *Definition) { for i := range definition.Flags { flag := &definition.Flags[i] @@ -218,16 +218,45 @@ func walkResolve(node any, terminal bool, flagKey string) error { operator, args := onlyRuleEntry(rule) if operator == ResolveEvaluationName { if !terminal { - return fmt.Errorf("flag %q: resolve is only valid as the targeting result or an if/?: result", flagKey) + return fmt.Errorf( + "flag %q: resolve is only valid as the targeting result, an if/?: result, or a fractional bucket variant", + flagKey) } return validateResolveArguments(args, flagKey) } if operator == "if" || operator == "?:" { return walkConditional(args, terminal, flagKey) } + if operator == FractionEvaluationName { + return walkFractional(args, terminal, flagKey) + } return walkResolve(args, false, flagKey) } +// walkFractional treats each bucket's variant as a result. The bucketing value and the weights are consumed. +func walkFractional(args any, parentTerminal bool, flagKey string) error { + items, ok := args.([]any) + if !ok { + return walkResolve(args, false, flagKey) + } + for _, item := range items { + bucket, isBucket := item.([]any) + if !isBucket || len(bucket) == 0 { + if err := walkResolve(item, false, flagKey); err != nil { + return err + } + continue + } + if err := walkResolve(bucket[0], parentTerminal, flagKey); err != nil { + return err + } + if err := walkResolve(bucket[1:], false, flagKey); err != nil { + return err + } + } + return nil +} + func walkConditional(args any, parentTerminal bool, flagKey string) error { clauses, ok := args.([]any) if !ok { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 0bc4f4c8f..6898257dc 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -155,6 +155,36 @@ func TestResolveEvaluation(t *testing.T) { variant: "green", reason: "ALLOWLIST", }, + // a fixed bucketing value and zero weights pick the bucket deterministically + "fractional bucket variant is terminal": { + flags: resolveFlag(`{"fractional": ["key", + [{"resolve": ["red", "SPLIT", [["details", "treatment"]]]}, 1], + [{"resolve": ["blue", "SPLIT", [["details", "holdback"]]]}, 0] + ]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"details": "treatment"}, + }, + "fractional mixes plain and resolve buckets": { + flags: resolveFlag(`{"fractional": ["key", [{"resolve": ["red", "SPLIT"]}, 0], ["blue", 1]]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.TargetingMatchReason, + }, + "fractional in an if result": { + flags: resolveFlag(`{"if": [true, + {"fractional": ["key", [{"resolve": ["green", "SPLIT", [["details", "treatment"]]]}, 1]]}, + "blue" + ]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: "SPLIT", + meta: map[string]any{"details": "treatment"}, + }, "computed variant reason and details": { flags: resolveFlag(`{ "resolve": [ @@ -228,21 +258,24 @@ func TestResolveInvalidFlagAtLoad(t *testing.T) { targeting string evaluators string }{ - "inside equality": {targeting: `{"==": [{"resolve": ["red"]}, "red"]}`}, - "inside cat": {targeting: `{"cat": [{"resolve": ["red"]}, "x"]}`}, - "if condition": {targeting: `{"if": [{"resolve": ["red"]}, "red", "blue"]}`}, - "consumed by outer if": {targeting: `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`}, - "inside fractional": {targeting: `{"fractional": ["key", [{"resolve": ["red"]}, 1], ["blue", 1]]}`}, - "nested in resolve arg": {targeting: `{"resolve": [{"resolve": ["red"]}]}`}, - "result array": {targeting: `{"if": [true, [{"resolve": ["red"]}], "blue"]}`}, - "no arguments": {targeting: `{"resolve": []}`}, - "too many arguments": {targeting: `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`}, - "non-string variant": {targeting: `{"resolve": [true]}`}, - "non-string reason": {targeting: `{"resolve": ["red", 1]}`}, - "metadata object": {targeting: `{"resolve": ["red", null, {"details": "x"}]}`}, - "short pair": {targeting: `{"resolve": ["red", null, [["details"]]]}`}, - "non-primitive value": {targeting: `{"resolve": ["red", null, [["details", {"nested": true}]]]}`}, - "non-string key": {targeting: `{"resolve": ["red", null, [[1, "x"]]]}`}, + "inside equality": {targeting: `{"==": [{"resolve": ["red"]}, "red"]}`}, + "inside cat": {targeting: `{"cat": [{"resolve": ["red"]}, "x"]}`}, + "if condition": {targeting: `{"if": [{"resolve": ["red"]}, "red", "blue"]}`}, + "consumed by outer if": {targeting: `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`}, + "fractional bucketing value": {targeting: `{"fractional": [{"resolve": ["red"]}, ["red", 1]]}`}, + "fractional weight": {targeting: `{"fractional": ["key", ["red", {"resolve": ["red"]}]]}`}, + "consumed fractional": {targeting: `{"==": [{"fractional": ["key", [{"resolve": ["red"]}, 1]]}, "red"]}`}, + "fractional as if condition": {targeting: `{"if": [{"fractional": ["key", [{"resolve": ["red"]}, 1]]}, "red", "blue"]}`}, + "nested in resolve arg": {targeting: `{"resolve": [{"resolve": ["red"]}]}`}, + "result array": {targeting: `{"if": [true, [{"resolve": ["red"]}], "blue"]}`}, + "no arguments": {targeting: `{"resolve": []}`}, + "too many arguments": {targeting: `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`}, + "non-string variant": {targeting: `{"resolve": [true]}`}, + "non-string reason": {targeting: `{"resolve": ["red", 1]}`}, + "metadata object": {targeting: `{"resolve": ["red", null, {"details": "x"}]}`}, + "short pair": {targeting: `{"resolve": ["red", null, [["details"]]]}`}, + "non-primitive value": {targeting: `{"resolve": ["red", null, [["details", {"nested": true}]]]}`}, + "non-string key": {targeting: `{"resolve": ["red", null, [[1, "x"]]]}`}, // the targeting schema only lets metadata values be computed "computed metadata": {targeting: `{"resolve": ["red", null, {"var": "meta"}]}`}, "computed pair": {targeting: `{"resolve": ["red", null, [{"var": "pair"}]]}`}, @@ -335,8 +368,11 @@ func TestResolveMalformedComputedArguments(t *testing.T) { context: map[string]any{"obj": map[string]any{"a": 1}}, }, "inside an if result": {targeting: `{"if": [true, {"resolve": [{"var": "pick"}]}, "blue"]}`}, - "+Inf metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 1, "total": 0}}, - "NaN metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 0, "total": 0}}, + "inside a fractional bucket": { + targeting: `{"fractional": ["key", [{"resolve": [{"var": "pick"}]}, 1], ["blue", 0]]}`, + }, + "+Inf metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 1, "total": 0}}, + "NaN metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 0, "total": 0}}, } for name, tt := range tests { diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index b68f61256..e99e6d38a 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -3,7 +3,7 @@ status: accepted author: Parth Suthar created: 2026-07-30 -updated: 2026-10-16 +updated: 2026-11-16 --- # Per-evaluation metadata from targeting rules @@ -56,7 +56,7 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. -`resolve` is **terminal**: it is only valid as the whole targeting rule, or as a result branch of `if` / `?:` (recursively). Implementations reject it anywhere else when the flag is loaded, so its result always passes through to the resolver unchanged. +`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if` / `?:`, or as the variant of a `fractional` bucket (recursively). Implementations reject it anywhere else when the flag is loaded, so its result always passes through to the resolver unchanged. ### Evaluator changes @@ -144,7 +144,7 @@ Each branch tags the evaluation with the rule that fired: ### Example — nested `if` with a fractional split -`fractional` returns a plain string (`"on"` or `"off"`), and both are truthy under JsonLogic — so it can't be used directly as an `if` condition; wrapping it in `==` against a target bucket label makes it a real boolean: +A `fractional` bucket's variant is a terminal position too, so each bucket can carry its own reason and metadata. The bucket a user lands in depends only on the bucketing value and the weights, so wrapping a variant in `resolve` doesn't move anyone: ```json { @@ -152,21 +152,10 @@ Each branch tags the evaluation with the rule that fired: "if": [ { "==": [{ "var": "locale" }, "en-US"] }, { - "if": [ - { - "==": [ - { - "fractional": [ - { "var": "targetingKey" }, - ["on", 10], - ["off", 90] - ] - }, - "on" - ] - }, - { "resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]] }, - { "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "us-holdback"]]] } + "fractional": [ + { "var": "targetingKey" }, + [{ "resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]] }, 10], + [{ "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "us-holdback"]]] }, 90] ] }, { "resolve": ["off", "FALLTHROUGH", [["details", "non-us-off"]]] } @@ -238,4 +227,3 @@ Those scenarios run across the gRPC, OFREP, and in-process paths that `test/inte ## Open questions - **Config version.** Proposal: bump the targeting/flags schema to `v0.1` and gate the new terminus on it, leaving `v0` untouched for existing fleets. Sequencing of the hosted schema at `flagd.dev` is covered in the migration warning above. -- **Fractional buckets.** `fractional` returns a variant string directly, so it can't tag the picked bucket with metadata without a separate operator extension (e.g. an optional third element per weight tuple). Proposal: defer — ship the base `resolve` operator first. Nesting metadata into fractional is meaningfully more complicated and shouldn't block this. diff --git a/docs/reference/custom-operations/fractional-operation.md b/docs/reference/custom-operations/fractional-operation.md index fb2c91808..33b946089 100644 --- a/docs/reference/custom-operations/fractional-operation.md +++ b/docs/reference/custom-operations/fractional-operation.md @@ -95,6 +95,7 @@ This value should typically be something that remains consistent for the duratio The seed is typically the flagKey so that experiments running across different flags are statistically independent, however, you can also specify another seed to either align or further decouple your allocations across different feature flags or use-cases. The other elements in the array are nested arrays with the first element representing a variant and the second being the relative weight for this option. There is no limit to the number of elements. +A variant can also be a [`resolve`](./resolve-operation.md) operation, so each bucket can carry its own reason and metadata. > [!NOTE] > Previous versions of the `fractional` operation used percentage-based weights that had to sum to 100 and were limited to 1% precision. diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 7411ae4e8..fdbcd86de 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -20,16 +20,12 @@ Rule metadata overwrites flag metadata, which overwrites flag-set metadata. `resolve` is terminal. -It is valid as the whole targeting rule, or as a result of `if` / `?:`. +It is valid as the whole targeting rule, as a result of `if` / `?:`, or as the variant of a `fractional` bucket, as in the [example below](#fractional-split). -flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, an `if` condition, or a `fractional` bucket, or when its literal arguments are malformed. +flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, an `if` condition, or the bucketing value or weight of `fractional`, or when its literal arguments are malformed. Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same configuration still load. -`fractional` buckets can't carry a reason or metadata yet. - -To tag a split, compare the `fractional` result in an `if` condition and use `resolve` in its branches, as in the [example below](#fractional-split). - The variant, the reason, and metadata values may be computed with other operators, such as `var` or `cat`. The metadata list, its pairs, and their keys must be literal. @@ -91,17 +87,13 @@ The final branch selects `ga` with reason `FALLTHROUGH`. ```json { - "if": [ - { - "==": [ - { "fractional": [{ "var": "targetingKey" }, ["on", 10], ["off", 90]] }, - "on" - ] - }, - { "resolve": ["on", "SPLIT_RANDOM", [["details", "10pct-rollout"]]] }, - { "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "holdback"]]] } + "fractional": [ + [{ "resolve": ["on", "SPLIT", [["details", "treatment"]]] }, 10], + [{ "resolve": ["off", "SPLIT", [["details", "holdback"]]] }, 90] ] } ``` -Both buckets of the split now report which one fired. +Each bucket reports which one fired. + +Wrapping a bucket's variant in `resolve` does not change which bucket a user lands in. From 5bc69074bde909f3efaf81b729e2d4dc0da4818c Mon Sep 17 00:00:00 2001 From: marcozabel Date: Tue, 17 Nov 2026 11:02:44 +0100 Subject: [PATCH 11/20] refactor(core): rely on the targeting schema for resolve placement Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 7 - core/pkg/evaluator/resolve.go | 227 ------------------ core/pkg/evaluator/resolve_test.go | 78 ------ core/pkg/model/flag.go | 2 - .../targeting-variant-metadata.md | 2 +- .../custom-operations/resolve-operation.md | 4 +- docs/reference/flag-definitions.md | 2 +- 7 files changed, 4 insertions(+), 318 deletions(-) diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index bca31609a..1a383e374 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -421,12 +421,6 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return "", nil, model.DisabledReason, metadata, nil } - if flag.Invalid != "" { - // already warned at load, so per-evaluation logging stays at debug - je.Logger.DebugWithID(reqID, fmt.Sprintf("flag %s is invalid: %s", flagKey, flag.Invalid)) - return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) - } - // get the targeting logic, if any targeting := flag.Targeting @@ -614,7 +608,6 @@ func (je *JSON) configToFlagDefinition(config string, definition *Definition) er definition.Flags = flags } je.warnUnsafeNumericVariants(definition) - je.markInvalidResolveFlags(definition) return validateDefaultVariants(definition) } diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index e68f58f65..a3cf19a7e 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -1,7 +1,6 @@ package evaluator import ( - "encoding/json" "errors" "fmt" "math" @@ -162,229 +161,3 @@ func (je *Resolver) applyResolveResult( } return parsed.variant, reason, metadata, nil } - -// markInvalidResolveFlags marks flags that use resolve outside a terminal position or with malformed literal -// arguments. Only the offending flag is invalid; the rest of the payload still loads. -// Terminal means the operator is the whole targeting rule, or a result branch of if / ?: or a fractional bucket -// variant whose own result is terminal. Its value must reach the resolver unchanged. -func (je *JSON) markInvalidResolveFlags(definition *Definition) { - for i := range definition.Flags { - flag := &definition.Flags[i] - if err := validateResolveTargeting(*flag); err != nil { - flag.Invalid = err.Error() - je.Logger.Warn(fmt.Sprintf("%s; evaluating the flag returns %s", err, model.ParseErrorCode)) - } - } -} - -func validateResolveTargeting(flag model.Flag) error { - if len(flag.Targeting) == 0 || string(flag.Targeting) == "null" { - return nil - } - var node any - if err := json.Unmarshal(flag.Targeting, &node); err != nil { - return fmt.Errorf("flag %q: invalid targeting: %w", flag.Key, err) - } - return walkResolve(node, true, flag.Key) -} - -func walkResolve(node any, terminal bool, flagKey string) error { - rule, ok := node.(map[string]any) - if !ok { - // Arrays do not pass a nested resolve through as the targeting result. - items, isArray := node.([]any) - if !isArray { - return nil - } - for _, item := range items { - if err := walkResolve(item, false, flagKey); err != nil { - return err - } - } - return nil - } - if len(rule) != 1 { - if _, ok := rule[ResolveEvaluationName]; ok { - return fmt.Errorf("flag %q: resolve must be the only key in its object", flagKey) - } - for _, value := range rule { - if err := walkResolve(value, false, flagKey); err != nil { - return err - } - } - return nil - } - - operator, args := onlyRuleEntry(rule) - if operator == ResolveEvaluationName { - if !terminal { - return fmt.Errorf( - "flag %q: resolve is only valid as the targeting result, an if/?: result, or a fractional bucket variant", - flagKey) - } - return validateResolveArguments(args, flagKey) - } - if operator == "if" || operator == "?:" { - return walkConditional(args, terminal, flagKey) - } - if operator == FractionEvaluationName { - return walkFractional(args, terminal, flagKey) - } - return walkResolve(args, false, flagKey) -} - -// walkFractional treats each bucket's variant as a result. The bucketing value and the weights are consumed. -func walkFractional(args any, parentTerminal bool, flagKey string) error { - items, ok := args.([]any) - if !ok { - return walkResolve(args, false, flagKey) - } - for _, item := range items { - bucket, isBucket := item.([]any) - if !isBucket || len(bucket) == 0 { - if err := walkResolve(item, false, flagKey); err != nil { - return err - } - continue - } - if err := walkResolve(bucket[0], parentTerminal, flagKey); err != nil { - return err - } - if err := walkResolve(bucket[1:], false, flagKey); err != nil { - return err - } - } - return nil -} - -func walkConditional(args any, parentTerminal bool, flagKey string) error { - clauses, ok := args.([]any) - if !ok { - return walkResolve(args, false, flagKey) - } - length := len(clauses) - for i, clause := range clauses { - terminal := false - // if/?: results are the then-branches (odd indexes) and, when the length is odd, the final else. - // A single clause is that else: JsonLogic returns it as the result. - if i%2 == 1 || (length%2 == 1 && i == length-1) { - terminal = parentTerminal - } - if err := walkResolve(clause, terminal, flagKey); err != nil { - return err - } - } - return nil -} - -func validateResolveArguments(args any, flagKey string) error { - items, ok := args.([]any) - if !ok || len(items) < 1 || len(items) > 3 { - return fmt.Errorf("flag %q: resolve arguments must be an array of 1 to 3 items", flagKey) - } - if err := validateResolveVariant(items[0], flagKey); err != nil { - return err - } - if len(items) >= 2 { - if err := validateResolveReason(items[1], flagKey); err != nil { - return err - } - } - if len(items) == 3 { - return validateResolveMetadata(items[2], flagKey) - } - return nil -} - -func validateResolveVariant(node any, flagKey string) error { - if isJSONLogicRule(node) { - return walkResolve(node, false, flagKey) - } - if _, ok := node.(string); ok { - return nil - } - return fmt.Errorf("flag %q: resolve variant must be a string", flagKey) -} - -func validateResolveReason(node any, flagKey string) error { - if node == nil { - return nil - } - if isJSONLogicRule(node) { - return walkResolve(node, false, flagKey) - } - if _, ok := node.(string); ok { - return nil - } - return fmt.Errorf("flag %q: resolve reason must be a string or null", flagKey) -} - -// validateResolveMetadata follows the targeting schema: the pairs and their keys are literal, only values may be computed -func validateResolveMetadata(node any, flagKey string) error { - pairs, ok := node.([]any) - if !ok { - return fmt.Errorf("flag %q: resolve metadata must be an array of [key, value] pairs", flagKey) - } - for _, pair := range pairs { - if err := validateMetadataPair(pair, flagKey); err != nil { - return err - } - } - return nil -} - -func validateMetadataPair(pair any, flagKey string) error { - items, ok := pair.([]any) - if !ok || len(items) != 2 { - return fmt.Errorf("flag %q: resolve metadata pair must be a [key, value] array", flagKey) - } - if _, ok := items[0].(string); !ok { - return fmt.Errorf("flag %q: resolve metadata key must be a string", flagKey) - } - return validateMetadataValue(items[1], flagKey) -} - -func validateMetadataValue(node any, flagKey string) error { - if isJSONLogicRule(node) { - return walkResolve(node, false, flagKey) - } - switch node.(type) { - case string, float64, bool: - return nil - default: - return fmt.Errorf("flag %q: resolve metadata value must be a string, number, or boolean", flagKey) - } -} - -func isJSONLogicRule(node any) bool { - rule, ok := node.(map[string]any) - if !ok || len(rule) != 1 { - return false - } - operator, _ := onlyRuleEntry(rule) - return knownTargetingOperator(operator) -} - -// knownTargetingOperators are the operators JsonLogic will call. -// Any other single-key object is data, not a computed argument. -var knownTargetingOperators = map[string]struct{}{ - ResolveEvaluationName: {}, FractionEvaluationName: {}, - StartsWithEvaluationName: {}, EndsWithEvaluationName: {}, SemVerEvaluationName: {}, - "and": {}, "or": {}, "filter": {}, "map": {}, "reduce": {}, "all": {}, "none": {}, "some": {}, - "in": {}, "missing": {}, "missing_some": {}, "var": {}, "set": {}, "cat": {}, "substr": {}, "merge": {}, - "if": {}, "?:": {}, "max": {}, "min": {}, "+": {}, "-": {}, "*": {}, "/": {}, "%": {}, "abs": {}, - "!": {}, "!!": {}, "===": {}, "!==": {}, "==": {}, "!=": {}, "<": {}, "<=": {}, ">": {}, ">=": {}, - "contains_all": {}, "contains_any": {}, "contains_none": {}, -} - -func knownTargetingOperator(operator string) bool { - _, ok := knownTargetingOperators[operator] - return ok -} - -func onlyRuleEntry(rule map[string]any) (string, any) { - for operator, args := range rule { - return operator, args - } - return "", nil -} diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 6898257dc..5abb34b48 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -253,62 +253,6 @@ func TestResolveEvaluation(t *testing.T) { } } -func TestResolveInvalidFlagAtLoad(t *testing.T) { - tests := map[string]struct { - targeting string - evaluators string - }{ - "inside equality": {targeting: `{"==": [{"resolve": ["red"]}, "red"]}`}, - "inside cat": {targeting: `{"cat": [{"resolve": ["red"]}, "x"]}`}, - "if condition": {targeting: `{"if": [{"resolve": ["red"]}, "red", "blue"]}`}, - "consumed by outer if": {targeting: `{"if": [{"if": [true, {"resolve": ["red"]}, "blue"]}, "red", "blue"]}`}, - "fractional bucketing value": {targeting: `{"fractional": [{"resolve": ["red"]}, ["red", 1]]}`}, - "fractional weight": {targeting: `{"fractional": ["key", ["red", {"resolve": ["red"]}]]}`}, - "consumed fractional": {targeting: `{"==": [{"fractional": ["key", [{"resolve": ["red"]}, 1]]}, "red"]}`}, - "fractional as if condition": {targeting: `{"if": [{"fractional": ["key", [{"resolve": ["red"]}, 1]]}, "red", "blue"]}`}, - "nested in resolve arg": {targeting: `{"resolve": [{"resolve": ["red"]}]}`}, - "result array": {targeting: `{"if": [true, [{"resolve": ["red"]}], "blue"]}`}, - "no arguments": {targeting: `{"resolve": []}`}, - "too many arguments": {targeting: `{"resolve": ["red", "ALLOWLIST", [], "extra"]}`}, - "non-string variant": {targeting: `{"resolve": [true]}`}, - "non-string reason": {targeting: `{"resolve": ["red", 1]}`}, - "metadata object": {targeting: `{"resolve": ["red", null, {"details": "x"}]}`}, - "short pair": {targeting: `{"resolve": ["red", null, [["details"]]]}`}, - "non-primitive value": {targeting: `{"resolve": ["red", null, [["details", {"nested": true}]]]}`}, - "non-string key": {targeting: `{"resolve": ["red", null, [[1, "x"]]]}`}, - // the targeting schema only lets metadata values be computed - "computed metadata": {targeting: `{"resolve": ["red", null, {"var": "meta"}]}`}, - "computed pair": {targeting: `{"resolve": ["red", null, [{"var": "pair"}]]}`}, - "computed key": {targeting: `{"resolve": ["red", null, [[{"var": "key"}, "x"]]]}`}, - "extra operator": {targeting: `{"resolve": ["red"], "if": [true, "red"]}`}, - "inlined bad evaluator": { - targeting: `{"==": [{"$ref": "bad"}, "red"]}`, - evaluators: `{"bad": {"resolve": ["red"]}}`, - }, - } - - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - log := logger.NewLogger(nil, false) - s, err := store.NewStore(log, []string{"testSource"}) - require.NoError(t, err) - je := NewJSON(log, s) - flags := resolveFlagWithSibling(tt.targeting, tt.evaluators) - require.NoError(t, je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"})) - - _, _, reason, _, err := je.ResolveStringValue(context.Background(), "default", "color", nil) - assert.Equal(t, model.ErrorReason, reason) - assert.Equal(t, errors.New(model.ParseErrorCode), err) - - // the rest of the payload still loads - value, _, reason, _, err := je.ResolveBooleanValue(context.Background(), "default", "sibling", nil) - require.NoError(t, err) - assert.True(t, value) - assert.Equal(t, model.StaticReason, reason) - }) - } -} - func TestResolveRuntimeErrors(t *testing.T) { tests := map[string]struct { targeting string @@ -442,28 +386,6 @@ func TestParseEvaluatedResolve(t *testing.T) { require.Error(t, err) } -func resolveFlagWithSibling(targeting, evaluators string) string { - if evaluators == "" { - evaluators = "{}" - } - return `{ - "flags": { - "color": { - "state": "ENABLED", - "defaultVariant": "yellow", - "variants": {"red": "#FF0000", "blue": "#0000FF", "yellow": "#FFFF00"}, - "targeting": ` + targeting + ` - }, - "sibling": { - "state": "ENABLED", - "defaultVariant": "on", - "variants": {"on": true, "off": false} - } - }, - "$evaluators": ` + evaluators + ` - }` -} - func resolveFlag(targeting string) string { return `{ "flags": { diff --git a/core/pkg/model/flag.go b/core/pkg/model/flag.go index dc43a5877..228470e9a 100644 --- a/core/pkg/model/flag.go +++ b/core/pkg/model/flag.go @@ -17,8 +17,6 @@ type Flag struct { Targeting json.RawMessage `json:"targeting,omitempty"` Source string `json:"source"` Metadata Metadata `json:"metadata,omitempty"` - // Invalid is set at load when the targeting cannot be evaluated; evaluating the flag returns PARSE_ERROR - Invalid string `json:"-"` } type Evaluators struct { diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index e99e6d38a..2ec33a985 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -56,7 +56,7 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. -`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if` / `?:`, or as the variant of a `fractional` bucket (recursively). Implementations reject it anywhere else when the flag is loaded, so its result always passes through to the resolver unchanged. +`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if` / `?:`, or as the variant of a `fractional` bucket (recursively). The targeting schema rejects it anywhere else, so its result always passes through to the resolver unchanged; like any other configuration that doesn't conform to the schema, misplaced `resolve` is undefined behavior. ### Evaluator changes diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index fdbcd86de..6d9f3a4b0 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -22,9 +22,9 @@ Rule metadata overwrites flag metadata, which overwrites flag-set metadata. It is valid as the whole targeting rule, as a result of `if` / `?:`, or as the variant of a `fractional` bucket, as in the [example below](#fractional-split). -flagd marks a flag invalid at load time when `resolve` appears anywhere else, including inside `==`, `cat`, an `if` condition, or the bucketing value or weight of `fractional`, or when its literal arguments are malformed. +The [targeting schema](../schema.md) rejects `resolve` anywhere else, such as inside `==`, `cat`, or the bucketing value or weight of `fractional`, and rejects malformed literal arguments. -Evaluating an invalid flag returns `PARSE_ERROR`. Other flags in the same configuration still load. +Like any other configuration that doesn't conform to the schema, flagd logs a warning at load, and the evaluation result is undefined. The variant, the reason, and metadata values may be computed with other operators, such as `var` or `cat`. diff --git a/docs/reference/flag-definitions.md b/docs/reference/flag-definitions.md index 7ac7b058f..8a98e2bcb 100644 --- a/docs/reference/flag-definitions.md +++ b/docs/reference/flag-definitions.md @@ -398,7 +398,7 @@ Consistent with built-in JsonLogic operators, flagd's custom operators return fa flagd's custom operations return `null` on invalid or unexpected inputs, consistent with how built-in JsonLogic operations represent no-value returns, for example how `var` treats missing keys. When used inside an `if`, `null` is falsy, so evaluation falls through to the else branch rather than producing a false positive match. - `resolve` is the exception: it is only valid in a terminal position. flagd marks a flag that misuses it invalid at load, and evaluating that flag returns `PARSE_ERROR`. + `resolve` is the exception: it is only valid in a terminal position, which the targeting schema enforces. #### Targeting key From 68c756489c79caf723c1d511a0549a6e5c186d11 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Tue, 17 Nov 2026 11:03:35 +0100 Subject: [PATCH 12/20] fix(core): coerce boolean and number resolve variants like plain results Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 24 ++++++++++-- core/pkg/evaluator/resolve_test.go | 38 +++++++++++++++++-- .../targeting-variant-metadata.md | 2 +- .../custom-operations/resolve-operation.md | 4 +- docs/reference/flag-definitions.md | 2 +- 5 files changed, 61 insertions(+), 9 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index a3cf19a7e..5fed5ac17 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -1,6 +1,7 @@ package evaluator import ( + "encoding/json" "errors" "fmt" "math" @@ -49,9 +50,9 @@ func parseEvaluatedResolve(values any) (*resolveResult, error) { return nil, errors.New("resolve arguments must be an array of 1 to 3 items") } - variant, ok := args[0].(string) - if !ok { - return nil, errors.New("resolve variant must be a string") + variant, err := resolveVariantKey(args[0]) + if err != nil { + return nil, err } parsed := &resolveResult{variant: variant} @@ -73,6 +74,23 @@ func parseEvaluatedResolve(values any) (*resolveResult, error) { return parsed, nil } +// resolveVariantKey coerces the variant like a plain targeting result: booleans become "true"/"false", and numbers +// take their JSON form (unofficially, as for plain results) +func resolveVariantKey(value any) (string, error) { + switch v := value.(type) { + case string: + return v, nil + case bool, float64, float32, int, int32, int64, uint, uint32, uint64: + encoded, err := json.Marshal(v) + if err != nil { + return "", fmt.Errorf("resolve variant %v has no variant key: %w", v, err) + } + return string(encoded), nil + default: + return "", errors.New("resolve variant must be a string, boolean, or number") + } +} + func parseEvaluatedMetadata(value any) (map[string]any, error) { pairs, ok := value.([]any) if !ok { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 5abb34b48..639a063e6 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -200,6 +200,21 @@ func TestResolveEvaluation(t *testing.T) { reason: "ALLOWLIST", meta: map[string]any{"details": "us-10pct"}, }, + "boolean variant is coerced like a plain result": { + flags: coercedKeysFlag(`{"resolve": [true, "BETA"]}`), + flagKey: "coerced", + value: "#00FF00", + variant: "true", + reason: "BETA", + }, + "computed number variant is coerced like a plain result": { + flags: coercedKeysFlag(`{"resolve": [{"var": "pick"}]}`), + flagKey: "coerced", + context: map[string]any{"pick": 1}, + value: "#0000FF", + variant: "1", + reason: model.TargetingMatchReason, + }, "numeric and boolean metadata": { flags: resolveFlag(`{"resolve": ["red", "SPLIT", [["percent", 10], ["enabled", false]]]}`), flagKey: "color", @@ -304,9 +319,12 @@ func TestResolveMalformedComputedArguments(t *testing.T) { targeting string context map[string]any }{ - "null variant": {targeting: `{"resolve": [{"var": "pick"}]}`}, - "non-string variant": {targeting: `{"resolve": [{"var": "pick"}]}`, context: map[string]any{"pick": 1}}, - "non-string reason": {targeting: `{"resolve": ["red", {"var": "why"}]}`, context: map[string]any{"why": 1}}, + "null variant": {targeting: `{"resolve": [{"var": "pick"}]}`}, + "object variant": { + targeting: `{"resolve": [{"var": "pick"}]}`, + context: map[string]any{"pick": map[string]any{"a": 1}}, + }, + "non-string reason": {targeting: `{"resolve": ["red", {"var": "why"}]}`, context: map[string]any{"why": 1}}, "non-primitive metadata": { targeting: `{"resolve": ["red", null, [["details", {"var": "obj"}]]]}`, context: map[string]any{"obj": map[string]any{"a": 1}}, @@ -403,3 +421,17 @@ func resolveFlag(targeting string) string { } }` } + +// coercedKeysFlag has variants named "true", "false" and "1", which only a coerced variant can select +func coercedKeysFlag(targeting string) string { + return `{ + "flags": { + "coerced": { + "state": "ENABLED", + "defaultVariant": "false", + "variants": {"true": "#00FF00", "false": "#FF0000", "1": "#0000FF"}, + "targeting": ` + targeting + ` + } + } + }` +} diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index 2ec33a985..986ce7bef 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -51,7 +51,7 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional ### Arguments -- **`variant`** (1st): string. The only **required** argument, and the exact equivalent of the plain-string return: `"red"` and `{ "resolve": ["red"] }` are interchangeable terminals selecting the variant `red`. +- **`variant`** (1st): string. The only **required** argument, and the exact equivalent of the plain-string return: `"red"` and `{ "resolve": ["red"] }` are interchangeable terminals selecting the variant `red`. Like a plain-string return, a boolean is coerced to `"true"`/`"false"`; the behavior of numbers is not defined. - **`reason`** (2nd): string or `null`, optional. Free-form, operator-defined; overrides the top-level evaluation `reason` for this branch. The schema does not constrain it to an enum (see [Narrowing the coarse `reason`](#narrowing-the-coarse-reason)). - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 6d9f3a4b0..26154d207 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -8,6 +8,8 @@ description: flagd resolve custom operation `"red"` and `{ "resolve": ["red"] }` select the same variant. +The variant is coerced like a plain targeting result: booleans become `"true"` or `"false"`, and the behavior of numbers is not defined. + A missing or null reason keeps `TARGETING_MATCH`. The reason is free-form: any string is passed through as the evaluation reason, including flagd's own reasons such as `FALLBACK` or `DISABLED`. @@ -30,7 +32,7 @@ The variant, the reason, and metadata values may be computed with other operator The metadata list, its pairs, and their keys must be literal. -When a computed argument is malformed, such as a variant that is not a string or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. +When a computed argument is malformed, such as an object variant or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. Older flagd binaries do not know this operator. diff --git a/docs/reference/flag-definitions.md b/docs/reference/flag-definitions.md index 8a98e2bcb..6ee3168b4 100644 --- a/docs/reference/flag-definitions.md +++ b/docs/reference/flag-definitions.md @@ -392,7 +392,7 @@ Consistent with built-in JsonLogic operators, flagd's custom operators return fa | `starts_with` | Attribute starts with the specified value | string | Logic: `#!json { "starts_with" : [ "192.168.0.1", "192.168"] }`
Result: `true`

Logic: `#!json { "starts_with" : [ "10.0.0.1", "192.168"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `ends_with` | Attribute ends with the specified value | string | Logic: `#!json { "ends_with" : [ "noreply@example.com", "@example.com"] }`
Result: `true`

Logic: `#!json { ends_with" : [ "noreply@example.com", "@test.com"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `sem_ver` | Attribute matches a semantic versioning condition | string (valid [semver](https://semver.org/)) | Logic: `#!json {"sem_ver": ["1.1.2", ">=", "1.0.0"]}`
Result: `true`

Additional documentation can be found [here](./custom-operations/semver-operation.md). | -| `resolve` | Ends targeting with a variant, optional reason, and metadata | string variant; reason string or null; metadata pairs of string, number, or boolean | Logic: `#!json {"resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]]}`
Result: variant `on`, reason `SPLIT_RANDOM`, metadata `details`

Additional documentation can be found [here](./custom-operations/resolve-operation.md). | +| `resolve` | Ends targeting with a variant, optional reason, and metadata | string or boolean variant; reason string or null; metadata pairs of string, number, or boolean | Logic: `#!json {"resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]]}`
Result: variant `on`, reason `SPLIT_RANDOM`, metadata `details`

Additional documentation can be found [here](./custom-operations/resolve-operation.md). | !!! info "Error handling in custom operations" From 72229fddeda3eac5dc283f5f23a45240f0abddad Mon Sep 17 00:00:00 2001 From: marcozabel Date: Tue, 17 Nov 2026 11:03:48 +0100 Subject: [PATCH 13/20] refactor(core): drop ?: as a resolve terminal position Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 2 +- core/pkg/evaluator/resolve_test.go | 14 -------------- .../targeting-variant-metadata.md | 2 +- .../custom-operations/resolve-operation.md | 2 +- 4 files changed, 3 insertions(+), 17 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 5fed5ac17..44e09a067 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -13,7 +13,7 @@ import ( const ResolveEvaluationName = "resolve" -// resolveResult is what the operator returns. JsonLogic passes it through if/?: untouched (it only +// resolveResult is what the operator returns. JsonLogic passes it through if untouched (it only // re-applies maps), and since no JSON input decodes to it, context data cannot forge one. // A nil reason keeps TARGETING_MATCH. type resolveResult struct { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 639a063e6..349f41eba 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -134,20 +134,6 @@ func TestResolveEvaluation(t *testing.T) { reason: "FALLTHROUGH", meta: map[string]any{"details": "else"}, }, - "ternary result is terminal": { - flags: resolveFlag(`{ - "?:": [ - {"==": [{"var": "id"}, "a"]}, - {"resolve": ["green", "ALLOWLIST"]}, - {"resolve": ["yellow", "FALLTHROUGH"]} - ] - }`), - flagKey: "color", - context: map[string]any{"id": "z"}, - value: "#FFFF00", - variant: "yellow", - reason: "FALLTHROUGH", - }, "single if clause is terminal": { flags: resolveFlag(`{"if": [{"resolve": ["green", "ALLOWLIST"]}]}`), flagKey: "color", diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index 986ce7bef..07f20d358 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -56,7 +56,7 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. -`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if` / `?:`, or as the variant of a `fractional` bucket (recursively). The targeting schema rejects it anywhere else, so its result always passes through to the resolver unchanged; like any other configuration that doesn't conform to the schema, misplaced `resolve` is undefined behavior. +`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if`, or as the variant of a `fractional` bucket (recursively). The targeting schema rejects it anywhere else, so its result always passes through to the resolver unchanged; like any other configuration that doesn't conform to the schema, misplaced `resolve` is undefined behavior. ### Evaluator changes diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 26154d207..9455f57c7 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -22,7 +22,7 @@ Rule metadata overwrites flag metadata, which overwrites flag-set metadata. `resolve` is terminal. -It is valid as the whole targeting rule, as a result of `if` / `?:`, or as the variant of a `fractional` bucket, as in the [example below](#fractional-split). +It is valid as the whole targeting rule, as a result of `if`, or as the variant of a `fractional` bucket, as in the [example below](#fractional-split). The [targeting schema](../schema.md) rejects `resolve` anywhere else, such as inside `==`, `cat`, or the bucketing value or weight of `fractional`, and rejects malformed literal arguments. From a8f5e4d681ecc78ad33fa3534e4f2df648b6f8c0 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Tue, 17 Nov 2026 11:04:08 +0100 Subject: [PATCH 14/20] test(core): cover computed resolve metadata lists, pairs and keys Signed-off-by: marcozabel --- core/pkg/evaluator/resolve_test.go | 27 +++++++++++++++++++ .../targeting-variant-metadata.md | 2 ++ .../custom-operations/resolve-operation.md | 4 +-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 349f41eba..da2b54fbb 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -201,6 +201,33 @@ func TestResolveEvaluation(t *testing.T) { variant: "1", reason: model.TargetingMatchReason, }, + "computed metadata list": { + flags: resolveFlag(`{"resolve": ["red", null, {"var": "meta"}]}`), + flagKey: "color", + context: map[string]any{"meta": []any{[]any{"details", "from-context"}}}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "from-context"}, + }, + "computed metadata pair": { + flags: resolveFlag(`{"resolve": ["red", null, [{"var": "pair"}]]}`), + flagKey: "color", + context: map[string]any{"pair": []any{"details", "from-context"}}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "from-context"}, + }, + "computed metadata key": { + flags: resolveFlag(`{"resolve": ["red", null, [[{"cat": ["az-", {"var": "zone"}]}, "served"]]]}`), + flagKey: "color", + context: map[string]any{"zone": "a"}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"az-a": "served"}, + }, "numeric and boolean metadata": { flags: resolveFlag(`{"resolve": ["red", "SPLIT", [["percent", 10], ["enabled", false]]]}`), flagKey: "color", diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index 07f20d358..47ffa0a18 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -56,6 +56,8 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. +Every argument may be computed with JsonLogic: the variant, the reason, and the metadata list, its pairs, their keys, and their values. + `resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if`, or as the variant of a `fractional` bucket (recursively). The targeting schema rejects it anywhere else, so its result always passes through to the resolver unchanged; like any other configuration that doesn't conform to the schema, misplaced `resolve` is undefined behavior. ### Evaluator changes diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 9455f57c7..811264e46 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -28,9 +28,7 @@ The [targeting schema](../schema.md) rejects `resolve` anywhere else, such as in Like any other configuration that doesn't conform to the schema, flagd logs a warning at load, and the evaluation result is undefined. -The variant, the reason, and metadata values may be computed with other operators, such as `var` or `cat`. - -The metadata list, its pairs, and their keys must be literal. +Every argument may be computed with other operators, such as `var` or `cat`: the variant, the reason, and the metadata list, its pairs, their keys, and their values. When a computed argument is malformed, such as an object variant or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. From 7417653d5cfcd26f2b83e22f79d031bace5fa9de Mon Sep 17 00:00:00 2001 From: marcozabel Date: Wed, 18 Nov 2026 11:23:14 +0100 Subject: [PATCH 15/20] fix(core): keep context data from invoking the resolve operator JsonLogic re-applies a map returned from an if/?: branch, so a context value like {"resolve": [...]} reached through {"var": ...} was dispatched as a real resolve call, letting context data set the variant, reason and metadata. Bind the rule's own resolve calls to an internal operator name that no JSON-decoded context key can equal, and make a leftover "resolve" call return null so the flag falls back to its default variant. Signed-off-by: marcozabel --- core/pkg/evaluator/json.go | 8 ++++++-- core/pkg/evaluator/resolve.go | 33 ++++++++++++++++++++++++++++++ core/pkg/evaluator/resolve_test.go | 32 +++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 1a383e374..0d6f96309 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -169,7 +169,9 @@ func NewResolver(store store.IStore, logger *logger.Logger, jsonEvalTracer trace jsonlogic.AddOperator(StartsWithEvaluationName, NewStringComparisonEvaluator(logger).StartsWithEvaluation) jsonlogic.AddOperator(EndsWithEvaluationName, NewStringComparisonEvaluator(logger).EndsWithEvaluation) jsonlogic.AddOperator(SemVerEvaluationName, NewSemVerComparison(logger).SemVerEvaluation) - jsonlogic.AddOperator(ResolveEvaluationName, NewResolveEvaluator(logger).Evaluate) + resolveEvaluator := NewResolveEvaluator(logger) + jsonlogic.AddOperator(resolveOperatorName, resolveEvaluator.Evaluate) + jsonlogic.AddOperator(ResolveEvaluationName, resolveEvaluator.rejectFromContext) return Resolver{store: store, Logger: logger, tracer: jsonEvalTracer} } @@ -510,7 +512,9 @@ func applyTargeting(rule, data []byte) (any, error) { if err := json.Unmarshal(data, &parsedData); err != nil { return nil, err } - return jsonlogic.ApplyInterface(parsedRule, parsedData) + // parsedData comes from json.Unmarshal, so it cannot hold resolveOperatorName; only the rule's own resolve + // calls reach the operator + return jsonlogic.ApplyInterface(bindResolveOperator(parsedRule), parsedData) } func setFlagdProperties( diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 44e09a067..7867a0499 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -13,6 +13,12 @@ import ( const ResolveEvaluationName = "resolve" +// resolveOperatorName is the operator the rule's own resolve calls are bound to before evaluation. +// JsonLogic re-applies a map that some operators (if, ?:, reduce...) get back from a branch, so a context value like +// {"resolve": [...]} is dispatched as an operator call. The invalid UTF-8 byte keeps that from reaching this +// operator: json.Unmarshal replaces it with U+FFFD, so no decoded context key can equal this name. +const resolveOperatorName = ResolveEvaluationName + "\xff" + // resolveResult is what the operator returns. JsonLogic passes it through if untouched (it only // re-applies maps), and since no JSON input decodes to it, context data cannot forge one. // A nil reason keeps TARGETING_MATCH. @@ -44,6 +50,33 @@ func (re *ResolveEvaluator) Evaluate(values, _ any) any { return parsed } +// rejectFromContext handles "resolve" calls that are left after bindResolveOperator, which can only come from +// context data. It returns null, so the flag falls back to its default variant. +func (re *ResolveEvaluator) rejectFromContext(_, _ any) any { + re.Logger.Debug("ignoring resolve operator supplied by evaluation context") + return nil +} + +// bindResolveOperator renames the rule's resolve calls (single-key maps, as JsonLogic treats larger maps as +// literals) to resolveOperatorName, in place. Call it only on a freshly decoded rule, never on context data. +func bindResolveOperator(rule any) any { + switch node := rule.(type) { + case map[string]any: + if args, ok := node[ResolveEvaluationName]; ok && len(node) == 1 { + delete(node, ResolveEvaluationName) + node[resolveOperatorName] = args + } + for _, value := range node { + bindResolveOperator(value) + } + case []any: + for _, item := range node { + bindResolveOperator(item) + } + } + return rule +} + func parseEvaluatedResolve(values any) (*resolveResult, error) { args, ok := values.([]any) if !ok || len(args) < 1 || len(args) > 3 { diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index da2b54fbb..05e65345f 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -326,6 +326,38 @@ func TestResolveRuntimeErrors(t *testing.T) { } } +// jsonlogic re-applies a map that some operators (if, ?:...) get back from a branch, so a single-key +// context map like {"resolve": [...]} gets dispatched as an operator. It must not reach the real resolve +// operator: the flag falls back to its default variant, without the context's reason or metadata. +func TestResolveContextCannotInvokeResolve(t *testing.T) { + injected := map[string]any{"pick": map[string]any{ + "resolve": []any{"red", "INJECTED", []any{[]any{"flagSetId", "spoofed"}}}, + }} + + tests := map[string]string{ + "nested if": `{"if": [true, {"var": "pick"}, "blue"]}`, + "nested if else": `{"if": [false, "blue", {"var": "pick"}]}`, + "nested ?:": `{"?:": [true, {"var": "pick"}, "blue"]}`, + "inside resolve": `{"resolve": [{"if": [true, {"var": "pick"}, "blue"]}]}`, + } + + for name, targeting := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(targeting), Source: "testSource"})) + + _, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", injected) + require.NoError(t, err) + assert.Equal(t, "yellow", variant) + assert.Equal(t, model.DefaultReason, reason) + assert.NotContains(t, metadata, "flagSetId") + }) + } +} + // malformed computed arguments return null like the other custom operators, so the default variant is selected func TestResolveMalformedComputedArguments(t *testing.T) { tests := map[string]struct { From f6484bcc77bf626831559e97f789946f7d152299 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Wed, 18 Nov 2026 11:52:49 +0100 Subject: [PATCH 16/20] test(core): make resolve injection test independent of jsonlogic version jsonlogic v3.10.2 (on main) no longer re-applies maps returned from if/?: branches, so the injected map comes back as an invalid variant instead of selecting the default. Assert only what must hold on both versions: the context's variant, reason and metadata never come through. Signed-off-by: marcozabel --- core/pkg/evaluator/resolve_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index 05e65345f..b45e8fa3e 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -326,9 +326,10 @@ func TestResolveRuntimeErrors(t *testing.T) { } } -// jsonlogic re-applies a map that some operators (if, ?:...) get back from a branch, so a single-key -// context map like {"resolve": [...]} gets dispatched as an operator. It must not reach the real resolve -// operator: the flag falls back to its default variant, without the context's reason or metadata. +// a single-key context map like {"resolve": [...]} returned from a branch must never reach the real resolve +// operator. jsonlogic before v3.10.2 re-applies such maps as operator calls (the flag then falls back to its +// default variant); later versions return them as values (an invalid variant). Either way the context's variant, +// reason and metadata must not come through. func TestResolveContextCannotInvokeResolve(t *testing.T) { injected := map[string]any{"pick": map[string]any{ "resolve": []any{"red", "INJECTED", []any{[]any{"flagSetId", "spoofed"}}}, @@ -349,10 +350,9 @@ func TestResolveContextCannotInvokeResolve(t *testing.T) { je := NewJSON(log, s) require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(targeting), Source: "testSource"})) - _, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", injected) - require.NoError(t, err) - assert.Equal(t, "yellow", variant) - assert.Equal(t, model.DefaultReason, reason) + _, variant, reason, metadata, _ := je.ResolveStringValue(context.Background(), "default", "color", injected) + assert.NotEqual(t, "red", variant) + assert.NotEqual(t, "INJECTED", reason) assert.NotContains(t, metadata, "flagSetId") }) } From 6ee3a20b5dd0479051bedb555707bfa6eb366acb Mon Sep 17 00:00:00 2001 From: marcozabel Date: Thu, 19 Nov 2026 11:46:47 +0100 Subject: [PATCH 17/20] fix(core): leave resolve keys in literal rule data unbound Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 10 +++++++--- core/pkg/evaluator/resolve_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 7867a0499..85ce50eb8 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -57,12 +57,16 @@ func (re *ResolveEvaluator) rejectFromContext(_, _ any) any { return nil } -// bindResolveOperator renames the rule's resolve calls (single-key maps, as JsonLogic treats larger maps as -// literals) to resolveOperatorName, in place. Call it only on a freshly decoded rule, never on context data. +// bindResolveOperator renames the rule's resolve calls to resolveOperatorName, in place. Only single-key maps are +// operator calls; JsonLogic returns larger maps as literal data without evaluating them, so their contents are left +// unchanged. Call it only on a freshly decoded rule, never on context data. func bindResolveOperator(rule any) any { switch node := rule.(type) { case map[string]any: - if args, ok := node[ResolveEvaluationName]; ok && len(node) == 1 { + if len(node) != 1 { + return rule + } + if args, ok := node[ResolveEvaluationName]; ok { delete(node, ResolveEvaluationName) node[resolveOperatorName] = args } diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index b45e8fa3e..fdabbdd35 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -242,6 +242,23 @@ func TestResolveEvaluation(t *testing.T) { reason: model.ErrorReason, err: errors.New(model.GeneralErrorCode), }, + // a multi-key object is literal data to JsonLogic, so a "resolve" key nested in it must not be bound + "literal data keeps a nested resolve key": { + flags: resolveFlag(`{ + "if": [ + {"some": [ + [{"payload": {"resolve": "eu"}, "tag": 1}], + {"==": [{"var": "payload.resolve"}, "eu"]} + ]}, + {"resolve": ["red", "EU"]}, + "blue" + ] + }`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "EU", + }, "shared evaluator inlines a terminal resolve": { flags: `{ "flags": { From e31e23b9a795456059329524c479bb48aa269d90 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Fri, 20 Nov 2026 10:23:27 +0100 Subject: [PATCH 18/20] fix(core): keep resolve from overriding reserved flag set metadata flagSetId and version belong to flag set metadata. The schema rejects them as literal rule metadata keys; skip them at runtime too so computed keys can't override them either. Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 8 ++++ core/pkg/evaluator/resolve_test.go | 59 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 85ce50eb8..25fa5ac22 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -19,6 +19,10 @@ const ResolveEvaluationName = "resolve" // operator: json.Unmarshal replaces it with U+FFFD, so no decoded context key can equal this name. const resolveOperatorName = ResolveEvaluationName + "\xff" +// reservedMetadataKeys belong to flag set metadata. The schema rejects them as literal rule metadata keys; this +// also skips computed ones. +var reservedMetadataKeys = map[string]struct{}{"flagSetId": {}, "version": {}} + // resolveResult is what the operator returns. JsonLogic passes it through if untouched (it only // re-applies maps), and since no JSON input decodes to it, context data cannot forge one. // A nil reason keeps TARGETING_MATCH. @@ -208,6 +212,10 @@ func (je *Resolver) applyResolveResult( return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode) } for key, value := range parsed.metadata { + if _, reserved := reservedMetadataKeys[key]; reserved { + je.Logger.DebugWithID(reqID, fmt.Sprintf("ignoring reserved resolve metadata key: %s", key)) + continue + } metadata[key] = value } reason = model.TargetingMatchReason diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index fdabbdd35..a02661a93 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "testing" "github.com/open-feature/flagd/core/pkg/logger" @@ -298,6 +299,64 @@ func TestResolveEvaluation(t *testing.T) { } } +// flagSetId and version belong to flag set metadata, so rule metadata can't override or add them, literal or computed +func TestResolveReservedMetadataKeys(t *testing.T) { + const withSetMetadata = `{ + "metadata": {"flagSetId": "set", "version": "1"}, + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "yellow": "#FFFF00"}, + "targeting": %s + } + } + }` + literal := `{"resolve": ["red", null, [["flagSetId", "rule"], ["version", "rule"], ["details", "rule"]]]}` + computed := `{"resolve": ["red", null, [ + [{"cat": ["flagSet", "Id"]}, "rule"], [{"var": "key"}, "rule"], ["details", "rule"] + ]]}` + + tests := map[string]struct { + flags string + want map[string]any + }{ + "literal keys keep flag set values": { + flags: fmt.Sprintf(withSetMetadata, literal), + want: map[string]any{"flagSetId": "set", "version": "1"}, + }, + "computed keys keep flag set values": { + flags: fmt.Sprintf(withSetMetadata, computed), + want: map[string]any{"flagSetId": "set", "version": "1"}, + }, + "literal keys are not added": {flags: resolveFlag(literal)}, + "computed keys are not added": {flags: resolveFlag(computed)}, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: tt.flags, Source: "testSource"})) + + _, variant, _, metadata, err := je.ResolveStringValue( + context.Background(), "default", "color", map[string]any{"key": "version"}) + require.NoError(t, err) + assert.Equal(t, "red", variant) + assert.Equal(t, "rule", metadata["details"]) + for _, key := range []string{"flagSetId", "version"} { + if want, ok := tt.want[key]; ok { + assert.Equal(t, want, metadata[key]) + } else { + assert.NotContains(t, metadata, key) + } + } + }) + } +} + func TestResolveRuntimeErrors(t *testing.T) { tests := map[string]struct { targeting string From e243f8ff72a2f7f6dd9ff03298502305db387c3a Mon Sep 17 00:00:00 2001 From: marcozabel Date: Fri, 20 Nov 2026 10:23:48 +0100 Subject: [PATCH 19/20] refactor(core): drop the ?: injection case ?: is no longer a resolve terminal position. Signed-off-by: marcozabel --- core/pkg/evaluator/resolve.go | 2 +- core/pkg/evaluator/resolve_test.go | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go index 25fa5ac22..88d27350a 100644 --- a/core/pkg/evaluator/resolve.go +++ b/core/pkg/evaluator/resolve.go @@ -14,7 +14,7 @@ import ( const ResolveEvaluationName = "resolve" // resolveOperatorName is the operator the rule's own resolve calls are bound to before evaluation. -// JsonLogic re-applies a map that some operators (if, ?:, reduce...) get back from a branch, so a context value like +// JsonLogic re-applies a map that some operators (if, reduce...) get back from a branch, so a context value like // {"resolve": [...]} is dispatched as an operator call. The invalid UTF-8 byte keeps that from reaching this // operator: json.Unmarshal replaces it with U+FFFD, so no decoded context key can equal this name. const resolveOperatorName = ResolveEvaluationName + "\xff" diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go index a02661a93..f398ebc63 100644 --- a/core/pkg/evaluator/resolve_test.go +++ b/core/pkg/evaluator/resolve_test.go @@ -414,7 +414,6 @@ func TestResolveContextCannotInvokeResolve(t *testing.T) { tests := map[string]string{ "nested if": `{"if": [true, {"var": "pick"}, "blue"]}`, "nested if else": `{"if": [false, "blue", {"var": "pick"}]}`, - "nested ?:": `{"?:": [true, {"var": "pick"}, "blue"]}`, "inside resolve": `{"resolve": [{"if": [true, {"var": "pick"}, "blue"]}]}`, } From 3526e339e93068d2d6a40b41531e1f0b55a04a72 Mon Sep 17 00:00:00 2001 From: marcozabel Date: Fri, 20 Nov 2026 10:23:54 +0100 Subject: [PATCH 20/20] docs: note reserved flag set metadata keys for resolve Signed-off-by: marcozabel --- docs/reference/custom-operations/resolve-operation.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md index 811264e46..fd7d6a82f 100644 --- a/docs/reference/custom-operations/resolve-operation.md +++ b/docs/reference/custom-operations/resolve-operation.md @@ -18,7 +18,9 @@ Metadata is a shallow list of `[key, value]` pairs. Values are strings, numbers, or booleans. -Rule metadata overwrites flag metadata, which overwrites flag-set metadata. +Rule metadata overwrites flag metadata, which overwrites flag set metadata. + +`flagSetId` and `version` are reserved for flag set metadata and can't be overridden. `resolve` is terminal.