Skip to content

feat(flags): add local evaluation telemetry opt-out - #1230

Open
leoromanovsky wants to merge 10 commits into
developfrom
leoromanovsky/v4-evaluation-telemetry-opt-out
Open

leoromanovsky wants to merge 10 commits into
developfrom
leoromanovsky/v4-evaluation-telemetry-opt-out

Conversation

@leoromanovsky

@leoromanovsky leoromanovsky commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Applications need to serve feature flags while applying customer-owned policies to evaluation telemetry.

This replaces #1229 for the v4 development branch. It includes the latest v4 changes, including the completed develop synchronization in #1227.

Changes and Decisions

  • Add explicit enableEvaluationTelemetryOptOutParameter activation, disabled by default. Only boolean dd_evaluation_telemetry_opt_out: true suppresses new evaluation events, counts, and automatic RUM flag annotations.
  • Retain the attribute in targeting requests, cached context, and exposure attributes. Preserve manual annotations, unrelated telemetry, and queued events.
  • Keep each subject's latest reporting decision during refresh. Switching subjects cannot enable reporting for opted-out assignments that remain active.
  • Require datadog_flags: ^1.2.0 in the Flutter wrapper. Both Flags packages currently target the unreleased 1.2.0 release. No new Flutter plugin API is required, so its existing >=3.4.0 <5.0.0 constraint remains.
flowchart LR
    App[Application context] --> Policy{Option enabled and\nboolean opt-out is true?}
    Policy -->|Yes| Local[Suppress new evaluation telemetry\nand automatic RUM annotations]
    Policy -->|No| Emit[Keep existing evaluation telemetry]
    App --> Evaluation[Evaluate stored assignments]
    Evaluation --> Result[Return unchanged flag result]
    Evaluation --> Exposure[Keep existing exposure behavior]
Loading
// Add this plugin to the application's Datadog configuration before initialization.
configuration.addPlugin(const DatadogFlagsPluginConfiguration(
  flagsConfiguration: DatadogFlagsConfiguration(
    enableEvaluationTelemetryOptOutParameter: true,
  ),
));
await DatadogSdk.instance.initialize(configuration, TrackingConsent.granted);

final flags = DatadogSdk.instance.flags!.sharedClient();
await flags.initialize(FlagsEvaluationContext(
  targetingKey: subjectId,
  attributes: {'dd_evaluation_telemetry_opt_out': evaluationTelemetryOptedOut},
));
final enabled = flags.getBooleanDetails(
  key: 'new-route-planner',
  defaultValue: false,
).value;

The application owns evaluationTelemetryOptedOut. The attribute remains available to targeting rules; changing it can change assignments.

Validation

Tested commit Validation Result
DataDog/dd-sdk-flutter@54ffe382620a5237faaa00ac1cd877bcf3e59266 Local integration: evaluation opt-out, preserved exposures, and native RUM uploads; iOS 26.5 Simulator 1 passed; 0 failed or skipped. Suppressed control: 0 evaluation events, 1 exposure, no automatic RUM annotations. Pending subject-switch race is not exercised by this device test.

FFE reviewer selection

Reviewers: @sameerank, @greghuels

Why: Privacy opt-out and event logging rules — The PR adds a DatadogFlagsConfiguration option, off by default. Global reviewers cover a shortage in the matched pod.

🤖 Automated selection.

Selection details

Initiative: project / ufc-compliance

Why this match: The PR adds a DatadogFlagsConfiguration option, off by default. When it is on, a boolean dd_evaluation_telemetry_opt_out=true in the evaluation context stops new evaluation events, counts and automatic RUM flag annotations from being sent. The EvaluationAggregator skips recording when telemetryOptedOut is set, and the opt-out decision is kept per subject during refresh and subject switches. This is per-context suppression of evaluation event egress for a user opt-out, which is what ufc-compliance covers. flag-evaluation-evp explicitly assigns this kind of suppression to ufc-compliance. Exposure behavior is unchanged. The Dart fallback has supplemental review disabled, so no additional area applies.

Why these owners: The matched initiative has fewer than two approved, non-author candidates. The approved global pool supplies the remaining review owners; proposed memberships were not activated.

  • @sameerank — final owner (final-review-owners): Global pool filling a pod coverage gap. Existing review coverage preserved.
  • @greghuels — final owner (final-review-owners): Global pool filling a pod coverage gap. Existing review coverage preserved.

The PR author was excluded. Existing reviewers and teams were preserved.

Debug or fix a problem

Workflow run · Bits Code session

  • Wrong project or pod? Clarify this PR’s purpose, or correct the reviewer registry and publish the change. Sheet edits take effect after publication.
  • Need another reviewer now? Request them in GitHub. This workflow only adds requests and keeps existing reviewers.
  • Stuck beyond five minutes or failed? Inspect the run’s failed step and available Bits session. After fixing the cause, rerun the workflow with this PR URL and dry_run=false. Unchanged completed runs are skipped. If the receipt says needs_reconciliation or a write outcome is uncertain, ask the workflow owner to reconcile GitHub and the receipt before retrying; do not delete the lock blindly.
  • Report a problem: Comment on the reviewer-routing skill PR with this PR URL, the workflow run link, and the expected initiative or reviewer correction.
Evidence and run details

✅ Complete — reviewer coverage verified. The workflow checked pending requests or submitted reviews on the evaluated head.

Generated asynchronously by the FFE reviewer-routing workflow.

Changed paths: packages/datadog_flags/lib/src/flags_configuration.dart, packages/datadog_flags/lib/src/evaluation_aggregator.dart, packages/datadog_flags/lib/src/default_flags_client.dart, packages/datadog_flags/lib/src/flags_repository.dart, packages/datadog_flags/lib/src/flags_client.dart, packages/datadog_flags/lib/src/datadog_flags.dart, packages/datadog_flags_flutter/lib/src/datadog_flags_plugin.dart, packages/datadog_flags/test/evaluation_telemetry_opt_out_test.dart, packages/datadog_flags/test/evaluation_telemetry_opt_out_http_test.dart, packages/datadog_flags_flutter/example/integration_test/evaluation_telemetry_opt_out_test.dart

Evaluated head: 54ffe382620a5237faaa00ac1cd877bcf3e59266

Registry revision: revision:1946aa2a-530e-487a-84a7-83aff44a1089

Pinned skill source: d214cfc65ae154b97d39af5cf32caf48aaec9bf0

Instructions: workflow-injected snapshot (no plugin loaded)

Instruction snapshot SHA-256: f23b2a88c13c0da90e2dd58246a14f257af91e2195c555039bd555b52e6f3516

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Pipelines

✨ Unblock PR with BitsAI

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 6 Pipeline jobs failed

DDCI - DataDog/dd-sdk-flutter | build-macos-spm — 🔧 Needs a code fix, caused by this PR

View more details · View in DDCI

DataDog/dd-sdk-flutter | build-macos-spm — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

DDCI - DataDog/dd-sdk-flutter | android-integration-test

View more details · View in DDCI

View all 6 failed jobs.

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 55bff60 | Docs | View more details | Give us feedback!

@leoromanovsky
leoromanovsky marked this pull request as ready for review October 15, 2026 19:13
@leoromanovsky
leoromanovsky requested review from a team as code owners October 15, 2026 19:13
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T16:23:08.502784Z 55bff60 New commits
🔒 Security Review ✅ Completed 2026-11-04T16:26:17.521893Z 55bff60 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

fuzzybinary
fuzzybinary previously approved these changes Oct 15, 2026

@fuzzybinary fuzzybinary left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for this, but if we can I'd like to keep datadog_flutter_plugin/integration_test_app testing only that package, and integration tests for datadog_flags and datadog_flags_flutter should really live in those packages. This is what the http interception packages do, and it will make life easier if you need to have tests for both datadog_flags_flutter and open telemetry.

datadog_common_test holds all of our common integration test helpers, so you should be able to make integration tests in your packages fairly easily.

Comment thread packages/datadog_flags/README.md Resolved
Comment thread packages/datadog_flags/README.md Resolved

@vjfridge vjfridge left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some thoughts! Let me know when it's ready for another look!

vjfridge
vjfridge previously approved these changes Oct 21, 2026
fuzzybinary
fuzzybinary previously approved these changes Oct 21, 2026

@fuzzybinary fuzzybinary left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly nits.

Comment thread melos.yaml Resolved
@fuzzybinary

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 54ffe38262

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54ffe38262

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@fuzzybinary
fuzzybinary changed the base branch from v4 to develop October 22, 2026 20:39
@fuzzybinary
fuzzybinary dismissed stale reviews from vjfridge and themself October 22, 2026 20:39

The base branch was changed.

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The opt-out policy preserves each active subject’s latest reporting decision during refresh and suppresses evaluation aggregation and automatic RUM annotations while preserving exposures. No actionable regression was identified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 54ffe38

Comment thread packages/datadog_flags/README.md Resolved
Comment thread melos.yaml Resolved
Comment thread tools/ci/bin/web_integration_tests.dart Resolved
@greghuels
greghuels removed their request for review October 27, 2026 10:33
@leoromanovsky

leoromanovsky commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

FFE reviewer selection

Reviewers: @vjfridge, @sameerank

Why: Privacy opt-out and event logging rules — Adds an opt-in, per-context user opt-out for evaluation telemetry in the Dart Flags SDK and Flutter wrapper. Reviewers come from the matched pod.

🤖 Automated selection.

Selection details

Initiative: project / ufc-compliance

Why this match: Adds an opt-in, per-context user opt-out for evaluation telemetry in the Dart Flags SDK and Flutter wrapper. When the option is enabled and the context has boolean dd_evaluation_telemetry_opt_out=true, the SDK stops recording evaluation events and adds no automatic RUM flag annotations. Flag evaluation results, targeting and exposure behavior stay unchanged. The repository keeps each subject's opt-out decision across refreshes and subject switches. This is per-context suppression of evaluation event egress, which matches ufc-compliance. It is not EVP telemetry consent and not onboarding diagnostics.

  • @vjfridge — primary (flag-evaluation-evp): Matched pod member. Existing review coverage preserved.
  • @sameerank — floating (flag-evaluation-evp): Coverage and knowledge sharing. Covers: openfeature-architecture. Existing review coverage preserved.

Additional review: openfeature-architecture — The change alters shared client contracts. The public FlagDetails evaluation result gains an evaluationTelemetryOptedOut metadata field, which the default client fills in and integrations read. The Flutter client wrapper also changes how initialize and reset handle context and lifecycle: it adds context revisioning that drops superseded initializations and deduplicates concurrent delegate resolution. These are behavioral changes to the evaluation-result, context and lifecycle contracts. Coverage: @sameerank. Evidence: packages/datadog_flags/lib/src/flags_client.dart, packages/datadog_flags/lib/src/default_flags_client.dart, packages/datadog_flags_flutter/lib/src/datadog_flags_plugin.dart

The PR author was excluded. Existing reviewers and teams were preserved.

Debug or fix a problem

Workflow run · Bits Code session

  • Wrong project or pod? Clarify this PR’s purpose, or correct the reviewer registry and publish the change. Sheet edits take effect after publication.
  • Need another reviewer now? Request them in GitHub. This workflow only adds requests and keeps existing reviewers.
  • Stuck beyond five minutes or failed? Inspect the run’s failed step and available Bits session. After fixing the cause, rerun the workflow with this PR URL and dry_run=false. Unchanged completed runs are skipped. If the receipt says needs_reconciliation or a write outcome is uncertain, ask the workflow owner to reconcile GitHub and the receipt before retrying; do not delete the lock blindly.
  • Report a problem: Comment on the reviewer-routing skill PR with this PR URL, the workflow run link, and the expected initiative or reviewer correction.
