Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
18 changes: 18 additions & 0 deletions .changeset/node-sdk-collection-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
"@reflag/node-sdk": major
"@reflag/openfeature-node-provider": patch
---

Adopt evaluator v2 and the complete `GET /flags` collection protocol in the Node SDK.

- `getFlag(context, key)` and bound `getFlag(key)` are direct Boolean reads with an implicit `false` default. Positional defaults infer the value type, widening literals, without generated declarations. Non-null defaults require the same top-level JSON category; missing/mismatched values use the default without authored-selection metadata. An explicit `null` default accepts arbitrary JSON, including authored null. Nested payload schemas are not validated. There is no flag wrapper, `.isEnabled`, `.config`, or flag `.track()` method. Batch `getFlags()` keeps raw JSON/`undefined` values. Ordinary client `track()` APIs remain separate.
- Singular remote reads share the default contract. Root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` puts the default second, moving old positional IDs one place right; pass `undefined` for a Boolean read with IDs. Bound `getFlagRemote(key, defaultValue?)` needs no explicit IDs.
- Reads immediately register checks for requested roots. Checks carry the selected variant key as `evalResult`, `sourceVersionId`, and the snapshot `flagStateVersion`. Boolean values send the keys `"true"` / `"false"`. Equal-valued variants and dependency-only version changes retain their distinct identities. Delivery remains buffered and rate-limited.
- Prepare complete flags/segments snapshots before atomically accepting them. Memoize flag and segment dependency results within each evaluation, without sharing context-dependent results across calls.
- Persist full graphs and snapshot versions in version-2 fallback snapshots. V1 snapshots are not converted. Built-in storage uses separate versioned keys/files so V1 and V2 clients cannot overwrite one another's snapshots. Local overrides and value-only fallbacks do not fabricate authored variant selections.
- Bootstrap state contains v2 selection results and context/version metadata, without registering browser checks. Existing v1 browser bootstrap consumers require a separate migration; this is not a backwards-compatible bootstrap shape.
- Preserve sync modes, ordinary tracking, bound contexts, and post-evaluation override layering. Update the Express example to consume direct values.

The existing OpenFeature provider and v1 React bootstrap demo remain explicitly pinned to published Node SDK v1 through an npm alias. This prevents automatic workspace dependency upgrades from silently breaking their wrapper/bootstrap contracts; migrating those consumers to multivariate values is separate work.

This release requires the collection-capable evaluator and compatible `/flags` and variant-key check ingestion. It does not migrate legacy remote config into multivariate flag values.
5 changes: 5 additions & 0 deletions .changeset/node-sdk-registered-defaults.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reflag/node-sdk": patch
---

Check non-null singular-read defaults against the registered flag value type for local, remote, and bound getters. Accept named-interface and readonly defaults, while preserving Boolean bare reads, explicit-null arbitrary JSON, default-inferred widening, and runtime JSON validation/copying.
5 changes: 5 additions & 0 deletions .changeset/shared-dependency-memoization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reflag/flag-evaluation": patch
---

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.
2 changes: 1 addition & 1 deletion docs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ do
echo "Processing $file..."

# Fix anchor links in globals.md files
if [[ "$file" == *"globals.md" ]]; then
if [ "${file##*/}" = "globals.md" ]; then
sed -r "$SEDCOMMAND" "$file" > "$file.fixed"
rm "$file"
mv "$file.fixed" "$file"
Expand Down
9 changes: 5 additions & 4 deletions packages/flag-evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,11 @@ variant keys, and cycles, including mixed flag/segment cycles and references in
unreachable branches. Evaluating an unknown flag key also throws. Flag and segment
keys occupy separate namespaces.

References are evaluated recursively without dependency-result caching or
memoization. Context is normalized once per call; repeated references are evaluated
again. Only the existing definition-level membership Sets and percentage bounds
are prepared ahead of time.
Context is normalized once per call. Flag results and segment matches, errors, and
diagnostics are memoized within that evaluation, including across roots in
`evaluateAll`. Cached diagnostics are propagated into every referencing rule;
results are never reused across calls or contexts. Definition-level membership
Sets and percentage bounds are prepared ahead of time.

## Migration from v1

Expand Down
67 changes: 49 additions & 18 deletions packages/flag-evaluation/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,15 @@ type EvaluationState<T> = {
flags: Map<string, PreparedFlag<T>>;
segments: Map<string, PreparedFilter>;
context: FlattenedContext;
flagResults: Map<string, FlagEvaluationResult<T>>;
segmentResults: Map<
string,
{
matched: boolean;
errors: Map<string, EvaluationError>;
diagnostics: Map<string, EvaluationError>;
}
>;
};

function prepareFilter(filter: RuleFilter): PreparedFilter {
Expand Down Expand Up @@ -448,7 +457,8 @@ function propagateErrors(
errors?: Map<string, EvaluationError>,
): void {
for (const error of sourceErrors) {
const diagnostic = error.source ? error : { ...error, source };
// Cached diagnostics can reach multiple roots; keep their public objects independent.
const diagnostic = { ...error, source: { ...(error.source ?? source) } };
const key = JSON.stringify(diagnostic);
diagnostics.set(key, diagnostic);
errors?.set(key, diagnostic);
Expand Down Expand Up @@ -507,19 +517,28 @@ function evaluateFilter<T>(
return matched;
}
case "segment": {
const segmentErrors = new Map<string, EvaluationError>();
const segmentDiagnostics = new Map<string, EvaluationError>();
const matched = evaluateFilter(
state.segments.get(filter.key)!,
state,
segmentErrors,
segmentDiagnostics,
);
let result = state.segmentResults.get(filter.key);
if (!result) {
const segmentErrors = new Map<string, EvaluationError>();
const segmentDiagnostics = new Map<string, EvaluationError>();
const matched = evaluateFilter(
state.segments.get(filter.key)!,
state,
segmentErrors,
segmentDiagnostics,
);
result = {
matched,
errors: segmentErrors,
diagnostics: segmentDiagnostics,
};
state.segmentResults.set(filter.key, result);
}
const source = { type: "segment" as const, key: filter.key };
propagateErrors(segmentDiagnostics.values(), source, diagnostics);
// Segments are predicates, not sets of independent enable rules.
propagateErrors(segmentErrors.values(), source, diagnostics, errors);
return matched && segmentErrors.size === 0;
propagateErrors(result.diagnostics.values(), source, diagnostics);
// Re-propagate cached failures into every containing rule, including negation.
propagateErrors(result.errors.values(), source, diagnostics, errors);
return result.matched && result.errors.size === 0;
}
case "group":
for (const child of filter.filters) {
Expand Down Expand Up @@ -593,8 +612,8 @@ function validateReferences<T>(
}

/**
* Prepare a complete snapshot once on definition refresh. References are resolved
* recursively for each call, without caching context-dependent results.
* Prepare a complete snapshot once on definition refresh. Flag and segment results
* are memoized within each evaluation, never across calls or contexts.
* Throws for duplicate keys, missing references, unknown referenced variants or
* cycles. Evaluating an unknown flag key also throws.
*/
Expand All @@ -619,7 +638,13 @@ export function newEvaluator<T>(
}
validateReferences(flags, segments);
function createState(context: Record<string, unknown>): EvaluationState<T> {
return { flags, segments, context: flattenContext(context) };
return {
flags,
segments,
context: flattenContext(context),
flagResults: new Map(),
segmentResults: new Map(),
};
}

return {
Expand Down Expand Up @@ -647,6 +672,8 @@ function evaluatePreparedFlag<T>(
flag: PreparedFlag<T>,
state: EvaluationState<T>,
): FlagEvaluationResult<T> {
const cached = state.flagResults.get(flag.key);
if (cached) return cached;
const flatContext = state.context;
const errors = new Map<string, EvaluationError>();
const filterErrors = new Map<string, EvaluationError>();
Expand Down Expand Up @@ -710,7 +737,7 @@ function evaluatePreparedFlag<T>(
);
break;
}
return {
const result: FlagEvaluationResult<T> = {
resolved: true,
flagKey: flag.key,
sourceVersionId: flag.sourceVersionId,
Expand All @@ -721,18 +748,22 @@ function evaluatePreparedFlag<T>(
matchedRuleId: rule.id,
allocationIndex: ruleResult.allocationIndex,
};
state.flagResults.set(flag.key, result);
return result;
}
if (!errors.has("invalid"))
invalidDefinition(
errors,
"No rule selected a variant; a catch-all default is required",
);
return {
const result: FlagEvaluationResult<T> = {
resolved: false,
value: undefined,
flagKey: flag.key,
sourceVersionId: flag.sourceVersionId,
ruleResults,
errors: Array.from(errors.values()),
};
state.flagResults.set(flag.key, result);
return result;
}
164 changes: 154 additions & 10 deletions packages/flag-evaluation/test/collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, expectTypeOf, it, vi } from "vitest";
import {
CollectionEvaluationResult,
CompiledFlag,
CompiledSegment,
EvaluationResult,
FlagEvaluationResult,
newEvaluator,
Expand Down Expand Up @@ -188,39 +189,182 @@ describe("batch and single-flag API", () => {
});

it.each([false, true])(
"re-evaluates dependencies without memoization, reversed: %s",
"memoizes flag diamonds within each evaluation, reversed: %s",
(reversed) => {
const definitions = [
flag("a", {
type: "group",
operator: "and",
filters: [reference, reference],
filters: [
{ type: "flag", key: "left", variantKey: "on" },
{ type: "flag", key: "right", variantKey: "on" },
],
}),
flag("left", reference),
flag("right", reference),
flag("dependency", grant),
];
const evaluator = newEvaluator({
flags: reversed ? definitions.reverse() : definitions,
});
const lookups = vi.spyOn(Set.prototype, "has");
try {
expect(evaluator.evaluateAll(context).flags.a.value).toBe(true);
// Twice through a, once as a root output, regardless of definition order.
for (const id of ["acme", "other", "acme"]) {
const request = { company: { id } };
lookups.mockClear();
const batch = evaluator.evaluateAll(request);
expect(Object.values(batch.flags).map(({ value }) => value)).toEqual(
definitions.map(() => id === "acme"),
);
expect(
lookups.mock.calls.filter(([value]) => value === id),
).toHaveLength(1);
lookups.mockClear();
expect(evaluator.evaluateFlag(request, "a")).toEqual({
...batch.flags.a,
context: batch.context,
});
expect(
lookups.mock.calls.filter(([value]) => value === id),
).toHaveLength(1);
}
} finally {
lookups.mockRestore();
}
},
);

it("memoizes shared segment graphs across roots but not across calls", () => {
const segments: CompiledSegment[] = [{ key: "s0", filter: grant }];
for (let i = 1; i <= 16; i++) {
segments.push({
key: `s${i}`,
filter: {
type: "group",
operator: "and",
filters: [
{ type: "segment", key: `s${i - 1}` },
{ type: "segment", key: `s${i - 1}` },
],
},
});
}
const evaluator = newEvaluator({
flags: [
flag("a", { type: "segment", key: "s16" }),
flag("b", { type: "segment", key: "s16" }),
],
segments,
});
const lookups = vi.spyOn(Set.prototype, "has");
try {
for (const id of ["acme", "other", "acme"]) {
const request = { company: { id } };
lookups.mockClear();
const batch = evaluator.evaluateAll(request);
expect(batch.flags.a.value).toBe(id === "acme");
expect(batch.flags.b.value).toBe(id === "acme");
expect(
lookups.mock.calls.filter(([value]) => value === "acme"),
).toHaveLength(3);
lookups.mock.calls.filter(([value]) => value === id),
).toHaveLength(1);
lookups.mockClear();
expect(evaluator.evaluateFlag(request, "a")).toEqual({
...batch.flags.a,
context: batch.context,
});
expect(
evaluator.evaluateAll({ company: { id: "other" } }).flags.a.value,
).toBe(false);
expect(evaluator.evaluateAll(context).flags.a.value).toBe(true);
lookups.mock.calls.filter(([value]) => value === id),
).toHaveLength(1);
}
} finally {
lookups.mockRestore();
}
});

it.each(["flag", "segment", "unresolved flag"] as const)(
"caches a failed %s while propagating errors to every referencing rule",
(kind) => {
const type = kind === "segment" ? "segment" : "flag";
const dependency: RuleFilter =
type === "segment"
? { type, key: "dependency" }
: { type, key: "dependency", variantKey: "on" };
const failed: RuleFilter = {
type: "group",
operator: "and",
filters: [grant, missing],
};
const parent = flag("a", { type: "negation", filter: dependency });
parent.rules.unshift({ ...parent.rules[0], id: "repeated" });
const child = flag("dependency", failed);
if (kind === "unresolved flag") child.rules.pop();
const evaluator = newEvaluator({
flags: [
parent,
{ ...parent, key: "b" },
...(type === "flag" ? [child] : []),
],
segments:
type === "segment" ? [{ key: "dependency", filter: failed }] : [],
});
const lookups = vi.spyOn(Set.prototype, "has");
try {
const batch = evaluator.evaluateAll(context);
expect(
lookups.mock.calls.filter(([value]) => value === "acme"),
).toHaveLength(6);
).toHaveLength(1);
for (const key of ["a", "b"]) {
expect(batch.flags[key].value).toBe(false);
expect(
batch.flags[key].ruleResults.map(({ matched }) => matched),
).toEqual([false, false, true]);
expect(batch.flags[key].errors).toEqual([
expect.objectContaining({
code: "MISSING_CONTEXT_FIELD",
source: { type, key: "dependency" },
}),
...(kind === "unresolved flag"
? [
expect.objectContaining({
code: "INVALID_FLAG_DEFINITION",
source: { type, key: "dependency" },
}),
]
: []),
]);
const { context: _, ...single } = evaluator.evaluateFlag(
context,
key,
);
expect(single).toEqual(batch.flags[key]);
}
} finally {
lookups.mockRestore();
}
},
);

it("keeps cached nested diagnostics independent between batch outputs", () => {
const evaluator = newEvaluator({
flags: [
flag("a", reference),
flag("b", reference),
flag("dependency", { type: "segment", key: "outer" }),
],
segments: [
{ key: "outer", filter: { type: "segment", key: "inner" } },
{ key: "inner", filter: missing },
],
});
const first = evaluator.evaluateAll(context);
const expected = structuredClone(first);
first.flags.a.errors[0].source!.key = "changed";
first.flags.a.ruleResults.length = 0;
expect(first.flags.b).toEqual(expected.flags.b);
expect(first.flags.dependency).toEqual(expected.flags.dependency);
expect(evaluator.evaluateAll(context)).toEqual(expected);
});

it("keeps diagnostics local to each flag and each call", () => {
const evaluator = newEvaluator({
flags: [flag("a", reference), flag("dependency", missing), flag("clean")],
Expand Down
Loading
Loading