Skip to content

feat: Contract tests for client-side prerequisite cycle detection - #384

Merged
tanderson-ld merged 4 commits into
v2from
ta/cspe-contract-tests
Jul 20, 2026
Merged

tanderson-ld merged 4 commits into
v2from
ta/cspe-contract-tests

Conversation

@tanderson-ld

@tanderson-ld tanderson-ld commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the client-prereq-cycle-detection capability plus a set of contract tests that exercise CSPE 1.2.5, 1.2.5.1, and 1.2.5.2 (see sdk-specs PR #246, currently in review):

  • 1.2.5: on a cyclic prerequisite graph reachable from the evaluated flag, the SDK must not enter unbounded recursion, exhaust its stack, or terminate abnormally. It must skip descent into the cyclic edge and continue processing any remaining prerequisites at the current level.
  • 1.2.5.1: the returned value and reason must equal the requested flag's cached evaluation result unchanged. A client-side cycle must not surface as MALFORMED_FLAG and must not fall back to the caller-provided default.
  • 1.2.5.2: cycle detection must use ancestor-set (current-path) semantics so that a prerequisite reachable via multiple non-cyclic paths (a diamond) is still processed on each path.

Draft while sdk-specs PR #246 is in review; tests may be adjusted to match final requirement wording. Zero SDKs declare client-prereq-cycle-detection at merge time, so this PR is a no-op for existing CI runs. Each per-SDK fix will declare the capability and activate the test for that SDK.

What's in

servicedef/service_params.go — new capability constant CapabilityClientPrereqCycleDetection = "client-prereq-cycle-detection".

sdktests/client_side_events_eval.go — new doClientSidePrereqCycleTests covering feature-event emission across cycle shapes. Cases: self-loop, self-loop-with-sibling, two-cycle (evaluated from each end), three-cycle, cycle-in-subgraph, diamond (non-cyclic control), 20-flag deep chain (non-cyclic control). Each case asserts that the returned value equals the flag's cached value and that the emitted feature events match the expected set (bounded — a failed cycle guard would emit unbounded events and fail the match).

sdktests/client_side_events_summary.go — new doClientSideSummaryPrereqCycleTests. Summary-counter mirror of the feature-event cases: each cycle-safe descent increments the counter exactly once; cyclic edges do not increment; the diamond's shared descendant increments twice (ancestor-set proof).

sdktests/client_side_events_all.go and the "prerequisites" subtree in the summary file — wires the new tests behind t.RequireCapability(CapabilityClientPrereqCycleDetection), nested under the existing CapabilityClientPrereqEvents gate.

What's deliberately not in

  • Persisted-cyclic-cache-across-restart scenario: platform-specific storage — belongs in each SDK's own unit tests. The runtime cycle guard fixes the in-memory case and the persisted case equally.
  • Patch-introduces-cycle-mid-stream scenario: exercises the same walker code path as an initial put containing a cycle. Redundant.
  • Hooks-not-triggered-on-prereq-recursion: SDK-specific (some SDKs have hooks, some don't). Belongs per-SDK.

Rollout

Parent story: SDK-2695. This is SDK-2703. Per-SDK subtasks are SDK-2704 through SDK-2715. Suggested order: Android → shipping iOS → JS shared sdk-client → wrappers (React, RN, Electron, node-client, Vue) → Flutter → .NET → C++ → Roku.

Test plan

  • go build ./... passes (verified locally).
  • go vet ./sdktests/... ./servicedef/... passes (verified locally).
  • With zero SDKs declaring the capability, this PR is a no-op for existing CI runs.
  • Once a fixed SDK declares client-prereq-cycle-detection, this test suite runs against it and passes.

Note

Low Risk
Harness-only additions behind a new opt-in capability; no production SDK or runtime behavior changes in this repo.

Overview
Introduces the client-prereq-cycle-detection harness capability and contract tests for CSPE 1.2.5 (safe handling of cyclic prerequisite graphs on client-side evaluation).

Feature-event tests (doClientSidePrereqCycleTests) assert the evaluated flag still returns its cached value, the SDK does not crash or emit unbounded events, and prerequisite feature events match expected finite sets for self-loops, multi-flag cycles, cycles beside acyclic siblings, diamond graphs (shared node counted per path), and a deep acyclic chain control.

Summary-counter tests (doClientSideSummaryPrereqCycleTests) mirror those graphs: each non-cyclic descent increments counters once, cyclic edges do not, and the diamond case expects the shared flag counted twice.

Both suites are gated behind CapabilityClientPrereqCycleDetection (nested under existing client-prereq-events), so CI stays unchanged until an SDK opts in.

Reviewed by Cursor Bugbot for commit e819cc6. Bugbot is set up for automated code reviews on this repo. Configure here.

tanderson-ld and others added 3 commits July 20, 2026 10:30
Adds the client-prereq-cycle-detection capability and contract tests
exercising CSPE 1.2.5, 1.2.5.1, and 1.2.5.2:
* the SDK must not crash on a cyclic prerequisite graph reachable from
  the evaluated flag,
* the returned value and reason MUST equal the requested flag's cached
  evaluation result (no MALFORMED_FLAG substitution),
* cycle detection MUST use ancestor-set (current-path) semantics so
  legitimate reconvergent paths (diamonds) continue to emit an event
  per path.

Feature-event cases live in client_side_events_eval.go
(doClientSidePrereqCycleTests): self-loop, self-loop-with-siblings,
two-cycle (evaluating each end), three-cycle, cycle-in-subgraph,
diamond, and a 20-flag non-cyclic deep chain.

Summary-counter cases mirror those in client_side_events_summary.go
(doClientSideSummaryPrereqCycleTests), confirming that each cycle-safe
descent increments the counter exactly once, that cyclic edges do not
increment, and that a diamond increments the shared descendant twice.

Tests are gated on client-prereq-cycle-detection so unfixed SDKs
remain green until they opt in.
@tanderson-ld
tanderson-ld merged commit 3605eb7 into v2 Jul 20, 2026
6 checks passed
@tanderson-ld
tanderson-ld deleted the ta/cspe-contract-tests branch July 20, 2026 20:26
tanderson-ld pushed a commit that referenced this pull request Jul 20, 2026
🤖 I have created a release *beep* *boop*
---


##
[2.38.0](v2.37.0...v2.38.0)
(2026-07-20)


### Features

* Add contract tests for client-side secure mode hash (h query param)
([#358](#358))
([16ed598](16ed598))
* Add migration op event context redaction tests
([#383](#383))
([daa7ad4](daa7ad4))
* Contract tests for client-side prerequisite cycle detection
([#384](#384))
([3605eb7](3605eb7))


### Bug Fixes

* Fix capability guarding custom event redaction
([#386](#386))
([357898f](357898f))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mechanical version and changelog update with no runtime or test logic
changes in the diff.
> 
> **Overview**
> **Release 2.38.0** bumps the harness version from **2.37.0** to
**2.38.0** in `main.go` and `.release-please-manifest.json`, and adds a
**2.38.0** section to `CHANGELOG.md`.
> 
> The changelog for this release (from already-merged work) covers new
contract tests for client-side secure mode hash (`h` query param),
migration op event context redaction, and client-side prerequisite cycle
detection, plus a fix for capability guarding on custom event redaction
tests. This PR does not change test or framework code—only release
metadata.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9ab60fd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
tanderson-ld added a commit to launchdarkly/android-client-sdk that referenced this pull request Jul 21, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`LDClient.variationDetailInternal`, bringing the client SDK's behavior
into line with the LaunchDarkly server SDK evaluators.

Tracker: [SDK-2706](https://launchdarkly.atlassian.net/browse/SDK-2706).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Matching contract-test PR:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384).

## The fix

`variationDetailInternal` now threads a lazily-allocated
`HashSet<String>` through the recursion carrying the flag keys on the
current evaluation path. Before descending into a prerequisite, the
walker checks whether that key is already on the path; if so, it skips
that edge and continues with remaining prerequisites at the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate zero collections. The HashSet is created only when the
walker descends into a prerequisite for the first time in a call, then
reused for the rest of the walk.
- **Mutable add/remove with `try/finally`**: `add(key)` before recursing
and `remove(key)` in a `finally`, so the invariant "the set contains
exactly the current path" holds even under exceptions.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly counts D twice. There is a
unit test guarding this.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

[SDK-2706]:
https://launchdarkly.atlassian.net/browse/SDK-2706?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
tanderson-ld added a commit to launchdarkly/flutter-client-sdk that referenced this pull request Jul 22, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`LDCommonClient._variationInternal`, bringing the Flutter client SDK's
behavior into line with the LaunchDarkly server SDK evaluators.

Tracker: [SDK-2705](https://launchdarkly.atlassian.net/browse/SDK-2705).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Contract-test coverage:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384)
(merged in v2.38.0). Companion PRs:
[android-client-sdk#377](launchdarkly/android-client-sdk#377),
[ios-client-sdk#512](launchdarkly/ios-client-sdk#512),
[js-core#1816](launchdarkly/js-core#1816).

## Background

The LaunchDarkly service validates prerequisite graphs on every mutation
and rejects any change that would produce a cycle, so under normal
operation the SDK does not see a cyclic prerequisite graph. Server-side
SDK evaluators nonetheless carry defensive cycle detection for
exceptional cases — for example, delivery of updates out of order or a
persisted state loaded from disk that predates a subsequent correction.
This PR extends the same defensive posture to the Flutter client SDK.

## The fix

`_variationInternal` now threads a lazily-allocated `Set<String>?`
through the recursion carrying the flag keys on the current evaluation
path. Before descending into a prerequisite, the walker checks whether
that key is already on the path; if so, it skips that edge and continues
with remaining prerequisites at the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate zero collections. The `Set<String>` is created only when
the walker descends into a prerequisite for the first time in a call,
then reused for the rest of the walk.
- **Mutable `add` / `finally remove`**: no per-descent copy.
`ancestors.add(flagKey)` before recursing, `ancestors.remove(flagKey)`
in a `finally` — the invariant "the set contains exactly the current
path" holds even under early exits.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly emits D twice. There is a unit
test guarding this.

The optional named parameter `visited` is added last, so all existing
callers (the seven typed and untyped `variation` / `variationDetail`
entry points) work unchanged.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

## Files changed

- `packages/common_client/lib/src/ld_common_client.dart` — cycle guard
in `_variationInternal`.
- `packages/common_client/test/ld_dart_client_test.dart` — 5 new tests
under the existing `given mock flag data with prerequisites` group:
self-loop, two-cycle (evaluating each end), three-cycle, and a
non-cyclic diamond that asserts the shared descendant emits an event for
each path (the ancestor-set regression fence).
-
`apps/flutter_client_contract_test_service/bin/contract_test_service.dart`
— declares `client-prereq-cycle-detection` so the matching contract
tests in sdk-test-harness v2.38.0+ activate for this SDK.

## Verification

- **Unit tests**: `dart test test/ld_dart_client_test.dart` → 31 tests,
0 failures. The 5 new cycle-detection tests all pass.

## Changelog

> Updated prerequisite evaluation event emission to match server SDK
behavior for cyclic prerequisite graphs.

[SDK-2705]:
https://launchdarkly.atlassian.net/browse/SDK-2705?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes flag evaluation’s prerequisite recursion and analytics event
ordering, but behavior is narrowly scoped to abnormal cyclic graphs and
is covered by new unit and contract tests.
> 
> **Overview**
> Adds **defensive cycle detection** to the recursive prerequisite walk
in `LDCommonClient._variationInternal`, matching server SDK behavior
when a cyclic prereq graph appears (e.g. stale persisted state).
> 
> The walker threads a lazily allocated **ancestor set** (current path
only): before recursing into a prerequisite it skips edges whose key is
already on the path, then continues with other prerequisites. The
evaluated flag still returns its **cached value and reason**; only the
ancillary prereq event walk is affected. **Diamond graphs** still emit
one prereq event per independent path (not treated as cycles).
> 
> Adds five unit tests (self-loop, 2- and 3-cycles, diamond regression)
and advertises the **`client-prereq-cycle-detection`** contract-test
capability on the Flutter contract test service.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7ea0310. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
tanderson-ld added a commit to launchdarkly/dotnet-core that referenced this pull request Jul 23, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`LdClient.EvaluateInternal`, bringing the .NET client SDK's behavior
into line with the LaunchDarkly server SDK evaluators.

Tracker: [SDK-2708](https://launchdarkly.atlassian.net/browse/SDK-2708).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Contract-test coverage:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384)
(merged in v2.38.0). Companion PRs:
[android-client-sdk#377](launchdarkly/android-client-sdk#377),
[ios-client-sdk#512](launchdarkly/ios-client-sdk#512),
[js-core#1816](launchdarkly/js-core#1816),
[flutter-client-sdk#329](launchdarkly/flutter-client-sdk#329).

## Background

The LaunchDarkly service validates prerequisite graphs on every mutation
and rejects any change that would produce a cycle, so under normal
operation the SDK does not see a cyclic prerequisite graph. Server-side
SDK evaluators nonetheless carry defensive cycle detection for
exceptional cases — for example, delivery of updates out of order or a
persisted state loaded from disk that predates a subsequent correction.
Note that the .NET **server** SDK evaluator already carries this guard
(`PrereqFlagKeyStack` in `Evaluator.cs`); this PR extends the same
posture to the client SDK.

## The fix

`EvaluateInternal<T>` now threads a lazily-allocated `HashSet<string>`
through the recursion carrying the flag keys on the current evaluation
path. Before descending into a prerequisite, the walker checks whether
that key is already on the path; if so, it skips that edge and continues
with remaining prerequisites at the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate zero collections. The `HashSet<string>` is created only
when the walker descends into a prerequisite for the first time in a
call, then reused for the rest of the walk.
- **Mutable `Add` / `finally Remove`**: no per-descent copy.
`ancestors.Add(featureKey)` before recursing,
`ancestors.Remove(featureKey)` in a `finally` — the invariant "the set
contains exactly the current path" holds even under exceptions.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly emits D twice. There is a unit
test guarding this.

The optional trailing parameter `HashSet<string> visited = null` is
added to `EvaluateInternal<T>`, so all existing callers (the public
`BoolVariation` / `IntVariation` / `StringVariation` / `DoubleVariation`
/ `JsonVariation` and their `*Detail` counterparts) work unchanged.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

## Files changed

- `pkgs/sdk/client/src/LdClient.cs` — cycle guard in
`EvaluateInternal<T>`.
-
`pkgs/sdk/client/test/LaunchDarkly.ClientSdk.Tests/LdClientEventTests.cs`
— 5 new xUnit tests: self-loop, two-cycle (evaluating each end),
three-cycle, and a non-cyclic diamond that asserts the shared descendant
emits an event for each path (the ancestor-set regression fence).
- `pkgs/sdk/client/contract-tests/TestService.cs` — declares
`client-prereq-cycle-detection` so the matching contract tests in
sdk-test-harness v2.38.0+ activate for this SDK.

## Verification

- **Unit tests**: `dotnet test -f net8.0 --filter
"Prerequisite|Cycle|Diamond"` → 6 passed, 0 failures (the original
prereq event test plus 5 new cycle-detection tests).

## Changelog

> Updated prerequisite evaluation event emission to match server SDK
behavior for cyclic prerequisite graphs.

[SDK-2708]:
https://launchdarkly.atlassian.net/browse/SDK-2708?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core flag evaluation and analytics event emission for
prerequisite walks; behavior change is defensive but affects event
ordering/counts on malformed graphs.
> 
> **Overview**
> Adds **defensive cycle detection** to the recursive prerequisite walk
in `LdClient.EvaluateInternal`, aligning client SDK behavior with server
evaluators and sdk-spec CSPE 1.2.5.
> 
> Before descending into each prerequisite, the walker tracks flag keys
on the **current path** in a lazily allocated `HashSet<string>` (add
before recurse, remove in `finally`). If a prerequisite key is already
on that path, that edge is skipped; the requested flag still returns its
**cached value and reason** unchanged.
> 
> **Ancestor-set semantics** (not a global visited set) preserve correct
analytics for diamond graphs: a shared prerequisite reached via separate
branches still emits one evaluation event per path.
> 
> Contract tests declare capability `client-prereq-cycle-detection`.
Five xUnit tests cover self-loops, 2- and 3-cycles, and the diamond
regression case.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
81fbdce. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
tanderson-ld added a commit to launchdarkly/roku-client-sdk that referenced this pull request Jul 23, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`variationDetail` (`LaunchDarklyClient.brs`), bringing the Roku client
SDK's behavior into line with the LaunchDarkly server SDK evaluators.

Tracker: [SDK-2710](https://launchdarkly.atlassian.net/browse/SDK-2710).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Contract-test coverage:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384)
(merged in v2.38.0). Companion PRs:
[android-client-sdk#377](launchdarkly/android-client-sdk#377),
[ios-client-sdk#512](launchdarkly/ios-client-sdk#512),
[js-core#1816](launchdarkly/js-core#1816),
[flutter-client-sdk#329](launchdarkly/flutter-client-sdk#329),
[dotnet-core#317](launchdarkly/dotnet-core#317),
[cpp-sdks#582](launchdarkly/cpp-sdks#582).

## Background

The LaunchDarkly service validates prerequisite graphs on every mutation
and rejects any change that would produce a cycle, so under normal
operation the SDK does not see a cyclic prerequisite graph. Server-side
SDK evaluators nonetheless carry defensive cycle detection for
exceptional cases — for example, delivery of updates out of order or a
persisted state loaded from disk that predates a subsequent correction.
This PR extends the same defensive posture to the Roku client SDK.

## The fix

`variationDetail` now threads a lazily-allocated associative array
through the recursion carrying the flag keys on the current evaluation
path. Before descending into a prerequisite, the walker checks whether
that key is already on the path; if so, it skips that edge and continues
with remaining prerequisites at the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate no associative array. The map is created only when the
walker descends into a prerequisite for the first time in a call, then
reused for the rest of the walk.
- **Mutable add/delete around the loop**: no per-descent copy. The
current flag's key is inserted before the loop and removed after, so the
invariant "the map contains exactly the current path" holds across
sibling descents.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly emits D twice. There is a unit
test guarding this.

The optional trailing parameter `launchDarklyParamVisited=invalid` is
added to `variationDetail`, so existing callers (`boolVariation`,
`intVariationDetail`, `stringVariationDetail`, `doubleVariationDetail`,
`jsonVariationDetail`, and the untyped `variation`) work unchanged.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

## Files changed

- `rawsrc/LaunchDarklyClient.brs` — cycle guard in `variationDetail`.
- `src/test/source/tests/Test__Client.brs` — 5 new unit tests:
self-loop, two-cycle (evaluating each end), three-cycle, and a
non-cyclic diamond that asserts the shared descendant emits an event for
each path (the ancestor-set regression fence).
- `src/contract-tests/components/HttpServerTask.brs` — declares
`client-prereq-cycle-detection` so the matching contract tests in
sdk-test-harness v2.38.0+ activate for this SDK.

## Verification

- **Unit tests**: 5 new `TestCase__Client_CycleDetection_*` cases follow
the existing `TestCase__Client_*` pattern (seed `client.private.store`,
call `client.variation()`, flush and inspect the event queue). Local
execution requires a Roku device (`ukor test`); CI provides the actual
test run.
- **Contract tests**: local run requires deployment to a Roku device; CI
provides the run against the released harness. The new suite
(`client-prereq-cycle-detection`) will activate as soon as CI picks up
harness v2.38.0+.

## Changelog

> Updated prerequisite evaluation event emission to match server SDK
behavior for cyclic prerequisite graphs.

[SDK-2710]:
https://launchdarkly.atlassian.net/browse/SDK-2710?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the prerequisite event-walk in core flag evaluation, but
behavior for normal graphs is preserved and cycles only skip redundant
descent; coverage is strong via new unit and contract capability tests.
> 
> **Overview**
> Adds **defensive cycle detection** when the Roku client walks flag
**prerequisites** to emit evaluation events, matching other LaunchDarkly
SDKs and avoiding unbounded recursion on malformed graphs.
> 
> Core `variationDetail` logic moves into
**`LaunchDarklyClientSharedPrivateFunctions`** and is merged into both
the standard client and SceneGraph client. The recursive walk threads a
**current-path ancestor set** (`launchDarklyParamVisited`): before
descending into a prerequisite, if that flag is already on the path the
edge is skipped; diamonds still emit events per path (not a global
visited set). **Public variation APIs are unchanged**—they delegate to
the private implementation with `m.status`.
> 
> Contract tests advertise capability
**`client-prereq-cycle-detection`**. **Five unit tests** cover
self-loop, 2- and 3-cycles, and a diamond graph (cached values
unchanged; feature event order asserted).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1e59528. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
tanderson-ld added a commit to launchdarkly/cpp-sdks that referenced this pull request Jul 27, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`ClientImpl::VariationInternal`, bringing the C++ client SDK's behavior
into line with the LaunchDarkly server SDK evaluators.

Tracker: [SDK-2709](https://launchdarkly.atlassian.net/browse/SDK-2709).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Contract-test coverage:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384)
(merged in v2.38.0). Companion PRs:
[android-client-sdk#377](launchdarkly/android-client-sdk#377),
[ios-client-sdk#512](launchdarkly/ios-client-sdk#512),
[js-core#1816](launchdarkly/js-core#1816),
[flutter-client-sdk#329](launchdarkly/flutter-client-sdk#329),
[dotnet-core#317](launchdarkly/dotnet-core#317).

## Background

The LaunchDarkly service validates prerequisite graphs on every mutation
and rejects any change that would produce a cycle, so under normal
operation the SDK does not see a cyclic prerequisite graph. Server-side
SDK evaluators nonetheless carry defensive cycle detection for
exceptional cases — for example, delivery of updates out of order or a
persisted state loaded from disk that predates a subsequent correction.
This PR extends the same defensive posture to the C++ client SDK.

## The fix

`VariationInternal<T>` now threads a lazily-allocated
`std::unordered_set<std::string>*` through the recursion carrying the
flag keys on the current evaluation path. Before descending into a
prerequisite, the walker checks whether that key is already on the path;
if so, it skips that edge and continues with remaining prerequisites at
the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate zero collections. The `std::unordered_set` is created
only when the walker descends into a prerequisite for the first time in
a call, then reused for the rest of the walk.
- **Mutable `insert` / catch-and-rethrow `erase`**: no per-descent copy.
`ancestors->insert(key)` before recursing; if a nested call throws, the
exception handler restores `ancestors` to its pre-descent state before
rethrowing. This preserves the invariant "the set contains exactly the
current path" even under exceptions.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly emits D twice. The
contract-test suite has a case guarding this.

The optional trailing parameter `std::unordered_set<std::string>*
visited = nullptr` is added to `VariationInternal<T>`, so all existing
callers (the public `BoolVariation` / `IntVariation` / `StringVariation`
/ `DoubleVariation` / `JsonVariation` and their `*Detail` counterparts)
work unchanged. The recursive call now goes directly to
`VariationInternal<Value>` rather than through `JsonVariation`, so the
visited pointer can be threaded through — behavior is otherwise
identical.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

## Files changed

- `libs/client-sdk/src/client_impl.hpp` — added
`std::unordered_set<std::string>*` optional parameter to
`VariationInternal<T>` declaration, plus the `<string>` /
`<unordered_set>` includes.
- `libs/client-sdk/src/client_impl.cpp` — cycle guard implementation in
`VariationInternal<T>`.
- `contract-tests/client-contract-tests/src/main.cpp` — declares
`client-prereq-cycle-detection` capability so the matching contract
tests in sdk-test-harness v2.38.0+ activate for this SDK.

## Verification

- **Build**: `cmake --build build --target launchdarkly-cpp-client` →
clean, no warnings.
- **Contract tests locally** against harness v2.38.1: `client-tests`
binary + `sdk-test-harness v2.38.1` → **876 total, 12 skipped, 864 ran,
all passed.** Both new suites (`events/prerequisite events handle
cycles` and `events/summary events/prerequisites/handles cycles`) fire
all 15 subtests including the deep-chain non-cyclic control, no
failures.

The C++ client SDK does not have existing unit tests that exercise
prerequisite walks (`libs/client-sdk/tests/client_test.cpp` currently
covers only default-value paths with no flag data loaded). Rather than
build new unit-test infrastructure for this PR, verification is provided
by the contract-test suite, which now exercises the fix comprehensively.

## Changelog

> Updated prerequisite evaluation event emission to match server SDK
behavior for cyclic prerequisite graphs.

[SDK-2709]:
https://launchdarkly.atlassian.net/browse/SDK-2709?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core flag evaluation and analytics event emission for
prerequisites; behavior change is scoped to exceptional cyclic graphs
and is covered by contract tests.
> 
> **Overview**
> Adds **defensive cycle detection** to the recursive prerequisite walk
in `ClientImpl::VariationInternal`, aligning client-side prerequisite
**event emission** with server SDK behavior when a cyclic graph is
encountered (e.g. stale persisted state).
> 
> `VariationInternal` now accepts an optional
`std::unordered_set<std::string>*` tracking **ancestors on the current
path** (not a global visited set, so diamond graphs still emit
prerequisite events on each path). Before recursing into a prerequisite,
if that key is already on the path the edge is **skipped** with a
warning log; the requested flag’s cached value and reason are unchanged.
Prerequisite recursion calls `VariationInternal<Value>` directly so the
ancestor set can be threaded through.
> 
> Contract tests advertise the new **`client-prereq-cycle-detection`**
capability in `client-contract-tests`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b9e27d5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
tanderson-ld added a commit to launchdarkly/ios-client-sdk that referenced this pull request Jul 27, 2026
## Summary

Adds defensive cycle detection to the recursive prerequisite walk in
`LDClient.variationDetailInternal`, bringing the iOS client SDK's
behavior into line with the LaunchDarkly server SDK evaluators, which
have handled cyclic prerequisite graphs gracefully for years.

Tracker: [SDK-2704](https://launchdarkly.atlassian.net/browse/SDK-2704).
Parent: [SDK-2695](https://launchdarkly.atlassian.net/browse/SDK-2695).
Spec change:
[sdk-specs#246](launchdarkly/sdk-specs#246)
(CSPE 1.2.5, 1.2.5.1, 1.2.5.2). Contract-test coverage:
[sdk-test-harness#384](launchdarkly/sdk-test-harness#384)
(merged in v2.38.0). Companion Android fix:
[android-client-sdk#377](launchdarkly/android-client-sdk#377).

## Background

The LaunchDarkly service validates prerequisite graphs on every mutation
and rejects any change that would produce a cycle, so under normal
operation the SDK does not see a cyclic prerequisite graph. Server-side
SDK evaluators nonetheless carry defensive cycle detection for
exceptional cases — for example, delivery of updates out of order or a
persisted state loaded from disk that predates a subsequent correction.
This PR extends the same defensive posture to the iOS client SDK.

## The fix

`variationDetailInternal` now threads a lazily-allocated `Set<String>?`
through the recursion carrying the flag keys on the current evaluation
path. Before descending into a prerequisite, the walker checks whether
that key is already on the path; if so, it skips that edge and continues
with remaining prerequisites at the same level.

- **Lazy allocation**: variation calls on prereq-less flags (the common
case) allocate zero collections. The `Set<String>` is created only when
the walker descends into a prerequisite for the first time in a call,
then reused for the rest of the walk.
- **Mutable `insert` / `defer remove`**: no per-descent copy.
`insert(flagKey)` before recursing, `defer { visited!.remove(flagKey) }`
for guaranteed cleanup — the invariant "the set contains exactly the
current path" holds even under early exits.
- **Ancestor-set (current-path) semantics** — this is deliberate. A
prerequisite reached via multiple non-cyclic paths (a diamond `A -> [B,
C], B -> [D], C -> [D]`) is not a cycle; each path should emit its own
prerequisite event. A global visited-set would silently drop the second
event; the ancestor-set pattern correctly emits D twice. There is a unit
test guarding this.

The public 4-argument `variationDetailInternal` signature is preserved
as a thin wrapper that declares `var visited: Set<String>? = nil` and
calls the new 5-argument overload — none of the 12 top-level variation
methods (`boolVariation`, `intVariation`, etc.) need to change.

## Caller-visible behavior on a cycle

The requested flag returns its cached value and reason unchanged. A
client-side prerequisite cycle is not surfaced as `MALFORMED_FLAG` and
does not fall back to the caller-provided default value. This differs
from server-side behavior — the client already holds an authoritative
pre-evaluated result from the server; only the ancillary event walk is
affected by the cycle.

## Files changed

- `LaunchDarkly/LaunchDarkly/LDClientVariation.swift` — cycle guard in
`variationDetailInternal`. 4-argument public signature preserved as a
wrapper; new 5-argument overload carries the `inout Set<String>?`.
- `LaunchDarkly/LaunchDarklyTests/LDClientSpec.swift` — 5 new
Quick/Nimble tests under a new `context("flag store contains cyclic
prerequisites")`: self-loop, two-cycle (evaluating each end),
three-cycle, and a non-cyclic diamond that asserts the shared descendant
emits an event for each path (the ancestor-set regression fence).
- `ContractTests/Source/Controllers/SdkController.swift` — declares
`client-prereq-cycle-detection` so the matching contract tests in
sdk-test-harness v2.38.0+ activate for this SDK.

## Verification

- **Unit tests**: `swift test` → 615 tests, 0 failures. The 5 new
cycle-detection tests are visible in the log and passing.
- **Contract tests locally** against harness v2.38.0: `make
contract-tests` → 838 total, 15 skipped, 823 ran, all passed. Both new
suites (`events/prerequisite events handle cycles` and `events/summary
events/prerequisites/handles cycles`) fire and pass — 15 subtests total
between them.

## Changelog

> Updated prerequisite evaluation event emission to match server SDK
behavior for cyclic prerequisite graphs.

[SDK-2704]:
https://launchdarkly.atlassian.net/browse/SDK-2704?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SDK-2695]:
https://launchdarkly.atlassian.net/browse/SDK-2695?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core flag evaluation and prerequisite event emission; behavior
change is defensive and well-tested but affects analytics paths on
malformed graphs.
> 
> **Overview**
> Adds **defensive cycle detection** to the recursive prerequisite walk
in `variationDetailInternal`, aligning client behavior with server SDKs
and CSPE **1.2.5**.
> 
> Before descending into a prerequisite, the walker tracks flag keys on
the **current path** in a lazily allocated `Set` (no extra allocation
for flags without prerequisites). If a prerequisite key is already on
the path, that edge is **skipped**; the evaluated flag still returns its
**cached value and reason** unchanged. **Ancestor-set** semantics
preserve correct behavior on **diamond** graphs (shared descendants
still emit prerequisite events once per path).
> 
> Adds Quick/Nimble coverage for self-loops, 2- and 3-cycles, and the
diamond regression case. Contract tests advertise capability
**`client-prereq-cycle-detection`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5dd39a6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants