Skip to content

Commit d7078e0

Browse files
authored
feat: add protocol-v2 multivariate flag evaluation (#744)
## Summary - Make evaluator v2 a clean major release: `newEvaluator({ flags, segments })` prepares a complete collection and returns `evaluateAll(context)` and `evaluateFlag(context, flagKey)` methods. Remove the v1 value-rule API and legacy serialization helpers. - Batch evaluation returns `{ context, flags }` with normalized context once and independent per-flag results/diagnostics. One unresolved flag does not stop the remaining outputs. Single-flag evaluation visits only its selected root and dependencies. The methods map naturally to Node SDK `getFlags()` / `getFlagsForBootstrap()` and `getFlag()` respectively; SDK wrappers, overrides and fallbacks remain outside the evaluator. - Preserve flag and segment references instead of requiring publishers to inline their filters. Flag references match explicit variant keys, never the truthiness of variant values. Segments remain reusable predicates and can reference other segments or flags. - Resolve references recursively for every evaluation. **No dependency-result caching or memoization**; repeated references are evaluated again. Retain the existing definition-level membership Sets and percentage-bound preparation. - Preserve a valid matching referenced selection despite diagnostics from unsuccessful independent sibling rules. Nonmatches accompanied by diagnostics remain invalid through negation, so an uncertain negative reference cannot grant access. Ordinary authored AND/OR error handling is unchanged. Propagated diagnostics identify their original flag or segment. - Reject duplicate keys, missing references, unknown referenced variant keys and cycles during preparation, including mixed flag/segment cycles and unreachable references. Evaluating an unknown flag key also throws. - Preserve generic variant values and use a discriminated `resolved` result, distinguishing selected `undefined` from failure and requiring success metadata. - Keep prepared Sets and percentage bounds private. Precompute lookups/bounds once, use a simple allocation scan, and preserve boolean cohort hashing. - Return structured diagnostics instead of console logging. Invalid numeric/date comparisons cannot match through negation. - Keep the legacy Node SDK on published evaluator 1.1.2 via an npm alias, retaining main's v1 diagnostic fixes without linking it to the v2 workspace. Node SDK v2 adoption is separate in #790. ## Main synchronization Merged `main` at `abb17bd2f801a8b299ef02eca87b2d9ca774572a` through merge commit `486b2099e0d03f5e86566ab31660b0cb95b20ea8`. The reviewed collection evaluator source is unchanged. Main's SDK fixes, dependency updates and Vitest 4.1.11 migration are retained; an additional invalid-operator regression covers v2 fail-closed handling. No history was rewritten. The separate SDK branches were not changed and need their own synchronization with this updated base. ## API ```ts const evaluator = newEvaluator({ flags: compiledFlags, segments: compiledSegments, }); const batch = evaluator.evaluateAll(context); // { context, flags } const result = evaluator.evaluateFlag(context, "my-flag"); ``` Reference filters: ```ts { type: "flag", key: "model", variantKey: "quality" } { type: "segment", key: "enterprise" } ``` A matching selected variant is authoritative even if earlier rules produced diagnostics. A diagnostic-bearing nonmatch is deliberately more conservative than explicitly matching the selected fallback variant. Segments do not introduce independent-rule boundaries. ## Validation - **301 evaluator tests** and **265 legacy Node SDK tests** passed after the main merge. Consumer regressions also passed: **208 Browser, 65 React, 13 Vue, 27 OpenFeature Browser and 28 OpenFeature Node tests**. These are the v1 SDKs retained on this evaluator PR, not the separate SDK v2 branches. - **14 batch/single-flag API cases** cover result-type narrowing, output selection, normalized-context sharing, per-flag failure isolation, parity between operations, unrelated-root exclusion, no memoization in either definition order, returned-state isolation, selected undefined values, empty collections and dangerous object keys. - **71 collection/reference cases** cover the original independent-grant reproduction; both source-rule orders; missing context; unsupported arrays; invalid comparisons and operators; rollout/distribution behavior; nested flag/segment references; diagnostic provenance and deduplication; negative-reference safety; duplicate/missing/cyclic definitions; shared acyclic dependencies; and repeated evaluation without result caching. - Evaluator/test TypeScript checks and builds/declarations passed for evaluator, Node, Browser, React, Vue, both OpenFeature providers and React Native. Immutable installation, scoped formatting/lint and PR-delta whitespace checks passed. Scoped evaluator/Node lint has zero warnings/errors; repository lint has zero errors and one existing generated Next.js triple-slash-reference warning. Existing dependency peer warnings remain. Normal commit hooks passed without changing the verified content. - Existing definition-level benchmarks passed with the preceding collection change. No dependency-graph performance claim is made; correctness is the focus of this work. - Changesets release-plan validation selects evaluator 2.0.0, Node SDK 1.8.3 and OpenFeature Node 1.2.8; legacy SDKs are not migrated to the v2 protocol. - Full workspace build was previously attempted but blocked locally by missing Java for unrelated Management SDK OpenAPI generation; it was not rerun for this merge. No E2E was run in this checkpoint. Upstream-generated Management SDK files were retained unchanged; the PR delta contains no Management SDK changes. ## Scope Still a draft; nothing published or deployed. This layers the collection-based alternative discussed in #780 into v2 rather than adding `ruleEvaluation: "independent"` metadata to v1. #780 and its companion web PR are untouched. Publisher/compiler changes and matching server-side consumers are separate in reflagcom/web#3660. SDK adoption of `/flags` and variant-valued public APIs are separate in #790 and draft #791. Existing v1 consumers must not receive v2 reference nodes. Read-only inspection of web and its Advanced flags work (#3660) confirms the follow-up needs a distinct reference-preserving v2 lowering, reachable compiled segments, complete collection transport, and snapshot-level evaluator ownership. Boolean v2 rules must be compiled from normalized sources rather than copied from the already-inlined legacy rules. Keep legacy `/features` and config compilation unchanged, and retain the complete graph while selecting/authorizing output roots.
1 parent abb17bd commit d7078e0

16 files changed

Lines changed: 2667 additions & 2522 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
"@reflag/flag-evaluation": major
3+
---
4+
5+
Introduce a v2-only compiled-variant evaluator:
6+
7+
- `newEvaluator({ flags, segments })` prepares a complete collection and returns `evaluateAll(context)` and `evaluateFlag(context, flagKey)` methods. The batch result contains shared normalized context and per-flag results without repeated context. Single-flag evaluation visits only the requested flag and its dependencies. Unresolved batch entries do not prevent other flags from being evaluated. Remove the v1 value-rule APIs and the one-shot `evaluateFlag` wrapper.
8+
- Preserve flag and segment reference nodes instead of inlining their filters. Flag references explicitly match variant keys; segments remain reusable predicates. Resolve references recursively without dependency-result caching or memoization.
9+
- Preserve diagnostics from unsuccessful referenced rules without suppressing a valid matching selection. Invalid nonmatches remain fail-closed through negation. Propagated diagnostics identify their source flag or segment.
10+
- Reject duplicate keys, missing references, unknown referenced variant keys and cycles at preparation, including mixed flag/segment cycles. Evaluating an unknown flag key throws.
11+
- Preserve arbitrary variant value types through `CompiledFlag<T>` and `EvaluationResult<T>` (default `any`). `resolved: true | false` distinguishes a selected value, including `undefined`, from failure. Successful results require the variant key and matched rule ID.
12+
- Keep membership Sets and prepared percentage bounds private. `ANY_OF` / `NOT_ANY_OF` use cached Set lookups, including under groups and negations; percentage distributions use precomputed bounds and a simple scan.
13+
- Evaluate rules sequentially with explicit fallthrough and source-version/rule/allocation diagnostics.
14+
- Return structured `INVALID_COMPARISON` errors for invalid numeric/date comparisons instead of logging context values. Invalid conditions cannot match through negation.
15+
- Retain the original hash function and threshold rollout filter for boolean cohort compatibility. The inclusive maximum distribution bucket selects the last nonzero allocation.
16+
17+
The runtime exports are `newEvaluator`, `flattenContext`, and `hashInt`. Removed APIs include `evaluateFlagRules`, `newFlagEvaluator`, `evaluateFlag`, the scalar `evaluate` helper, and the legacy `flattenJSON` / `unflattenJSON` helpers.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@reflag/node-sdk": patch
3+
---
4+
5+
Keep the existing Node SDK on evaluator 1.1.2 through the `@reflag/flag-evaluation-v1` npm alias. This preserves its legacy protocol and prevents the evaluator's v2 workspace release from automatically upgrading its dependency before SDK migration.

‎packages/flag-evaluation/README.md‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# Flag evaluation v2
2+
3+
Prepare a complete collection of compiled flags and segments when definitions
4+
are loaded or refreshed, then evaluate all flags or select one flag for each context:
5+
6+
```ts
7+
import { newEvaluator } from "@reflag/flag-evaluation";
8+
9+
const evaluator = newEvaluator({
10+
flags: compiledFlags,
11+
segments: compiledSegments,
12+
});
13+
const context = { company: { id: "acme" }, user: { id: "alice" } };
14+
15+
// getFlags() / getFlagsForBootstrap(): all flags, one normalized context.
16+
const batch = evaluator.evaluateAll(context);
17+
const selected = batch.flags["my-flag"];
18+
19+
// getFlag(): just the requested flag and its dependencies.
20+
const result = evaluator.evaluateFlag(context, "my-flag");
21+
22+
// Diagnostics can accompany either a successful result or a failure.
23+
if (result.errors.length) console.warn(result.errors);
24+
25+
if (result.resolved) {
26+
// T, not T | undefined. An undefined variant value is still a success.
27+
console.log(result.value);
28+
// Required success metadata for diagnostics/exposure events.
29+
console.log(result.variantKey, result.matchedRuleId);
30+
} else {
31+
// No variant was selected: use the SDK's fallback behavior.
32+
}
33+
```
34+
35+
`CompiledFlag<T = any>`, `CompiledCollection<T = any>`,
36+
`FlagEvaluationResult<T = any>` and `EvaluationResult<T = any>` preserve the
37+
caller's value type. A heterogeneous collection can use a union for `T`.
38+
Non-fatal diagnostics may also accompany a successful default/fallthrough result.
39+
40+
`evaluateAll(context)` returns `CollectionEvaluationResult<T>`: a shared normalized
41+
`context` and a `flags` record keyed by flag key. Each entry is a
42+
`FlagEvaluationResult<T>` with its own resolution status, value, metadata and
43+
errors, without a repeated `context`. Unresolved flags do not prevent other flags
44+
from being evaluated; segments are not returned as outputs.
45+
46+
`evaluateFlag(context, flagKey)` returns `EvaluationResult<T>`, which adds normalized
47+
`context` to one flag result. It evaluates dependencies but not unrelated flags.
48+
Both operations use the complete collection for resolving references.
49+
50+
Rebuild the evaluator when definitions change. Treat definitions and returned
51+
values as immutable. Each operation has independent diagnostics. SDK-specific
52+
tracking, fallbacks, overrides and bootstrap snapshot versions remain outside the
53+
evaluator.
54+
55+
## References
56+
57+
A collection contains `flags: CompiledFlag<T>[]` and optional
58+
`segments: { key: string; filter: RuleFilter }[]`. Keep references in filters
59+
instead of substituting the referenced definition's filters:
60+
61+
```ts
62+
// Match the variant selected by another flag in the collection.
63+
const flagReference = { type: "flag", key: "model", variantKey: "quality" };
64+
// Reuse a segment predicate from the same collection.
65+
const segmentReference = { type: "segment", key: "enterprise" };
66+
// Negation and authored AND/OR groups work with either reference type.
67+
const negativeReference = { type: "negation", filter: flagReference };
68+
```
69+
70+
Flag references match **variant keys**, never the truthiness of variant values.
71+
The referenced flag uses its own ordered rules, distributions and rollout salts.
72+
A matching selection remains valid despite diagnostics from unsuccessful sibling
73+
rules. A nonmatch accompanied by diagnostics is invalid, not a clean `false`, so
74+
negating an uncertain nonmatch cannot grant access. A clean nonmatch can be
75+
negated. This is intentionally more conservative than explicitly matching a
76+
selected fallback variant.
77+
78+
Segments are predicates, not independent enable-rule groups: errors in a segment
79+
invalidate the containing rule, including through negation. Diagnostics propagated
80+
through references include `source: { type: "flag" | "segment", key: string }`
81+
identifying their original definition. Existing short-circuit behavior is retained;
82+
unvisited runtime branches do not produce diagnostics.
83+
84+
`newEvaluator` throws for duplicate keys, missing references, unknown referenced
85+
variant keys, and cycles, including mixed flag/segment cycles and references in
86+
unreachable branches. Evaluating an unknown flag key also throws. Flag and segment
87+
keys occupy separate namespaces.
88+
89+
References are evaluated recursively without dependency-result caching or
90+
memoization. Context is normalized once per call; repeated references are evaluated
91+
again. Only the existing definition-level membership Sets and percentage bounds
92+
are prepared ahead of time.
93+
94+
## Migration from v1
95+
96+
V2 exports `newEvaluator(collection)`, `flattenContext`, and `hashInt`, plus their
97+
public types. `newEvaluator` accepts a complete compiled collection, not value
98+
rules or a single flag. It returns an object with `evaluateAll(context)` and
99+
`evaluateFlag(context, flagKey)` methods, rather than a callable evaluator.
100+
Publishers and consumers must adopt the collection/reference protocol together;
101+
the unchanged Node SDK remains on the published v1 evaluator.
102+
103+
V1's `evaluateFlagRules`, scalar `evaluate`, `flattenJSON`, `unflattenJSON`, and
104+
value-rule types are removed. There is no v2 one-shot evaluation wrapper.
105+
The hash and `rolloutPercentage` filter remain to preserve boolean cohorts.
106+
107+
## Performance checks
108+
109+
From the repository root:
110+
111+
```sh
112+
yarn workspace @reflag/flag-evaluation exec vitest bench --run test/variants.bench.ts
113+
```
114+
115+
Benchmarks exclude preparation and compare with published v1 across candidate
116+
lists up to 100,000 and percentage distributions up to 50 allocations. Unit tests
117+
assert cached Set usage, no repeated percentage reads, and stable hash cohorts.

‎packages/flag-evaluation/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@reflag/flag-evaluation",
3-
"version": "1.1.2",
3+
"version": "2.0.0-next.0",
44
"license": "MIT",
55
"repository": {
66
"type": "git",
@@ -16,6 +16,7 @@
1616
},
1717
"scripts": {
1818
"build": "tsc --project tsconfig.build.json",
19+
"prepack": "yarn build",
1920
"test": "vitest",
2021
"test:ci": "vitest --reporter=default --reporter=junit --outputFile=junit.xml",
2122
"lint": "oxlint .",
@@ -30,6 +31,7 @@
3031
"js-sha256": "0.11.0"
3132
},
3233
"devDependencies": {
34+
"@reflag/flag-evaluation-v1": "npm:@reflag/flag-evaluation@1.1.2",
3335
"@reflag/tsconfig": "^0.0.2",
3436
"@types/node": "^22.12.0",
3537
"ts-node": "^10.9.2",

0 commit comments

Comments
 (0)