Evidence and run details

✅ Complete — reviewer coverage verified. The workflow checked pending requests or submitted reviews on the evaluated head.

Generated asynchronously by the FFE reviewer-routing workflow.

Changed paths: packages/datadog_flags/lib/src/flags_configuration.dart, packages/datadog_flags/lib/src/flags_repository.dart, packages/datadog_flags/lib/src/evaluation_aggregator.dart, packages/datadog_flags/lib/src/default_flags_client.dart, packages/datadog_flags/lib/src/datadog_flags.dart, packages/datadog_flags_flutter/lib/src/datadog_flags_plugin.dart, packages/datadog_flags/test/evaluation_telemetry_opt_out_test.dart, packages/datadog_flags/test/evaluation_telemetry_opt_out_http_test.dart, packages/datadog_flags_flutter/test/evaluation_telemetry_opt_out_test.dart

Evaluated head: 54ffe382620a5237faaa00ac1cd877bcf3e59266

Registry revision: revision:fe6a8bb4-aeba-4b6e-af89-db919eb47638

Pinned skill source: 7e3283c602f6b18a7e3e623eecb52d3a9c091a2e

Instructions: workflow-injected snapshot (no plugin loaded)

Instruction snapshot SHA-256: 52ed8cb68675dde1a47addaefe4a9500891c24014abf7dade6dfe38cf836c1d2

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 063690821d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/datadog_flags/README.md Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ddcbf8ea1a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8136569af6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@vjfridge vjfridge left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My earlier concerns have been addressed, and the behavior tested looks good overall, thank you!

I left comments on a narrow startup case that can undercount flag evaluations, plus an optional test cleanup.


bool get evaluationTelemetryOptedOut =>
_evaluationTelemetryOptedOut ||
(_subjectTelemetryOptOut[context?.targetingKey] ?? false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Count evaluations correctly during anonymous-to-identified startup

Codex working with Vickie

There is a narrow startup case where the SDK can stop counting evaluations even though reporting is allowed for the current user. If an opted-out anonymous user starts loading flags, then the app switches to an identified user with reporting allowed before either request finishes, this lookup keeps applying the anonymous user's opt-out. No flags have actually been installed for that anonymous user, so there is no previous set of flags whose reporting needs to stay suppressed. The app still returns its normal fallback value, but evaluation counts are understated during that window.

How we reproduced it

On head 55bff60, we used a mocked HTTP client to hold assignment responses pending:

  1. Enable enableEvaluationTelemetryOptOutParameter.
  2. Start initialization with targetingKey: null and dd_evaluation_telemetry_opt_out: true; hold the response before any assignments are installed.
  3. Start initialization for targetingKey: 'B' with dd_evaluation_telemetry_opt_out: false; hold that response too.
  4. Evaluate a boolean flag while B is pending, then release the requests and flush telemetry.

Expected: the usual providerNotReady fallback, an opt-out decision of false, and one recorded evaluation. Observed: the same fallback, but an opt-out decision of true and zero recorded evaluations.

Only this case failed in an eight-case matrix covering enabled/disabled support, anonymous/named previous subjects, and installed/not-yet-installed assignments. In particular, already-installed opted-out anonymous assignments correctly stay suppressed while B loads; that behavior should be preserved. All requests and telemetry were intercepted by the mock client.

Suggested fix and validation

Only consult the retained subject policy when assignments are actually installed. Otherwise, context?.targetingKey == null conflates an absent state with an installed anonymous subject:

bool get evaluationTelemetryOptedOut =>
    _evaluationTelemetryOptedOut ||
    (_state != null &&
        (_subjectTelemetryOptOut[context?.targetingKey] ?? false));

Keep regression coverage for both the uninstalled-anonymous case above and the installed-anonymous case that must remain opted out. In our scratch copy, this guard passed the eight-case reproduction and the complete core test suite: 249 tests, including the added cases.

(count, event) => count + (event['evaluation_count'] as int),
);

static Future<_Intake> start() async => _Intake();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, non-blocking nit: construct the test intake directly

Codex working with Vickie

Could we simplify this helper? _Intake.start() only creates an _Intake, but its name and Future return type make it look as though it starts a server or waits for setup. Constructing the fixture directly would make the tests easier to read. This is test-code cleanup with no app-user impact.

How we verified it

We inspected the helper and its call sites at head 55bff60. Its entire implementation is:

static Future<_Intake> start() async => _Intake();

There is no asynchronous setup or I/O in this helper. The fixture uses MockClient, and the call sites already register addTearDown(intake.close). This is based on source inspection; we did not run a separate behavioral test for this optional cleanup.

Suggested fix

Replace each:

final intake = await _Intake.start();

with:

final intake = _Intake();

Then remove start() and keep the existing teardown registrations.

@aarsilv aarsilv left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving with mostly minor findings now but assuming you engage on the "p1"s (which are questionably p1s)

)..additionalConfig['_dd.needsClearTextHttp'] = true,
TrackingConsent.granted,
);
addTearDown(sdk.flushAndDeinitialize);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P1] Make the relocated opt-out integration test pass on iOS, and check it on Android.

Since 0636908 moved this test into integration_test_app, the ios-integration-test job failed on 4 of 5 runs and android-integration-test on 5 of 5. On develop over the same 21 days, those jobs failed on 3 of 31 and 7 of 32 runs. On an iOS simulator, this teardown failed in both runs, and a Podfile change fixes it. I could not run Android. My hypothesis there is that the OS blocks cleartext HTTP to the mock server, but I have not seen which Android test fails.

