Per-evaluation metadata from targeting rules
Let a targeting rule terminate with { "resolve": ["<key>", "<reason>", [["<metadata-key>", <value>], ...]] } in place of a plain variant string, so the branch that fired can annotate the evaluation with extra metadata, custom reasons, and other auxiliary information. Existing string returns are unchanged.
Background
An evaluation today returns value, variant, reason, and metadata. The reason is a coarse enum (TARGETING_MATCH, DEFAULT, STATIC, …); metadata carries only the static blocks defined at flag-set and flag level. Neither answers the debugging question we hit most often: which branch of the targeting expression fired?
For a nested if / and / or tree the resolver just returns the winning variant key. Two rules landing on the same variant are indistinguishable in the response — the only way to know why today is to fetch the flag config and re-run the logic by hand. Encoding the branch identity into the variant key ("clubs-eu-rollout-a") is the workaround, and it pollutes the variant space with debug info consumers then have to parse back out.
The plumbing to carry metadata already exists on most paths: AnyValue.Metadata (core/pkg/evaluator/ievaluator.go) is threaded through the evaluator and surfaced via OFREP (single and bulk) and single-resolution gRPC responses as flagMetadata. Two paths don't carry it yet — bulk gRPC ResolveAll and RecordEvaluation telemetry — but wiring those up is separate follow-up work.
Proposal
Add a resolve operator to schemas/json/targeting.json, alongside fractional, starts_with, ends_with, and sem_ver. Plain string returns are untouched:
{
"resolve": {
"description": "Terminates targeting with a variant, and optionally a custom reason and metadata for the branch that fired.",
"type": "array",
"minItems": 1,
"maxItems": 3,
"items": [
{
"description": "Variant: string, or boolean coerced to \"true\"/\"false\". Literal numbers and null are rejected. A computed rule is also accepted; it is coerced like a plain targeting result.",
"oneOf": [
{ "type": "string" },
{ "type": "boolean" },
{ "$ref": "#/definitions/anyRule" }
]
},
{
"description": "Reason: string, null, or a computed rule. A null or omitted reason keeps TARGETING_MATCH. Reasons other than TARGETING_MATCH and SPLIT that are defined by OpenFeature or flagd are reserved.",
"oneOf": [
{ "type": "null" },
{
"type": "string",
"not": {
"enum": ["ERROR", "DISABLED", "DEFAULT", "FALLBACK", "STATIC", "CACHED", "STALE", "UNKNOWN"]
}
},
{ "$ref": "#/definitions/anyRule" }
]
},
{
"description": "Metadata: [key, value] pairs. The list, each pair, each key, and each value may also be a computed rule. flagSetId and version are reserved for flag-set metadata.",
"oneOf": [
{ "$ref": "#/definitions/anyRule" },
{
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/definitions/anyRule" },
{
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": [
{
"oneOf": [
{ "type": "string", "not": { "enum": ["flagSetId", "version"] } },
{ "$ref": "#/definitions/anyRule" }
]
},
{
"oneOf": [
{ "type": ["string", "number", "boolean"] },
{ "$ref": "#/definitions/anyRule" }
]
}
]
}
]
}
}
]
}
]
}
}
Arguments
variant(1st): a literal string; a literal boolean, coerced to"true"or"false"; or a computed expression. The only required argument, and the exact equivalent of the plain-string return:"red"and{ "resolve": ["red"] }are interchangeable terminals selecting the variantred. Literal numbers andnullare rejected. Computed variants are coerced like plain targeting results: booleans become"true"/"false", and the behavior of numbers is not defined.reason(2nd): string,null, or a computed expression, optional. Free-form, operator-defined, apart from the reserved reasons below; overrides the top-level evaluationreasonfor this branch. Anullor omittedreasonkeepsTARGETING_MATCH(see Narrowing the coarsereason). Reasons defined by OpenFeature or flagd, other thanTARGETING_MATCHandSPLIT, are reserved (see Reserved reasons): the schema rejects them as literal reasons, and implementations ignore computed reasons that match, keepingTARGETING_MATCH.metadata(3rd): array of[key, value]pairs, optional, shallow. The whole list, each pair, each key, and each value may also be a computed expression. Literal values arestring | number | boolean, matching flag and flag-set metadata.flagSetIdandversionare reserved for flag-set metadata and cannot be overridden by rules; the schema rejects them as literal keys, and implementations skip computed keys that match.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; the result branches of if (recursively); and fractional bucket variants, in both the shorthand and the bucketing-value form. Every bucket variant is evaluated, and the selected one is returned.
The resolve operation is validated the same way as others: via JSON schema at load time only. The schema enforces terminality through separate terminalIfRule and terminalFractionalRule definitions reachable only from terminal positions, and by restricting the first if argument (always a condition) to plain args.
What the schema cannot enforce: resolve as a later else-if condition (positions 2, 4, … in a chained if), and resolve reached through $ref shared evaluators. Those cases are undefined behavior.
Evaluator changes
In evaluateVariant (core/pkg/evaluator/json.go), the current unconditional quote-strip of the JsonLogic result gains a resolve case ahead of it:
resolveresult: use itsvariantas the variant key (booleans are coerced to"true"/"false"officially; numbers are coerced like plain terminals, behavior not defined); shallow-merge itsmetadatapairs into the returned metadata; ifreasonis present and non-null, use it in place ofTARGETING_MATCH(anullor omittedreasonkeepsTARGETING_MATCH)- everything else → unchanged from today:
nullexits targeting todefaultVariant; strings, booleans, and numbers are quote-stripped into a variant key (so a booleantruestill resolves the"true"variant, asschemas/json/targeting.jsondocuments and the existing tests cover); a key absent fromvariantserrors exactly as it does now
Metadata merge precedence, lowest > highest, so more specific wins: flag-set metadata < flag metadata < rule-returned metadata. The reserved keys (flagSetId, version) are the exception: the schema rejects them as literal rule metadata keys, so they come from the existing flag evaluation flow.
Forward compatibility
Existing configs keep working on a new binary, but the reverse does not hold: a config using resolve, evaluated by an older flagd binary, fails with an unknown-operator error. flagd has to be upgraded fleet-wide before any config starts using resolve. This needs an explicit migration note in the release.
flagd-schemas is pre-1.0, so resolve merges into the v0 schema without a version bump; flagd core decides which schema version it uses by pinning the embedded snapshot it ships with.
Hold the hosted schema back. https://flagd.dev/schema/v0/flags.json is what editors and IDE tooling resolve against. Do not publish resolve there until it has landed in flagd and a few providers — otherwise editors will happily autocomplete a construct most of the fleet cannot evaluate.
Why an operator with array arguments rather than a returned object: JsonLogic engines disagree on objects. Some return a multi-key object as data (Go, Python, .NET), others reject it (JS, Rust, and Java outside if results), and C++ applies only its first key. A single-key object as an operator call, and arrays of primitives as arguments, behave the same in every engine flagd implementations use.
Metadata is an array of pairs for the same reason: an object argument fails to parse in Java, JS, and Rust.
Example — a full flag config
{
"$schema": "https://flagd.dev/schema/v0/flags.json",
"flags": {
"enable-mainframe-access": {
"state": "ENABLED",
"defaultVariant": "off",
"variants": {
"on": true,
"off": false,
},
"targeting": {
"if": [
{
"ends_with": [{ "var": "email" }, "@ingen.com"],
},
// new terminus — this node used to be the plain string "on"
{
"resolve": [
"on", // required
"my_super_cool_custom_reason", // optional
[], // custom metadata pairs, optionally including "details"
],
},
],
},
},
},
}
Example — chained if
Each branch tags the evaluation with the rule that fired:
{
"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"] }
]
}
}
}
Example — if with a fractional split
resolve is valid as a fractional bucket variant, so each bucket can carry its own reason and metadata directly:
{
"targeting": {
"if": [
{ "==": [{ "var": "locale" }, "en-US"] },
{
"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"]]] }
]
}
}
The 90% US holdback and the non-US off case both serve off but carry different reason and details values, so they stay distinguishable in telemetry.
Narrowing the coarse reason
flagd's top-level reason today (TARGETING_MATCH, DEFAULT, STATIC, DISABLED, ERROR, FALLBACK) says what class of evaluation happened but not which specific path inside it — every rule-driven result collapses to TARGETING_MATCH. A rule-scoped reason plus metadata.details sub-classifies that. The schema deliberately does not fix an enum: reason is an arbitrary string the operator defines, so each fleet picks whatever taxonomy fits it.
Note that the OpenFeature spec (evaluation details, requirement 6.1) types reason as a free-form string — the values in the spec (TARGETING_MATCH, SPLIT, DEFAULT, …) are recommended, not exhaustive, and providers are explicitly allowed to emit their own.
That means letting a branch-scoped reason override the top-level reason is spec-legal without any SDK contract change; SDK hooks and telemetry sinks already treat the field as opaque.
The user-facing reason does not match what the flagd engine actually evaluated for different variants of SPLIT. Today SPLIT covers both fractional and gradual rollout. Letting the rule override the reason is an easy win here, and the same applies to the several distinct kinds of OVERRIDE.
{ "resolve": ["on", "SPLIT_GRADUAL", [["details", "5%→50% ramp, week 3"]]] }
{ "resolve": ["on", "SPLIT_STEPPED", [["details", "stage 2 of 4, cohort=eu-west"]]] }
{ "resolve": ["on", "SPLIT_RANDOM", [["details", "50/50 A/B, salt=exp-4231"]]] }
Seeing these reasons instead of a bare SPLIT allows for much richer telemetry signals.
Reserved reasons
Every reason defined by OpenFeature or flagd is reserved, except TARGETING_MATCH and SPLIT, which describe rule-driven results and so remain valid for a rule to return.
Each reserved reason says something about the evaluation as a whole that a matched targeting branch cannot truthfully claim.
Set by flagd's own evaluation flow:
ERRORmeans the evaluation failed and is paired with anerrorCode; a rule that resolved a variant did not fail.DISABLEDmeans the flag is disabled, which flagd decides before targeting runs.DEFAULTmeans targeting did not pick a variant anddefaultVariantwas served.STATICmeans the flag has no targeting, so no rule ran.FALLBACKmeans the flag has nodefaultVariantand the caller's code default was used.
Set by providers and SDKs, not by the flag config:
CACHEDmeans the value was served from a provider cache.STALEmeans the value may be out of date.UNKNOWNmeans the reason could not be determined.
Hooks, telemetry sinks, and the evaluation-details data models in other language SDKs and providers branch on these values (for example, treating ERROR as a failed evaluation and looking for an errorCode, or CACHED as a cache hit). Letting a rule emit them would make a successful targeting match look like a failure, a disabled flag, a default fallback, or a cached result to every consumer downstream.
Like the reserved metadata keys, the schema rejects them as literals; implementations ignore a computed reason that evaluates to one of them, keeping TARGETING_MATCH.
Other patterns the free-form field unlocks inside a single TARGETING_MATCH:
- Split vs. allowlist under the same top-level reason — two paths reach the same variant, telemetry can tell them apart:
{ "resolve": ["on", "SPLIT", [["details", "10% cohort bucketed by email"]]] }
{ "resolve": ["on", "ALLOWLIST", [["details", "customerId in enterprise-pilot"]]] }
- Kill switch / override tagged distinctly — a branch short-circuiting an incident stays visible in traces:
- Audience-segment attribution — which specific condition inside a large predicate fired:
Testing
Beyond Go unit tests in core/pkg/evaluator, the flagd gherkin suite gets extended to cover the new terminus end-to-end: testbed flag configs using resolve, and scenarios in the shared feature files asserting the resolved variant, the overridden reason, and the merged flagMetadata (including details).
Those scenarios run across the gRPC, OFREP, and in-process paths that test/integration already exercises, which keeps every provider honest about the new shape rather than testing it only inside flagd.
Consequences
- Good — direct answer to "which branch fired" without overloading the variant key; no wire-format changes.
flagMetadatais already emitted on OpenFeature evaluation events and picked up by SDK hooks (OpenTelemetry, logging, custom exporters), so anything reading it — OTel spans, A/B dashboards, debug logs — picks up rule-level attribution automatically. - Good — backwards compatible for existing configs: string, boolean, number, and null returns are byte-for-byte unchanged on an upgraded flagd binary.
- Good — no OpenFeature spec change required.
reasonis already a first-class spec field, anddetailsridesflagMetadata, so no SDK gains a new resolution field. - Bad — not forward compatible: a config using
resolve, evaluated by an older flagd binary, fails with an unknown-operator error. Rollouts must upgrade flagd before configs start usingresolve. Needs an explicit migration note in the release. No schema version bump is needed — flagd-schemas is pre-1.0 andresolvemerges into the existingv0schema; flagd core pins the snapshot it embeds. - Bad — automatic telemetry attribution requires the separate
RecordEvaluationwork called out in Background; without it, rule ids rideflagMetadatafor SDK-side hooks but don't reach flagd's own OTel metrics.
Open questions
None outstanding. Schema version bump and fractional bucket support were both resolved during schema review (flagd-schemas#238, flagd#2127): no version bump is needed (pre-1.0), and resolve is now valid as a fractional bucket variant.