Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
91a209a
feat(core): implement the terminal resolve operator
marcozabel Nov 9, 2026
d7994b7
fix(core): return an unforgeable resolve result
marcozabel Nov 9, 2026
b80d06f
fix(core): mark only the misused resolve flag invalid
marcozabel Nov 9, 2026
5efaf01
fix: let a resolve reason be any string without changing the result
marcozabel Nov 10, 2026
517e867
fix(core): fall back to the default variant on malformed computed res…
marcozabel Nov 11, 2026
66a6ddd
test(core): check every branch of a nested resolve if
marcozabel Nov 12, 2026
ac04644
docs: show how to tag a fractional split with resolve
marcozabel Nov 12, 2026
4aea53f
fix(core): reject resolve forms the targeting schema doesn't allow
marcozabel Nov 13, 2026
d379961
fix(core): treat a single if clause as a terminal result
marcozabel Nov 16, 2026
92b1561
feat(core): allow resolve as a fractional bucket variant
marcozabel Nov 16, 2026
5bc6907
refactor(core): rely on the targeting schema for resolve placement
marcozabel Nov 17, 2026
68c7564
fix(core): coerce boolean and number resolve variants like plain results
marcozabel Nov 17, 2026
72229fd
refactor(core): drop ?: as a resolve terminal position
marcozabel Nov 17, 2026
a8f5e4d
test(core): cover computed resolve metadata lists, pairs and keys
marcozabel Nov 17, 2026
7417653
fix(core): keep context data from invoking the resolve operator
marcozabel Nov 18, 2026
f6484bc
test(core): make resolve injection test independent of jsonlogic version
marcozabel Nov 18, 2026
6ee3a20
fix(core): leave resolve keys in literal rule data unbound
marcozabel Nov 19, 2026
e31e23b
fix(core): keep resolve from overriding reserved flag set metadata
marcozabel Nov 20, 2026
e243f8f
refactor(core): drop the ?: injection case
marcozabel Nov 20, 2026
3526e33
docs: note reserved flag set metadata keys for resolve
marcozabel Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions core/pkg/evaluator/fractional.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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:
Expand All @@ -223,8 +224,11 @@ func parseFractionalEvaluationDistributions(values []any, data any, logger *logg
variant = v
case nil:
variant = nil
case *resolveResult:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, this covers resolve in fractional buckets for Go. The other in-process providers will need the same small change; I'll open issues for those.

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)
Expand Down
8 changes: 8 additions & 0 deletions core/pkg/evaluator/hot_path_logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}},
Expand Down
40 changes: 34 additions & 6 deletions core/pkg/evaluator/json.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package evaluator

import (
"bytes"
"context"
"encoding/json"
"errors"
Expand Down Expand Up @@ -36,7 +35,7 @@
jsonEvaluatorTracerName = "jsonEvaluator"
)

func addSchemaResource(compiler *jsonschema.Compiler, url string, schemaData string) error {

Check warning on line 38 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dn&open=AaHzY3-4NIrkaf_HM7dn&pullRequest=2127
unmarshalJSON, err := jsonschema.UnmarshalJSON(strings.NewReader(schemaData))
if err != nil {
return err
Expand Down Expand Up @@ -170,6 +169,9 @@
jsonlogic.AddOperator(StartsWithEvaluationName, NewStringComparisonEvaluator(logger).StartsWithEvaluation)
jsonlogic.AddOperator(EndsWithEvaluationName, NewStringComparisonEvaluator(logger).EndsWithEvaluation)
jsonlogic.AddOperator(SemVerEvaluationName, NewSemVerComparison(logger).SemVerEvaluation)
resolveEvaluator := NewResolveEvaluator(logger)
jsonlogic.AddOperator(resolveOperatorName, resolveEvaluator.Evaluate)
jsonlogic.AddOperator(ResolveEvaluationName, resolveEvaluator.rejectFromContext)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

return Resolver{store: store, Logger: logger, tracer: jsonEvalTracer}
}
Expand Down Expand Up @@ -225,7 +227,7 @@
}

func (je *Resolver) ResolveBooleanValue(
ctx context.Context, reqID string, flagKey string, context map[string]any) (

Check warning on line 230 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7do&open=AaHzY3-4NIrkaf_HM7do&pullRequest=2127
value bool,
variant string,
reason string,
Expand All @@ -240,7 +242,7 @@
}

func (je *Resolver) ResolveStringValue(
ctx context.Context, reqID string, flagKey string, context map[string]any) (

Check warning on line 245 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dp&open=AaHzY3-4NIrkaf_HM7dp&pullRequest=2127
value string,
variant string,
reason string,
Expand All @@ -255,7 +257,7 @@
}