1. iOS — reproduced on an iPhone 17 Pro simulator, iOS 26.5

The iOS plugin compiles flushAndDeinitialize only under #if DD_SDK_COMPILED_FOR_TESTING (packages/datadog_flutter_plugin/datadog_flutter_plugin_ios/darwin/datadog_flutter_plugin_ios/Sources/datadog_flutter_plugin/DatadogSdkPlugin.swift:378-383). This app's Podfile does not set that flag, so this line throws MissingPluginException(No implementation found for method flushAndDeinitialize on channel datadog_sdk_flutter). The SDK is never deinitialized between cases. The log then shows Trying to add logs to a dead session, and the next four cases find no RUM views at line 238.

Run Opt-out cases openfeature_test.dart
55bff60, two runs (SwiftPM; CocoaPods as in CI) 5 of 5 fail in each pass
55bff60 + Podfile change, two runs 5 of 5 pass (whole directory 115 s, then 80 s) pass
a88e36f (base) file absent pass

flags_intake_test.dart skips its only test on native platforms.

--- a/packages/datadog_flags_flutter/integration_test_app/ios/Podfile
+++ b/packages/datadog_flags_flutter/integration_test_app/ios/Podfile
@@ -39,6 +39,8 @@ post_install do |installer|
   installer.pods_project.targets.each do |target|
     flutter_additional_ios_build_settings(target)
     target.build_configurations.each do |config|
+      # Exposes the plugin's `flushAndDeinitialize` method, which the tests use to reset the SDK.
+      config.build_settings['SWIFT_ACTIVE_COMPILATION_CONDITIONS'] = '$(inherited) DD_SDK_COMPILED_FOR_TESTING'
       # Match the host minimum; Xcode 27 no longer builds iOS 13 targets.
       if config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f < 15.0
         config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0'

packages/datadog_flutter_plugin/datadog_flutter_plugin/e2e_test_app/ios/Podfile:49 sets the same flag. CI builds with CocoaPods, so regenerate ios/Podfile.lock with the repo's CocoaPods version.

The flushAndDeinitialize teardown arrived in 8136569, which matches the iOS failures at 8136569 and 55bff60. The iOS failure at ddcbf8e came before that teardown, and I could not explain it.

2. Android — static diagnosis; I could not run Android here

The test sends native RUM to http://localhost:2228 (packages/datadog_common_test/lib/src/mock_http_sever.dart:22). Line 98 sets _dd.needsClearTextHttp, which lets the Datadog SDK send HTTP. On Android 9 and later, the default network security policy blocks cleartext HTTP unless the app allows it. At 54ffe38, CI copied this PR's example/integration_test/AndroidManifest.xml, which set usesCleartextTraffic="true", into the app's android/app/src/debug/AndroidManifest.xml before the run (melos.yaml:293-295 at that commit), and the Android job passed. 0636908 deleted that manifest, and integration_test_app has no network security config. The core plugin's integration app allows localhost in packages/datadog_flutter_plugin/datadog_flutter_plugin/integration_test_app/android/app/src/main/res/xml/network_security_config.xml.

--- a/packages/datadog_flags_flutter/integration_test_app/android/app/src/debug/AndroidManifest.xml
+++ b/packages/datadog_flags_flutter/integration_test_app/android/app/src/debug/AndroidManifest.xml
@@ -4,4 +4,6 @@
          to allow setting breakpoints, to provide hot reload, etc.
     -->
     <uses-permission android:name="android.permission.INTERNET"/>
+    <!-- Native uploads go to the local recording server over HTTP. -->
+    <application android:usesCleartextTraffic="true" />
 </manifest>

An alternative is a copy of the core app's network_security_config.xml, referenced from the main manifest with android:networkSecurityConfig. It allows cleartext only to localhost and its subdomains.

3. CI history — GitHub commit statuses and Datadog CI Visibility
Commit android-integration-test ios-integration-test
54ffe38 success success
0636908 failure success
ddcbf8e failure failure
8136569 failure failure
55bff60 (two runs) failure, failure failure, failure
develop, last 21 days 7 of 32 failed 3 of 31 failed

build-macos-spm also fails here, with cannot find 'trackBackgroundEvents' in scope. It fails the same way at the base a88e36f and passes on current develop (00dcdb4), so it is likely a develop failure, not this PR's.

key: key,
value: defaultValue,
error: FlagEvaluationError.providerNotReady,
evaluationTelemetryOptedOut: _evaluationTelemetryOptedOut,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P3] Add tests for four opt-out result values that the suites do not check.

These one-line mutants pass all 241 core and 61 wrapper tests. Each one changes only the evaluationTelemetryOptedOut value or the opt-out metadata on an error, no-op, or post-shutdown result; the evaluation gate itself is unchanged. Integrations that read those fields would get the wrong value. The two files below catch all four and pass at 55bff60.

Mutation results — full suites at 55bff60 against the new files
Mutant PR suites New tests that fail
NoOpDatadogFlagsClient.shutdown() keeps the decision pass both retained no-op client drops the opt-out after … rows
Provider structure error result drops the opt-out metadata pass provider structure type mismatch … and provider structure flag not found …
Wrapper _providerNotReady drops the wrapper decision pass result before delegate resolution carries the RUM policy: optedOut=true
Wrapper _shutdown() keeps the decision pass shutdown clears the RUM policy on the retained wrapper

Both files use one test per case and keep fixtures inside main; the wrapper file uses mocktail. With them added, the suites pass 247/247 and 64/64.

Core test file — `packages/datadog_flags/test/evaluation_telemetry_opt_out_survivors_test.dart`, 6 tests
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0. This product includes software
// developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

// Legacy API compatibility coverage.
// ignore_for_file: deprecated_member_use

