Skip to content

Commit a1bd963

Browse files
authored
fix: memoize v2 flag and segment dependencies (#803)
## Summary Memoize flag and segment results within each evaluation in `@reflag/flag-evaluation`. Without memoization, segments and flags that are referenced more than once are evaluated again at every reference. In a chain of 17 segments where each one references the previous segment twice, a single flag read performs 65,536 leaf comparisons. - Batch evaluation (`evaluateAll`) shares cached results across roots. Separate calls and contexts never share them, and there is no process-wide cache. - Cached errors still propagate to every rule that references them, and fail closed. Variant-key matching and rule traces are unchanged. - A `flag-evaluation` patch changeset releases this as `2.0.1`. Changesets updates `@reflag/node-sdk@2.0.0` to depend on it. Rebased onto current `main` as this single commit. The earlier Node SDK v2 history on this branch was already squash-merged into `main`. ## Validation - `@reflag/flag-evaluation`: 307 tests pass. `@reflag/node-sdk`: 288 tests pass. - Release-script tests pass (25). `changeset status` plans `flag-evaluation` 2.0.1 alongside the six 2.0.0 packages.
1 parent fb3b1a2 commit a1bd963

5 files changed

Lines changed: 231 additions & 38 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@reflag/flag-evaluation": patch
3+
---
4+
5+
Memoize flag and segment results within each evaluation to avoid repeated work in shared dependency graphs. Batch evaluation shares these results across roots, but separate calls and contexts never share cached results. Preserve variant-key matching, rule traces, diagnostic provenance and deduplication, and fail-closed handling of cached dependency errors.

‎packages/flag-evaluation/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,11 @@ variant keys, and cycles, including mixed flag/segment cycles and references in
8686
unreachable branches. Evaluating an unknown flag key also throws. Flag and segment
8787
keys occupy separate namespaces.
8888

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.
89+
Context is normalized once per call. Flag results and segment matches, errors, and
90+
diagnostics are memoized within that evaluation, including across roots in
91+
`evaluateAll`. Cached diagnostics are propagated into every referencing rule;
92+
results are never reused across calls or contexts. Definition-level membership
93+
Sets and percentage bounds are prepared ahead of time.
9394

9495
## Migration from v1
9596

‎packages/flag-evaluation/src/index.ts‎

Lines changed: 49 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,15 @@ type EvaluationState<T> = {
242242
flags: Map<string, PreparedFlag<T>>;
243243
segments: Map<string, PreparedFilter>;
244244
context: FlattenedContext;
245+
flagResults: Map<string, FlagEvaluationResult<T>>;
246+
segmentResults: Map<
247+
string,
248+
{
249+
matched: boolean;
250+
errors: Map<string, EvaluationError>;
251+
diagnostics: Map<string, EvaluationError>;
252+
}
253+
>;
245254
};
246255

247256
function prepareFilter(filter: RuleFilter): PreparedFilter {
@@ -448,7 +457,8 @@ function propagateErrors(
448457
errors?: Map<string, EvaluationError>,
449458
): void {
450459
for (const error of sourceErrors) {
451-
const diagnostic = error.source ? error : { ...error, source };
460+
// Cached diagnostics can reach multiple roots; keep their public objects independent.
461+
const diagnostic = { ...error, source: { ...(error.source ?? source) } };
452462
const key = JSON.stringify(diagnostic);
453463
diagnostics.set(key, diagnostic);
454464
errors?.set(key, diagnostic);
@@ -507,19 +517,28 @@ function evaluateFilter<T>(
507517
return matched;
508518
}
509519
case "segment": {
510-
const segmentErrors = new Map<string, EvaluationError>();
511-
const segmentDiagnostics = new Map<string, EvaluationError>();
512-
const matched = evaluateFilter(
513-
state.segments.get(filter.key)!,
514-
state,
515-
segmentErrors,
516-
segmentDiagnostics,
517-
);
520+
let result = state.segmentResults.get(filter.key);
521+
if (!result) {
522+
const segmentErrors = new Map<string, EvaluationError>();
523+
const segmentDiagnostics = new Map<string, EvaluationError>();
524+
const matched = evaluateFilter(
525+
state.segments.get(filter.key)!,
526+
state,
527+
segmentErrors,
528+
segmentDiagnostics,
529+
);
530+
result = {
531+
matched,
532+
errors: segmentErrors,
533+
diagnostics: segmentDiagnostics,
534+
};
535+
state.segmentResults.set(filter.key, result);
536+
}
518537
const source = { type: "segment" as const, key: filter.key };
519-
propagateErrors(segmentDiagnostics.values(), source, diagnostics);
520-
// Segments are predicates, not sets of independent enable rules.
521-
propagateErrors(segmentErrors.values(), source, diagnostics, errors);
522-
return matched && segmentErrors.size === 0;
538+
propagateErrors(result.diagnostics.values(), source, diagnostics);
539+
// Re-propagate cached failures into every containing rule, including negation.
540+
propagateErrors(result.errors.values(), source, diagnostics, errors);
541+
return result.matched && result.errors.size === 0;
523542
}
524543
case "group":
525544
for (const child of filter.filters) {
@@ -593,8 +612,8 @@ function validateReferences<T>(
593612
}
594613

595614
/**
596-
* Prepare a complete snapshot once on definition refresh. References are resolved
597-
* recursively for each call, without caching context-dependent results.
615+
* Prepare a complete snapshot once on definition refresh. Flag and segment results
616+
* are memoized within each evaluation, never across calls or contexts.
598617
* Throws for duplicate keys, missing references, unknown referenced variants or
599618
* cycles. Evaluating an unknown flag key also throws.
600619
*/
@@ -619,7 +638,13 @@ export function newEvaluator<T>(
619638
}
620639
validateReferences(flags, segments);
621640
function createState(context: Record<string, unknown>): EvaluationState<T> {
622-
return { flags, segments, context: flattenContext(context) };
641+
return {
642+
flags,
643+
segments,
644+
context: flattenContext(context),
645+
flagResults: new Map(),
646+
segmentResults: new Map(),
647+
};
623648
}
624649

625650
return {
@@ -647,6 +672,8 @@ function evaluatePreparedFlag<T>(
647672
flag: PreparedFlag<T>,
648673
state: EvaluationState<T>,
649674
): FlagEvaluationResult<T> {
675+
const cached = state.flagResults.get(flag.key);
676+
if (cached) return cached;
650677
const flatContext = state.context;
651678
const errors = new Map<string, EvaluationError>();
652679
const filterErrors = new Map<string, EvaluationError>();
@@ -710,7 +737,7 @@ function evaluatePreparedFlag<T>(
710737
);
711738
break;
712739
}
713-
return {
740+
const result: FlagEvaluationResult<T> = {
714741
resolved: true,
715742
flagKey: flag.key,
716743
sourceVersionId: flag.sourceVersionId,
@@ -721,18 +748,22 @@ function evaluatePreparedFlag<T>(
721748
matchedRuleId: rule.id,
722749
allocationIndex: ruleResult.allocationIndex,
723750
};
751+
state.flagResults.set(flag.key, result);
752+
return result;
724753
}
725754
if (!errors.has("invalid"))
726755
invalidDefinition(
727756
errors,
728757
"No rule selected a variant; a catch-all default is required",
729758
);
730-
return {
759+
const result: FlagEvaluationResult<T> = {
731760
resolved: false,
732761
value: undefined,
733762
flagKey: flag.key,
734763
sourceVersionId: flag.sourceVersionId,
735764
ruleResults,
736765
errors: Array.from(errors.values()),
737766
};
767+
state.flagResults.set(flag.key, result);
768+
return result;
738769
}

‎packages/flag-evaluation/test/collection.test.ts‎

Lines changed: 154 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, expectTypeOf, it, vi } from "vitest";
33
import {
44
CollectionEvaluationResult,
55
CompiledFlag,
6+
CompiledSegment,
67
EvaluationResult,
78
FlagEvaluationResult,
89
newEvaluator,
@@ -188,39 +189,182 @@ describe("batch and single-flag API", () => {
188189
});
189190

190191
it.each([false, true])(
191-
"re-evaluates dependencies without memoization, reversed: %s",
192+
"memoizes flag diamonds within each evaluation, reversed: %s",
192193
(reversed) => {
193194
const definitions = [
194195
flag("a", {
195196
type: "group",
196197
operator: "and",
197-
filters: [reference, reference],
198+
filters: [
199+
{ type: "flag", key: "left", variantKey: "on" },
200+
{ type: "flag", key: "right", variantKey: "on" },
201+
],
198202
}),
203+
flag("left", reference),
204+
flag("right", reference),
199205
flag("dependency", grant),
200206
];
201207
const evaluator = newEvaluator({
202208
flags: reversed ? definitions.reverse() : definitions,
203209
});
204210
const lookups = vi.spyOn(Set.prototype, "has");
205211
try {
206-
expect(evaluator.evaluateAll(context).flags.a.value).toBe(true);
207-
// Twice through a, once as a root output, regardless of definition order.
212+
for (const id of ["acme", "other", "acme"]) {
213+
const request = { company: { id } };
214+
lookups.mockClear();
215+
const batch = evaluator.evaluateAll(request);
216+
expect(Object.values(batch.flags).map(({ value }) => value)).toEqual(
217+
definitions.map(() => id === "acme"),
218+
);
219+
expect(
220+
lookups.mock.calls.filter(([value]) => value === id),
221+
).toHaveLength(1);
222+
lookups.mockClear();
223+
expect(evaluator.evaluateFlag(request, "a")).toEqual({
224+
...batch.flags.a,
225+
context: batch.context,
226+
});
227+
expect(
228+
lookups.mock.calls.filter(([value]) => value === id),
229+
).toHaveLength(1);
230+
}
231+
} finally {
232+
lookups.mockRestore();
233+
}
234+
},
235+
);
236+
237+
it("memoizes shared segment graphs across roots but not across calls", () => {
238+
const segments: CompiledSegment[] = [{ key: "s0", filter: grant }];
239+
for (let i = 1; i <= 16; i++) {
240+
segments.push({
241+
key: `s${i}`,
242+
filter: {
243+
type: "group",
244+
operator: "and",
245+
filters: [
246+
{ type: "segment", key: `s${i - 1}` },
247+
{ type: "segment", key: `s${i - 1}` },
248+
],
249+
},
250+
});
251+
}
252+
const evaluator = newEvaluator({
253+
flags: [
254+
flag("a", { type: "segment", key: "s16" }),
255+
flag("b", { type: "segment", key: "s16" }),
256+
],
257+
segments,
258+
});
259+
const lookups = vi.spyOn(Set.prototype, "has");
260+
try {
261+
for (const id of ["acme", "other", "acme"]) {
262+
const request = { company: { id } };
263+
lookups.mockClear();
264+
const batch = evaluator.evaluateAll(request);
265+
expect(batch.flags.a.value).toBe(id === "acme");
266+
expect(batch.flags.b.value).toBe(id === "acme");
208267
expect(
209-
lookups.mock.calls.filter(([value]) => value === "acme"),
210-
).toHaveLength(3);
268+
lookups.mock.calls.filter(([value]) => value === id),
269+
).toHaveLength(1);
270+
lookups.mockClear();
271+
expect(evaluator.evaluateFlag(request, "a")).toEqual({
272+
...batch.flags.a,
273+
context: batch.context,
274+
});
211275
expect(
212-
evaluator.evaluateAll({ company: { id: "other" } }).flags.a.value,
213-
).toBe(false);
214-
expect(evaluator.evaluateAll(context).flags.a.value).toBe(true);
276+
lookups.mock.calls.filter(([value]) => value === id),
277+
).toHaveLength(1);
278+
}
279+
} finally {
280+
lookups.mockRestore();
281+
}
282+
});
283+
284+
it.each(["flag", "segment", "unresolved flag"] as const)(
285+
"caches a failed %s while propagating errors to every referencing rule",
286+
(kind) => {
287+
const type = kind === "segment" ? "segment" : "flag";
288+
const dependency: RuleFilter =
289+
type === "segment"
290+
? { type, key: "dependency" }
291+
: { type, key: "dependency", variantKey: "on" };
292+
const failed: RuleFilter = {
293+
type: "group",
294+
operator: "and",
295+
filters: [grant, missing],
296+
};
297+
const parent = flag("a", { type: "negation", filter: dependency });
298+
parent.rules.unshift({ ...parent.rules[0], id: "repeated" });
299+
const child = flag("dependency", failed);
300+
if (kind === "unresolved flag") child.rules.pop();
301+
const evaluator = newEvaluator({
302+
flags: [
303+
parent,
304+
{ ...parent, key: "b" },
305+
...(type === "flag" ? [child] : []),
306+
],
307+
segments:
308+
type === "segment" ? [{ key: "dependency", filter: failed }] : [],
309+
});
310+
const lookups = vi.spyOn(Set.prototype, "has");
311+
try {
312+
const batch = evaluator.evaluateAll(context);
215313
expect(
216314
lookups.mock.calls.filter(([value]) => value === "acme"),
217-
).toHaveLength(6);
315+
).toHaveLength(1);
316+
for (const key of ["a", "b"]) {
317+
expect(batch.flags[key].value).toBe(false);
318+
expect(
319+
batch.flags[key].ruleResults.map(({ matched }) => matched),
320+
).toEqual([false, false, true]);
321+
expect(batch.flags[key].errors).toEqual([
322+
expect.objectContaining({
323+
code: "MISSING_CONTEXT_FIELD",
324+
source: { type, key: "dependency" },
325+
}),
326+
...(kind === "unresolved flag"
327+
? [
328+
expect.objectContaining({
329+
code: "INVALID_FLAG_DEFINITION",
330+
source: { type, key: "dependency" },
331+
}),
332+
]
333+
: []),
334+
]);
335+
const { context: _, ...single } = evaluator.evaluateFlag(
336+
context,
337+
key,
338+
);
339+
expect(single).toEqual(batch.flags[key]);
340+
}
218341
} finally {
219342
lookups.mockRestore();
220343
}
221344
},
222345
);
223346

347+
it("keeps cached nested diagnostics independent between batch outputs", () => {
348+
const evaluator = newEvaluator({
349+
flags: [
350+
flag("a", reference),
351+
flag("b", reference),
352+
flag("dependency", { type: "segment", key: "outer" }),
353+
],
354+
segments: [
355+
{ key: "outer", filter: { type: "segment", key: "inner" } },
356+
{ key: "inner", filter: missing },
357+
],
358+
});
359+
const first = evaluator.evaluateAll(context);
360+
const expected = structuredClone(first);
361+
first.flags.a.errors[0].source!.key = "changed";
362+
first.flags.a.ruleResults.length = 0;
363+
expect(first.flags.b).toEqual(expected.flags.b);
364+
expect(first.flags.dependency).toEqual(expected.flags.dependency);
365+
expect(evaluator.evaluateAll(context)).toEqual(expected);
366+
});
367+
224368
it("keeps diagnostics local to each flag and each call", () => {
225369
const evaluator = newEvaluator({
226370
flags: [flag("a", reference), flag("dependency", missing), flag("clean")],

0 commit comments

Comments
 (0)