func (je *Resolver) ResolveFloatValue(
ctx context.Context, reqID string, flagKey string, context map[string]any) (

Check warning on line 260 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dq&open=AaHzY3-4NIrkaf_HM7dq&pullRequest=2127
value float64,
variant string,
reason string,
Expand All @@ -282,7 +284,7 @@
return
}

func (je *Resolver) ResolveIntValue(ctx context.Context, reqID string, flagKey string, context map[string]any) (

Check warning on line 287 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dr&open=AaHzY3-4NIrkaf_HM7dr&pullRequest=2127
value int64,
variant string,
reason string,
Expand Down Expand Up @@ -336,7 +338,7 @@
}

func (je *Resolver) ResolveObjectValue(
ctx context.Context, reqID string, flagKey string, context map[string]any) (

Check warning on line 341 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7ds&open=AaHzY3-4NIrkaf_HM7ds&pullRequest=2127
value map[string]any,
variant string,
reason string,
Expand All @@ -352,7 +354,7 @@

func (je *Resolver) ResolveAsAnyValue(
ctx context.Context,
reqID string,

Check warning on line 357 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dt&open=AaHzY3-4NIrkaf_HM7dt&pullRequest=2127
flagKey string,
context map[string]any,
) AnyValue {
Expand All @@ -365,7 +367,7 @@
}

// resolve is a helper for generic flag resolving
func resolve[T constraints](ctx context.Context, reqID string, key string, context map[string]any,

Check warning on line 370 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7du&open=AaHzY3-4NIrkaf_HM7du&pullRequest=2127
variantEval variantEvaluator) (value T, variant string, reason string, metadata map[string]interface{}, err error,
) {
variant, variants, reason, metadata, err := variantEval(ctx, reqID, key, context)
Expand All @@ -373,12 +375,13 @@
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
}
Expand All @@ -393,7 +396,7 @@
}

// nolint: funlen
func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey string, evalCtx map[string]any) (

Check warning on line 399 in core/pkg/evaluator/json.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Group together these consecutive parameters of the same type.

See more on https://sonarcloud.io/project/issues?id=open-feature_flagd&issues=AaHzY3-4NIrkaf_HM7dv&open=AaHzY3-4NIrkaf_HM7dv&pullRequest=2127
variant string, variants map[string]interface{}, reason string, metadata map[string]interface{}, err error,
) {
var selector store.Selector
Expand Down Expand Up @@ -442,16 +445,27 @@
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 == "" {
Expand Down Expand Up @@ -489,6 +503,20 @@
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
}
// 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(
log *logger.Logger,
context map[string]any,
Expand Down
226 changes: 226 additions & 0 deletions core/pkg/evaluator/resolve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
package evaluator

import (
"encoding/json"
"errors"
"fmt"
"math"

"github.com/open-feature/flagd/core/pkg/logger"
"github.com/open-feature/flagd/core/pkg/model"
"go.uber.org/zap"
)

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"

// 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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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 {
variant string
reason *string
metadata map[string]any
}

// 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 *resolveResult. Arguments are already evaluated by JsonLogic.
// 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 nil
}
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 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 len(node) != 1 {
return rule
}
if args, ok := node[ResolveEvaluationName]; ok {
delete(node, ResolveEvaluationName)
node[resolveOperatorName] = args
}
for _, value := range node {
bindResolveOperator(value)
Comment thread
marcozabel marked this conversation as resolved.
Resolved
}
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 {
return nil, errors.New("resolve arguments must be an array of 1 to 3 items")
}

variant, err := resolveVariantKey(args[0])
if err != nil {
return nil, err
}
parsed := &resolveResult{variant: variant}

if len(args) >= 2 && args[1] != nil {
reason, ok := args[1].(string)
if !ok {
return nil, 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 nil, err
}
parsed.metadata = metadata
}
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 {
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, finite 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
}

// 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:
return n, true
case float64:
return n, isFinite(n)
case float32:
return float64(n), isFinite(float64(n))
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 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, parsed *resolveResult,
) (variant, reason string, meta map[string]any, err error) {
if metadata == nil {
metadata = map[string]any{}
}
// 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)
}
for key, value := range parsed.metadata {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flagSetId and version are reserved and can't be overridden by rule metadata (this is in the schema now), but they're overwritten here. The schema only checks literal keys, so we need a runtime check too, which also covers computed keys. Can we skip them here, and add a test with a literal and a computed flagSetId?

if _, reserved := reservedMetadataKeys[key]; reserved {
je.Logger.DebugWithID(reqID, fmt.Sprintf("ignoring reserved resolve metadata key: %s", key))
continue
}
metadata[key] = value
Comment thread
marcozabel marked this conversation as resolved.
Resolved
}
reason = model.TargetingMatchReason
if parsed.reason != nil {
reason = *parsed.reason
}
return parsed.variant, reason, metadata, nil
}
Loading
Loading