import 'dart:convert';

import 'package:datadog_flags/datadog_flags.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk_experimental.dart'
    show createIsolatedOpenFeatureAPI;
import 'package:test/test.dart';

void main() {
  const optedOutContext = FlagsEvaluationContext(
    targetingKey: 'user',
    attributes: {FlagsEvaluationContext.evaluationTelemetryOptOutKey: true},
  );

  for (final lifecycle in ['client shutdown', 'sdk disable']) {
    test('retained no-op client drops the opt-out after $lifecycle', () async {
      final sdk = DatadogFlags();
      addTearDown(sdk.disable);
      await sdk.enable(
        configuration: const DatadogFlagsConfiguration(
          enableEvaluationTelemetryOptOutParameter: true,
        ),
      );
      final client = sdk.sharedClient();
      await client.initialize(optedOutContext);
      expect(
        client
            .getBooleanDetails(key: 'b', defaultValue: false)
            .evaluationTelemetryOptedOut,
        isTrue,
      );
      await (lifecycle == 'client shutdown'
          ? client.shutdown()
          : sdk.disable());
      expect(
        client
            .getBooleanDetails(key: 'b', defaultValue: false)
            .evaluationTelemetryOptedOut,
        isFalse,
      );
    });
  }

  for (final (name, evaluate, errorCode)
      in <
        (
          String,
          FlagEvaluationDetails<Object> Function(OpenFeatureClient),
          ErrorCode,
        )
      >[
        (
          'structure type mismatch',
          (client) => client.getStructureDetails('flag', const {}),
          ErrorCode.typeMismatch,
        ),
        (
          'structure flag not found',
          (client) => client.getStructureDetails('missing', const {}),
          ErrorCode.flagNotFound,
        ),
        (
          'boolean flag not found',
          (client) => client.getBooleanDetails('missing', false),
          ErrorCode.flagNotFound,
        ),
        (
          'integer type mismatch',
          (client) => client.getIntegerDetails('flag', 0),
          ErrorCode.typeMismatch,
        ),
      ]) {
    test('provider $name result carries the opt-out metadata', () async {
      final api = createIsolatedOpenFeatureAPI();
      addTearDown(api.shutdown);
      await api.setEvaluationContextAndWait(
        EvaluationContext(
          targetingKey: 'user',
          attributes: const {
            FlagsEvaluationContext.evaluationTelemetryOptOutKey: true,
          },
        ),
      );
      await api.setProviderAndWait(
        DatadogOpenFeatureProvider(
          configuration: DatadogFlagsConfiguration(
            datadogConfig: const DatadogFlagsConfig(
              clientToken: 'local-test-token',
              env: 'test',
              site: DatadogFlagsSite.us1,
            ),
            enableEvaluationTelemetryOptOutParameter: true,
            httpClient: MockClient((request) async {
              if (!request.url.path.contains('precompute')) {
                return http.Response('{}', 202);
              }
              return http.Response(
                jsonEncode({
                  'data': {
                    'attributes': {
                      'flags': {
                        'flag': {
                          'allocationKey': 'allocation',
                          'variationKey': 'on',
                          'variationType': 'boolean',
                          'variationValue': true,
                          'reason': 'TARGETING_MATCH',
                          'doLog': false,
                        },
                      },
                    },
                  },
                }),
                200,
              );
            }),
          ),
        ),
      );
      final details = evaluate(api.getClient());
      expect(details.errorCode, errorCode);
      expect(
        details.flagMetadata[DatadogOpenFeatureProvider
            .evaluationTelemetryOptOutMetadata],
        isTrue,
      );
    });
  }
}
Wrapper test file — `packages/datadog_flags_flutter/test/evaluation_telemetry_opt_out_survivors_test.dart`, 3 tests
// Legacy API compatibility coverage.
// ignore_for_file: deprecated_member_use

// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0. This product includes software
// developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import 'dart:async';

import 'package:datadog_flags_flutter/datadog_flags_flutter.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class _MockClient extends Mock implements DatadogFlagsClient {}

void main() {
  const key = FlagsEvaluationContext.evaluationTelemetryOptOutKey;

  setUpAll(() => registerFallbackValue(FlagsEvaluationContext.empty));

  for (final optedOut in [false, true]) {
    test(
      'result before delegate resolution carries the RUM policy: optedOut=$optedOut',
      () async {
        final delegate = _MockClient();
        when(() => delegate.initialize(any())).thenAnswer((_) async {});
        final resolved = Completer<DatadogFlagsClient>();
        final client = DatadogFlutterFlagsClient(
          name: 'default',
          resolveDelegate: () => resolved.future,
          enableEvaluationTelemetryOptOutParameter: true,
          addRumFeatureFlagEvaluation: null,
        );
        final initializing = client.initialize(
          FlagsEvaluationContext(
            targetingKey: 'u',
            attributes: {key: optedOut},
          ),
        );
        final details = client.getBooleanDetails(
          key: 'flag',
          defaultValue: false,
        );
        expect(details.error, FlagEvaluationError.providerNotReady);
        expect(details.evaluationTelemetryOptedOut, optedOut);
        resolved.complete(delegate);
        await initializing;
      },
    );
  }

  test('shutdown clears the RUM policy on the retained wrapper', () async {
    final delegate = _MockClient();
    when(() => delegate.initialize(any())).thenAnswer((_) async {});
    when(() => delegate.shutdown()).thenAnswer((_) async {});
    final client = DatadogFlutterFlagsClient(
      name: 'default',
      resolveDelegate: () async => delegate,
      enableEvaluationTelemetryOptOutParameter: true,
      addRumFeatureFlagEvaluation: null,
    );
    await client.initialize(
      const FlagsEvaluationContext(targetingKey: 'u', attributes: {key: true}),
    );
    await client.shutdown();
    final details = client.getBooleanDetails(key: 'flag', defaultValue: false);
    expect(details.error, FlagEvaluationError.providerNotReady);
    expect(details.evaluationTelemetryOptedOut, isFalse);
    verify(() => delegate.shutdown()).called(1);
  });
}


FlagsEvaluationContext? get context => _state?.data.context;

bool get evaluationTelemetryOptedOut =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

Heads up: #1297 and #1307 each need a small semantic merge to keep the opt-out working.

I merged both onto this PR and current develop, keeping both sides. #1297 withholds assignments on a targeting-key change, so context is null while the next subject loads, and this lookup loses the opted-out subject. #1307 builds provider repositories without enableEvaluationTelemetryOptOutParameter, so the opt-out is off for the provider. Each fix is one line.

1. #1297 — look up the installed subject, not `context`

#1297 turns evaluations during B's load into providerNotReady results, so this PR's test subject opt-out remains active during B refresh needs new expectations. With those updates and without this fix, both rows (responses 200 and 400) fail: evaluationTelemetryOptedOut is false where the test expects true. With this fix, both rows pass.

--- a/packages/datadog_flags/lib/src/flags_repository.dart
+++ b/packages/datadog_flags/lib/src/flags_repository.dart
@@ -72,7 +72,7 @@ class FlagsRepository {
 
   bool get evaluationTelemetryOptedOut =>
       _evaluationTelemetryOptedOut ||
-      (_subjectTelemetryOptOut[context?.targetingKey] ?? false);
+      (_subjectTelemetryOptOut[_state?.data.context.targetingKey] ?? false);
 
   DatadogFlagsClientStatus get status => _status;
 

#1297's test a later initialize stays last expects each wrapper initialize() call to reach the delegate in order. The wrapper's _contextRevision guard skips superseded calls, so that test fails until the merge drops the guard. The final policy still comes from the latest call. Some of this PR's tests also need new expectations, because #1297 withholds assignments during a subject switch, so those evaluations become providerNotReady.

2. #1307 — pass the option to provider-created repositories

After the merge, 10 tests in datadog_rum_hook_test.dart fail, while datadog_flags still passes 456/456. No core test caught it.

--- a/packages/datadog_flags/lib/src/datadog_openfeature_provider.dart
+++ b/packages/datadog_flags/lib/src/datadog_openfeature_provider.dart
@@ -880,6 +880,8 @@ final class _ProviderResources {
         store: configuration.store,
         dateProvider: configuration.dateProvider,
         initializationTimeout: configuration.initializationTimeout,
+        enableEvaluationTelemetryOptOutParameter:
+            configuration.enableEvaluationTelemetryOptOutParameter,
       ),
       exposureLogger: exposureLogger,
       evaluationAggregator: evaluationAggregator,

With both fixes, the guard removal, and the expectation updates, the merged suites pass: datadog_flags 456/456, datadog_flags_flutter 119/119 (including 46 merge probes). The provider tests in the survivors comment would add core coverage for this path.

openfeature.DomainScopedProvider {
/// Metadata consumed by telemetry hooks to suppress automatic reporting.
static const evaluationTelemetryOptOutMetadata =
'datadog.evaluationTelemetryOptedOut';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P3] Rename the new public metadata key to datadog.evaluation_telemetry_opted_out before it ships.

The provider's other public keys use snake_case: datadog.allocation_key and datadog.serial_id (flags_client.dart:11-12). Any OpenFeature hook can read this key on opted-out results, so a rename after release breaks hooks that match the old string.

Suggested change — the value only; the constant name stays
--- a/packages/datadog_flags/lib/src/datadog_openfeature_provider.dart
+++ b/packages/datadog_flags/lib/src/datadog_openfeature_provider.dart
@@ -35,7 +35,7 @@ final class DatadogOpenFeatureProvider
         openfeature.DomainScopedProvider {
   /// Metadata consumed by telemetry hooks to suppress automatic reporting.
   static const evaluationTelemetryOptOutMetadata =
-      'datadog.evaluationTelemetryOptedOut';
+      'datadog.evaluation_telemetry_opted_out';
 
   /// OpenFeature flag metadata key containing the Datadog allocation key.
   static const allocationKeyMetadata = datadogAllocationKeyMetadata;

Applied alone to 55bff60, analysis is clean and the suites pass 241/241 and 61/61, because the tests read the constant.

final variant = details.variant;
if (details.error == null && variant != null) {
if (!_evaluationTelemetryOptedOut &&
!details.evaluationTelemetryOptedOut &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P3] Keep this client's opt-out decision on results from an unconfigured core.

When the plugin skips _flags.enable (no SDK configuration, or an unsupported site such as us1Fed without datadogConfig; lines 138-154), the core's no-op client runs without the option. Results then report evaluationTelemetryOptedOut: true before the delegate resolves and false after. The no-op client returns providerNotReady results (no_op_flags_client.dart:91-95). No RUM annotation follows either way: before resolution the wrapper builds its own result, and after resolution its own decision gates RUM (line 387). But integrations that read the field get the wrong value.

Suggested fix — return the wrapper decision when the core does not know it
--- a/packages/datadog_flags_flutter/lib/src/datadog_flags_plugin.dart
+++ b/packages/datadog_flags_flutter/lib/src/datadog_flags_plugin.dart
@@ -390,7 +390,19 @@ class DatadogFlutterFlagsClient
         variant != null) {
       _addRumFeatureFlagEvaluation?.call(details.key, variant);
     }
-    return details;
+    if (!_evaluationTelemetryOptedOut || details.evaluationTelemetryOptedOut) {
+      return details;
+    }
+    // An unconfigured core does not know this client's opt-out decision.
+    return FlagDetails(
+      key: details.key,
+      value: details.value,
+      variant: details.variant,
+      reason: details.reason,
+      error: details.error,
+      evaluationTelemetryOptedOut: true,
+      flagMetadata: details.flagMetadata,
+    );
   }
 
   FlagDetails<T> _providerNotReady<T>({

The copy keeps all seven FlagDetails fields. It runs whenever this client's decision is true and the result's is false.

Regression test — for `test/datadog_flags_plugin_test.dart`
  for (final site in <DatadogSite?>[null, DatadogSite.us1Fed]) {
    test('opt-out decision survives an unconfigured core: $site', () async {
      final sdk = MockDatadogSdk();
      when(() => sdk.configuration).thenReturn(
        site == null
            ? null
            : DatadogConfiguration(
                clientToken: 'token',
                service: 'service',
                env: 'env',
                site: site,
              ),
      );
      final flags = DatadogFlags();
      addTearDown(flags.disable);
      final plugin = DatadogFlagsPlugin(
        sdk,
        flagsConfiguration: const DatadogFlagsConfiguration(
          enableEvaluationTelemetryOptOutParameter: true,
        ),
        rumIntegrationEnabled: false,
        flags: flags,
      )..initialize();
      final client = plugin.sharedClient();
      final initializing = client.initialize(
        const FlagsEvaluationContext(
          targetingKey: 'user',
          attributes: {
            FlagsEvaluationContext.evaluationTelemetryOptOutKey: true,
          },
        ),
      );
      final before = client.getBooleanDetails(key: 'flag', defaultValue: false);
      await initializing;
      final after = client.getBooleanDetails(key: 'flag', defaultValue: false);
      expect(before.evaluationTelemetryOptedOut, isTrue);
      expect(after.evaluationTelemetryOptedOut, isTrue);
    });
  }

Both cases fail at 55bff60 (Expected: true, Actual: <false>). With only this fix, they pass, analysis is clean, and the wrapper suite passes 63/63.

See the [contributing guide](../../CONTRIBUTING.md) and
[OpenFeature validation instructions](OPENFEATURE_VALIDATION.md).

## Evaluation Telemetry Opt-Out

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P3] Move the opt-out section above "## Contributing" in both READMEs.

Here it follows "## Contributing" (line 165). In datadog_flags_flutter/README.md it also follows the license line (lines 92-96). The other feature sections come before "## Contributing".

Suggested change — move the Contributing section to the end
--- a/packages/datadog_flags/README.md
+++ b/packages/datadog_flags/README.md
@@ -162,11 +162,6 @@ For successful evaluations, details report `CACHED` when the installed assignmen
 were restored from the configured store, including an in-memory store. After a
 network response replaces those assignments, details report the response reason.
 
-## Contributing
-
-See the [contributing guide](../../CONTRIBUTING.md) and
-[OpenFeature validation instructions](OPENFEATURE_VALIDATION.md).
-
 ## Evaluation Telemetry Opt-Out
 
 Enable `enableEvaluationTelemetryOptOutParameter` in `DatadogFlagsConfiguration`
@@ -186,3 +181,8 @@ See the API documentation for
 and the legacy
 [`DatadogFlagsClient.initialize`](https://pub.dev/documentation/datadog_flags/latest/datadog_flags/DatadogFlagsClient/initialize.html)
 for context-change and telemetry-policy timing.
+
+## Contributing
+
+See the [contributing guide](../../CONTRIBUTING.md) and
+[OpenFeature validation instructions](OPENFEATURE_VALIDATION.md).
--- a/packages/datadog_flags_flutter/README.md
+++ b/packages/datadog_flags_flutter/README.md
@@ -89,12 +89,6 @@ For successful evaluations, details report `CACHED` when the installed assignmen
 were restored from the configured store, including an in-memory store. After a
 network response replaces those assignments, details report the response reason.
 
-## Contributing
-
-See the [contributing guide](../../CONTRIBUTING.md) and
-[OpenFeature validation instructions](../datadog_flags/OPENFEATURE_VALIDATION.md).
-Licensed under [Apache 2.0](LICENSE).
-
 ## Evaluation Telemetry Opt-Out
 
 Enable `enableEvaluationTelemetryOptOutParameter` in `DatadogFlagsConfiguration`
@@ -114,3 +108,9 @@ See the API documentation for
 and the legacy
 [`DatadogFlagsClient.initialize`](https://pub.dev/documentation/datadog_flags/latest/datadog_flags/DatadogFlagsClient/initialize.html)
 for context-change and telemetry-policy timing.
+
+## Contributing
+
+See the [contributing guide](../../CONTRIBUTING.md) and
+[OpenFeature validation instructions](../datadog_flags/OPENFEATURE_VALIDATION.md).
+Licensed under [Apache 2.0](LICENSE).

import 'package:http/testing.dart';
import 'package:test/test.dart';

const _key = 'dd_evaluation_telemetry_opt_out';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Claude working with Aaron Silverman:

[P3] Optional: use the public key constant here, and share one helper for the opt-out check in datadog_flags.

Both coverage tests retype the key as a file-scope const _key (line 20 in the wrapper's copy). FlagsEvaluationContext.evaluationTelemetryOptOutKey exists for this, and declaring it inside main matches the AGENTS.md:62 rule for shared fixtures. The check enabled && control is bool && control also appears three times: flags_repository.dart:90, no_op_flags_client.dart:39, and datadog_flags_plugin.dart:257. An extension in evaluation_context.dart removes the two core copies. It stays out of the package's public exports, because datadog_flags.dart exports that file with show FlagsEvaluationContext.

Tests — the key constant, inside `main`
--- a/packages/datadog_flags/test/evaluation_telemetry_opt_out_coverage_test.dart
+++ b/packages/datadog_flags/test/evaluation_telemetry_opt_out_coverage_test.dart
@@ -17,5 +17,5 @@ import 'package:test/test.dart';
 
-const _key = 'dd_evaluation_telemetry_opt_out';
-
 void main() {
+  const key = FlagsEvaluationContext.evaluationTelemetryOptOutKey;
+
   // Only the exact key with boolean true opts out.
@@ -24,9 +24,9 @@ void main() {
     {'Dd_Evaluation_Telemetry_Opt_Out': true},
-    {_key: '1'},
-    {_key: 'yes'},
-    {_key: 'TRUE'},
-    {_key: 'on'},
-    {_key: 1.0},
+    {key: '1'},
+    {key: 'yes'},
+    {key: 'TRUE'},
+    {key: 'on'},
+    {key: 1.0},
     {
-      _key: [true],
+      key: [true],
     },
@@ -64,3 +64,3 @@ void main() {
         targetingKey: 'user',
-        attributes: {_key: true},
+        attributes: {key: true},
       ),
@@ -88,3 +88,3 @@ void main() {
     await client.initialize(
-      const FlagsEvaluationContext(attributes: {_key: true}),
+      const FlagsEvaluationContext(attributes: {key: true}),
     );
@@ -108,3 +108,3 @@ void main() {
           targetingKey: 'user',
-          attributes: {_key: true},
+          attributes: {key: true},
         ),
--- a/packages/datadog_flags_flutter/test/evaluation_telemetry_opt_out_coverage_test.dart
+++ b/packages/datadog_flags_flutter/test/evaluation_telemetry_opt_out_coverage_test.dart
@@ -19,5 +19,5 @@ class _MockClient extends Mock implements DatadogFlagsClient {}
 
-const _key = 'dd_evaluation_telemetry_opt_out';
-
 void main() {
+  const key = FlagsEvaluationContext.evaluationTelemetryOptOutKey;
+
   setUpAll(() => registerFallbackValue(FlagsEvaluationContext.empty));
@@ -27,5 +27,5 @@ void main() {
     {'DD_EVALUATION_TELEMETRY_OPT_OUT': true},
-    {_key: '1'},
-    {_key: 'yes'},
-    {_key: 'TRUE'},
+    {key: '1'},
+    {key: 'yes'},
+    {key: 'TRUE'},
   ]) {
@@ -115,3 +115,3 @@ void main() {
     await client.initialize(
-      const FlagsEvaluationContext(targetingKey: 'u', attributes: {_key: true}),
+      const FlagsEvaluationContext(targetingKey: 'u', attributes: {key: true}),
     );
@@ -156,3 +156,3 @@ void main() {
             targetingKey: 'u',
-            attributes: {_key: optedOut},
+            attributes: {key: optedOut},
           ),
Core helper — one extension for the repository and the no-op client
--- a/packages/datadog_flags/lib/src/evaluation_context.dart
+++ b/packages/datadog_flags/lib/src/evaluation_context.dart
@@ -41,3 +41,14 @@ final class FlagsEvaluationContext {
   /// Converts this context to a JSON map.
   Map<String, Object?> toJson() => _$FlagsEvaluationContextToJson(this);
 }
+
+/// Reads the evaluation telemetry opt-out attribute.
+extension EvaluationTelemetryOptOut on FlagsEvaluationContext {
+  /// Whether this context opts out when the configuration [enabled] the
+  /// attribute. Only boolean `true` opts out.
+  bool optsOutOfEvaluationTelemetry({required bool enabled}) {
+    final control =
+        attributes[FlagsEvaluationContext.evaluationTelemetryOptOutKey];
+    return enabled && control is bool && control;
+  }
+}
--- a/packages/datadog_flags/lib/src/flags_repository.dart
+++ b/packages/datadog_flags/lib/src/flags_repository.dart
@@ -50,9 +50,6 @@ class FlagsRepository {
   // requests are cancelled and cannot install their assignments.
   final Map<String?, bool> _subjectTelemetryOptOut = {};
 
-  static const _telemetryControl =
-      FlagsEvaluationContext.evaluationTelemetryOptOutKey;
-
   FlagsRepository({
     required this.clientName,
     required this.fetcher,
@@ -85,9 +82,9 @@ class FlagsRepository {
   bool get isRestoredFromStore => _state?.restoredFromStore ?? false;
 
   Future<void> initialize(FlagsEvaluationContext context) {
-    final control = context.attributes[_telemetryControl];
-    _evaluationTelemetryOptedOut =
-        enableEvaluationTelemetryOptOutParameter && control is bool && control;
+    _evaluationTelemetryOptedOut = context.optsOutOfEvaluationTelemetry(
+      enabled: enableEvaluationTelemetryOptOutParameter,
+    );
     if (enableEvaluationTelemetryOptOutParameter) {
       _subjectTelemetryOptOut[context.targetingKey] =
           _evaluationTelemetryOptedOut;
--- a/packages/datadog_flags/lib/src/no_op_flags_client.dart
+++ b/packages/datadog_flags/lib/src/no_op_flags_client.dart
@@ -33,10 +33,9 @@ class NoOpDatadogFlagsClient
 
   @override
   Future<void> initialize(FlagsEvaluationContext context) async {
-    final control =
-        context.attributes[FlagsEvaluationContext.evaluationTelemetryOptOutKey];
-    _evaluationTelemetryOptedOut =
-        enableEvaluationTelemetryOptOutParameter && control is bool && control;
+    _evaluationTelemetryOptedOut = context.optsOutOfEvaluationTelemetry(
+      enabled: enableEvaluationTelemetryOptOutParameter,
+    );
   }
 
   @override

The wrapper keeps its own copy; reaching the helper from another package would need a src/ import or a public export. The opt-out test files still use the literal key, so its spelling stays pinned. Applied alone to 55bff60, analysis is clean and the suites pass 241/241 and 61/61.

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.

5 participants