From 5e8b6485359d30f1ec5ba5df2f6444400f28525f Mon Sep 17 00:00:00 2001 From: Sameeran Kunche Date: Thu, 19 Nov 2026 12:16:13 -0800 Subject: [PATCH 1/3] test(ffe): add fresh-process Node core provider harness Exercise synchronous portable bootstrap, overlapping request contexts and dependency telemetry, configuration replacement, and explicit exposure tracking through OpenFeature. Keep activation gated pending a containing Node dependency update. --- docs/understand/weblogs/parametric_weblog.md | 18 ++ manifests/cpp.yml | 1 + manifests/dotnet.yml | 1 + manifests/golang.yml | 1 + manifests/java.yml | 1 + manifests/nodejs.yml | 1 + manifests/php.yml | 1 + manifests/python.yml | 1 + manifests/ruby.yml | 1 + manifests/rust.yml | 1 + tests/ffe/README.md | 23 ++- .../test_ffe/core-provider-rules-wire.json | 7 + .../test_ffe/core-provider-rules-wire.md | 27 +++ .../parametric/test_ffe/test_core_provider.py | 159 +++++++++++++++++ .../nodejs/parametric/ffe-core-provider.js | 168 ++++++++++++++++++ .../build/docker/nodejs/parametric/server.js | 21 +++ .../_test_clients/_test_client_parametric.py | 10 ++ 17 files changed, 441 insertions(+), 1 deletion(-) create mode 100644 tests/parametric/test_ffe/core-provider-rules-wire.json create mode 100644 tests/parametric/test_ffe/core-provider-rules-wire.md create mode 100644 tests/parametric/test_ffe/test_core_provider.py create mode 100644 utils/build/docker/nodejs/parametric/ffe-core-provider.js diff --git a/docs/understand/weblogs/parametric_weblog.md b/docs/understand/weblogs/parametric_weblog.md index 74137655f11..d33554f9466 100644 --- a/docs/understand/weblogs/parametric_weblog.md +++ b/docs/understand/weblogs/parametric_weblog.md @@ -995,6 +995,24 @@ Response: not declared by the reference server. It contains `value`, `reason`, ` (see [Feature Flag evaluation provider status](../scenarios/parametric.md#feature-flag-evaluation-provider-status)), and `exposureHooks` when requested. +#### `POST /ffe/core-provider` + +Called by `ParametricTestClientApi.ffe_core_provider()`. Node.js-only fresh-process +portable-provider probe; it resolves the built `@datadog/openfeature-node-server/rules-based` +package shipped inside `dd-trace`, without importing or initializing the tracer. + +The request contains `operation` (`bootstrap`, `overlap`, `refresh`, or `tracking`), +portable `wire`, and an array of evaluation `contexts`. `refresh` additionally takes +`replacementWire` and server-channel `fetchOptions`. The custom Fetch transport +uses `SYSTEM_TESTS_FFE_RULES_BASE_URL`, as for the standalone rules helper. + +The response reports actual OpenFeature startup/final status, operation results, +configuration-change notifications or explicit sink records, package/runtime +versions, and HTTP/exposure-channel counts observed until child-process exit. +An unexpected failure, process timeout, or invalid child output returns HTTP 500. +The parent strips `NODE_OPTIONS` and imposes a 10-second deadline. +This does not test tracer hook attachment or delivery to an intake. + #### `POST /ffe/fetch-rules-configuration` Called by `ParametricTestClientApi.ffe_fetch_rules_configuration()`. Fetch and serialize portable rules in a process without tracer/provider initialization. diff --git a/manifests/cpp.yml b/manifests/cpp.yml index e2fc4fa4860..e8c99283af1 100644 --- a/manifests/cpp.yml +++ b/manifests/cpp.yml @@ -188,6 +188,7 @@ manifest: tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart::test_baggage: missing_feature (Automatic baggage propagation is not implemented) tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart_With_Extract_First::test_baggage: missing_feature (Automatic baggage propagation is not implemented) tests/parametric/test_ffe/test_configuration_sources.py: irrelevant (cpp is not in scope for v1 agentless server SDK configuration-source coverage) + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: missing_feature diff --git a/manifests/dotnet.yml b/manifests/dotnet.yml index 0ca7c22c0e4..a85642f9512 100644 --- a/manifests/dotnet.yml +++ b/manifests/dotnet.yml @@ -1284,6 +1284,7 @@ manifest: : # TODO: a lower version might be supported - declaration: bug (FFL-3325) component_version: <3.55.0 + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: '>=3.36.0' # Modified by easy win activation script diff --git a/manifests/golang.yml b/manifests/golang.yml index 97d0185a51c..e028efba924 100644 --- a/manifests/golang.yml +++ b/manifests/golang.yml @@ -2348,6 +2348,7 @@ manifest: tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart: incomplete_test_app (The parametric test app does not emit restart span links or preserve baggage) tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart_With_Extract_First: missing_feature (DD_TRACE_PROPAGATION_EXTRACT_FIRST=true is unsupported; dd-trace-go panics when extraction fails) tests/parametric/test_ffe/test_configuration_sources.py: v2.11.0-dev # Easy win for all weblogs and version 2.10.1 + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: v2.5.0-dev diff --git a/manifests/java.yml b/manifests/java.yml index 36a51452f09..07122bdc951 100644 --- a/manifests/java.yml +++ b/manifests/java.yml @@ -4385,6 +4385,7 @@ manifest: ? tests/parametric/test_ffe/test_configuration_sources.py::Test_Feature_Flag_Configuration_Source_Selection::test_stable_true_preserves_default_agentless : v1.65.0 tests/parametric/test_ffe/test_configuration_sources.py::Test_Feature_Flag_Configuration_Source_Warm_State_Preservation: v1.65.0 + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: v1.56.0 diff --git a/manifests/nodejs.yml b/manifests/nodejs.yml index 71f953a8bc4..71f082dfee6 100644 --- a/manifests/nodejs.yml +++ b/manifests/nodejs.yml @@ -2749,6 +2749,7 @@ manifest: : # TODO: a lower version might be supported - declaration: missing_feature (Requires a release containing dd-trace-js#11111) component_version: <6.25.0 + tests/parametric/test_ffe/test_core_provider.py: missing_feature (Awaiting the DatadogCoreProvider package dependency update; validate a containing build locally) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: *ref_5_75_0 diff --git a/manifests/php.yml b/manifests/php.yml index 6b4a045416a..ed267236442 100644 --- a/manifests/php.yml +++ b/manifests/php.yml @@ -1764,6 +1764,7 @@ manifest: ? tests/parametric/test_ffe/test_configuration_sources.py::Test_Feature_Flag_Configuration_Source_Selection::test_stable_true_preserves_default_agentless : missing_feature (FFL-2705 tracks PHP agentless configuration-source implementation; FFL-2731 tracks system-tests configuration-source contract) tests/parametric/test_ffe/test_configuration_sources.py::Test_Feature_Flag_Configuration_Source_Warm_State_Preservation: missing_feature (FFL-2705 tracks PHP agentless configuration-source implementation; FFL-2731 tracks system-tests configuration-source contract) + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: v1.21.0-dev diff --git a/manifests/python.yml b/manifests/python.yml index be41e372f77..2e1390073ec 100644 --- a/manifests/python.yml +++ b/manifests/python.yml @@ -3199,6 +3199,7 @@ manifest: tests/parametric/test_ffe/test_configuration_sources.py: v4.14.0-dev ? tests/parametric/test_ffe/test_configuration_sources.py::Test_Feature_Flag_Configuration_Source_Missing_Api_Key::test_default_endpoint_fails_fast : 'missing_feature (Requires a release containing dd-trace-py#21548)' + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release; dd-trace-py PR 21346) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: - declaration: irrelevant (Legacy coverage is pinned to Python 4.16.0) diff --git a/manifests/ruby.yml b/manifests/ruby.yml index 733040453f9..c75b173da74 100644 --- a/manifests/ruby.yml +++ b/manifests/ruby.yml @@ -2736,6 +2736,7 @@ manifest: tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart: incomplete_test_app (The parametric test app does not emit restart span links or preserve baggage) tests/parametric/test_extract_behavior.py::Test_ExtractBehavior_Restart_With_Extract_First: incomplete_test_app (The parametric test app does not emit restart span links or preserve baggage) tests/parametric/test_ffe/test_configuration_sources.py: v2.46.0-dev + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: v2.23.0 diff --git a/manifests/rust.yml b/manifests/rust.yml index 2fa9593b4d4..cc02269c6ee 100644 --- a/manifests/rust.yml +++ b/manifests/rust.yml @@ -301,6 +301,7 @@ manifest: tests/parametric/test_dynamic_configuration.py::Test_DynamicConfigSdkConfiguration::test_sdk_config_profiling_enabled: missing_feature (SDK_CONFIGURATION capability not yet implemented) tests/parametric/test_extract_behavior.py: '>=0.4.1-dev' tests/parametric/test_ffe/test_configuration_sources.py: irrelevant (rust is not in scope for v1 agentless server SDK configuration-source coverage) + tests/parametric/test_ffe/test_core_provider.py: incomplete_test_app (Standalone portable-provider endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: '>=0.5.3-dev+fd1307f' # TODO: a lower version might be supported diff --git a/tests/ffe/README.md b/tests/ffe/README.md index bf46dcbf00a..c2f5ce49ad3 100644 --- a/tests/ffe/README.md +++ b/tests/ffe/README.md @@ -63,7 +63,28 @@ configuration copies are needed. Standalone rules-configuration helpers are covered in `tests/parametric/test_ffe/test_rules_configuration.py` (Node.js only for now). These tests use `dd-trace/openfeature/rules-based` in a fresh process without initializing a tracer or provider, fetch protobuf over HTTP, and validate the portable wire output, channel credentials, typed errors, deadlines and cancellation during headers/body delivery, transport failures, invalid options, and redirect protection. They do not initialize a browser SDK or contact Datadog. -These tests report to [Offline initialization and portable configuration helpers (#562)](https://feature-parity.us1.prod.dog/?feature=562). Current coverage is limited to Node's rules-based fetching and serialization; precomputed helpers and provider offline initialization are not covered here. +These tests report to [Offline initialization and portable configuration helpers (#562)](https://feature-parity.us1.prod.dog/?feature=562). + +`tests/parametric/test_ffe/test_core_provider.py` separately exercises the built Node +`DatadogCoreProvider` through the real OpenFeature SDK in fresh processes. It covers +synchronous READY registration, zero-request local evaluation, overlapping contexts +with different root/dependency values, explicit server-channel refresh, rejected +replacement retention, configuration-change events, and opt-in exposure sinks with +deduplication and late-hook rollback. These are package-level integration checks, +not tracer evaluation-upload or intake-delivery tests. The adapter resolves the +Node package from the tracer's dependencies without importing the tracer; no +`dd-trace` wrapper exports are required. The Node manifest remains `missing_feature` +until a containing dependency update is available; other libraries are gated too. +With a custom containing Node build, select this file and force it with `-F`: + +```sh +PYTEST_XDIST_AUTO_NUM_WORKERS=1 TEST_LIBRARY=nodejs ./run.sh PARAMETRIC \ + tests/parametric/test_ffe/test_core_provider.py -F tests/parametric/test_ffe/test_core_provider.py +``` + +Fixture provenance and deterministic expected behavior are documented in +[`core-provider-rules-wire.md`](../parametric/test_ffe/core-provider-rules-wire.md). +Standalone precomputation helper coverage is a separate change in [#8267](https://github.com/DataDog/system-tests/pull/8267). `Test_FFE_Rules_Configuration_Selection` covers tag/key-pattern query parameters on both distribution channels, invalid/URL-overflow selections dropped with diagnostics, quiet empty-selection omission, and retention of the full response when the backend ignores selection. It also checks diagnostics for nonempty `DD-Flag-Selection-Ignored` response headers, including unknown reasons. The mock does not implement backend filtering. These cases require [openfeature-js-client #445](https://github.com/DataDog/openfeature-js-client/pull/445) in the `dd-trace` dependency and remain gated in the Node manifest until a containing build is available. Other SDKs retain the existing file-level gate. diff --git a/tests/parametric/test_ffe/core-provider-rules-wire.json b/tests/parametric/test_ffe/core-provider-rules-wire.json new file mode 100644 index 00000000000..21710c58c54 --- /dev/null +++ b/tests/parametric/test_ffe/core-provider-rules-wire.json @@ -0,0 +1,7 @@ +{ + "version": 1, + "rules": { + "response": "CgASBHByb2QacQoJdGVzdC1mbGFnEmQQBBoCKAEaBAgBKAAiKgoKYWxsb2NhdGlvbhABGgwSCgoEc2FsdBABGGQiCgoECAAQZBgHIAEoASIqCghmYWxsYmFjaxACGgwSCgoEc2FsdBABGGQiDAoECAAQZBABGAcgAigBGnIKDHByZXJlcXVpc2l0ZRJiEAQaAigBGgQIASgAIioKCmFsbG9jYXRpb24QABoMEgoKBHNhbHQQARhkIgoKBAgAEGQYByABKAEiKAoIZmFsbGJhY2saDBIKCgRzYWx0EAEYZCIMCgQIABBkEAEYByACKAEiBhIECgIIAyICCgAqAm9uKgNvZmYqAlVTKgdjb3VudHJ5KgxwcmVyZXF1aXNpdGUyBF5VUyQ6CQoBMQoBMgoBM0oFKgMSAQJKB1oFCAQSAQBKB1oFCAQSAQE=", + "etag": "rules-etag" + } +} diff --git a/tests/parametric/test_ffe/core-provider-rules-wire.md b/tests/parametric/test_ffe/core-provider-rules-wire.md new file mode 100644 index 00000000000..84cc46eb685 --- /dev/null +++ b/tests/parametric/test_ffe/core-provider-rules-wire.md @@ -0,0 +1,27 @@ +# Offline provider fixture + +`core-provider-rules-wire.json` is a harness-specific derivative of the existing +`rules-wire.json`, originally from `openfeature-js-client/packages/browser/test/data/rules-v1-wire.json`. +The portable wire was generated with the rules codec at +[`d50b38c2`](https://github.com/DataDog/openfeature-js-client/commit/d50b38c2e4040946af79ec3d19f6483589a7ce13). +No credentials or customer configuration are included. + +The decoded configuration has these deterministic rules: + +| Flag | Condition | Value | Variant | Reason | +|--|--|--|--|--| +| `prerequisite` | `country` is `US` | `true` | `on` | `TARGETING_MATCH` | +| `prerequisite` | otherwise | `false` | `off` | `SPLIT` | +| `test-flag` | `prerequisite` has variant `on` | `true` | `on` | `TARGETING_MATCH` | +| `test-flag` | `prerequisite` has variant `off` | `false` | `off` | `SPLIT` | + +Relative to `rules-wire.json`: add a boolean `off=false` variation and select it +in the fallback allocation; enable exposure logging for that allocation; clone +the flag as `prerequisite`; and give `test-flag`'s two allocations +`flagEvaluationStringMembership` conditions on `prerequisite`'s `on`/`off` variants. +Both flags use the original full 100-shard range, serial ID 7, and allocation keys. +The original fixture remains unchanged and is also used by the shared HTTP mock: +its fallback is `on=true`, so a successful server-channel refresh changes the value. + +Expected values and subjects are asserted in Python, not computed by the adapter. +The adapter only deserializes the wire and uses the built package's public entry point. diff --git a/tests/parametric/test_ffe/test_core_provider.py b/tests/parametric/test_ffe/test_core_provider.py new file mode 100644 index 00000000000..a64370b652a --- /dev/null +++ b/tests/parametric/test_ffe/test_core_provider.py @@ -0,0 +1,159 @@ +"""Offline provider lifecycle through the real OpenFeature SDK, isolated from the tracer.""" + +import json +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, urlsplit + +from utils import features, pytest, scenarios, slow +from utils.docker_fixtures import ParametricTestClientApi as APMLibrary +from utils.mocked_backend import MockedBackendServer +from utils.mocked_backend.ffe import RULES_CONFIG_PATH, load_rules_wire_fixture + +WIRE = (Path(__file__).parent / "core-provider-rules-wire.json").read_text() +FETCHED_WIRE = json.dumps(load_rules_wire_fixture()) +CONTEXTS = [ + {"targetingKey": "subject-us", "country": "US", "dd_assignment_token": "private-token-us"}, + {"targetingKey": "subject-fr", "country": "FR", "dd_assignment_token": "private-token-fr"}, +] + + +@pytest.fixture +def library_env(mocked_backend: MockedBackendServer) -> dict[str, str]: + return {"SYSTEM_TESTS_FFE_RULES_BASE_URL": mocked_backend.ffe_library_base_url} + + +def assert_evaluation(result: dict[str, Any], *, value: bool, variant: str, reason: str) -> None: + assert result["value"] is value, result + assert result["variant"] == variant, result + assert result["reason"] == reason, result + assert result.get("errorCode") is None, result + + +def assert_offline(result: dict[str, Any], mocked_backend: MockedBackendServer, *, exposure_events: int = 0) -> None: + assert result["startup"]["status"] == "READY", result + assert result["startup"]["readyEvents"] == 1, result + assert result["startup"]["httpRequests"] == 0, result + assert result["status"] == "READY", result + assert result["httpRequests"] == 0, result + assert result["exposureEvents"] == exposure_events, result + assert mocked_backend.ffe_get_requests() == [] + + +@scenarios.parametric +@features.feature_flags_portable_configuration +@slow +class Test_FFE_Core_Provider: + def test_synchronous_bootstrap(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + with test_library: + result = test_library.ffe_core_provider({"operation": "bootstrap", "wire": WIRE, "contexts": CONTEXTS}) + + assert_offline(result, mocked_backend) + assert result["startup"]["hooks"] == 0 + assert_evaluation(result["results"][0], value=True, variant="on", reason="TARGETING_MATCH") + assert_evaluation(result["results"][1], value=False, variant="off", reason="SPLIT") + + def test_overlapping_contexts(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + with test_library: + result = test_library.ffe_core_provider({"operation": "overlap", "wire": WIRE, "contexts": CONTEXTS}) + + assert_offline(result, mocked_backend, exposure_events=4) + assert_evaluation(result["results"][0], value=True, variant="on", reason="TARGETING_MATCH") + assert_evaluation(result["results"][1], value=False, variant="off", reason="SPLIT") + observations = {item["subject"]: item for item in result["observations"]} + assert len(result["observations"]) == 2 + for context, expected in zip(CONTEXTS, [True, False], strict=True): + observed = observations[context["targetingKey"]] + assert observed["value"] is expected + assert len(observed["dependencies"]) == 1 + assert observed["dependencies"][0]["flag"] == "prerequisite" + assert observed["dependencies"][0]["value"] is expected + assert observed["consumed"] == [] + exposures = result["exposures"] + assert len(exposures) == 4, exposures + assert {(item["subject"]["id"], item["flag"]["key"]) for item in exposures} == { + (context["targetingKey"], flag) for context in CONTEXTS for flag in ("test-flag", "prerequisite") + } + for exposure in exposures: + expected_country = "US" if exposure["subject"]["id"] == "subject-us" else "FR" + assert exposure["subject"]["attributes"] == {"country": expected_country} + assert "private-token" not in json.dumps(result) + + def test_refresh_and_rejected_replacement( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + with test_library: + for response in ("valid", "forbidden"): + mocked_backend.client.ffe_set_response(response, response_format="protobuf") + request_count = len(mocked_backend.ffe_get_requests()) + result = test_library.ffe_core_provider( + { + "operation": "refresh", + "wire": WIRE, + "replacementWire": WIRE if response == "valid" else FETCHED_WIRE, + "contexts": [CONTEXTS[1]], + "fetchOptions": {"distributionChannel": "server", "apiKey": "system-tests-key", "env": "test"}, + } + ) + assert result["startup"]["status"] == "READY" + assert result["startup"]["httpRequests"] == 0 + for phase in ("initial", "duringRefresh"): + assert_evaluation(result[phase], value=False, variant="off", reason="SPLIT") + for phase in ("afterFetch", "afterInvalid"): + assert_evaluation( + result[phase], + value=response == "valid", + variant="on" if response == "valid" else "off", + reason="SPLIT", + ) + assert result["invalidUpdateError"] == "TypeError" + assert result["unchanged"] is True + if response == "forbidden": + assert result["fetchError"] == {"name": "ConfigurationFetchError", "code": "http", "status": 403} + else: + assert "fetchError" not in result + assert_evaluation( + result["afterReplacement"], + value=response != "valid", + variant="off" if response == "valid" else "on", + reason="SPLIT", + ) + notifications = result["notifications"] + expected_values = [True, False] if response == "valid" else [True] + assert len(notifications) == len(expected_values) + for notification, value in zip(notifications, expected_values, strict=True): + assert notification["status"] == "READY" + assert_evaluation( + notification["result"], value=value, variant="on" if value else "off", reason="SPLIT" + ) + assert result["status"] == "READY" + assert result["httpRequests"] == 1 + assert result["exposureEvents"] == 0 + requests = mocked_backend.ffe_get_requests()[request_count:] + assert len(requests) == 1, requests + url = urlsplit(requests[0]["path"]) + assert url.path == f"{RULES_CONFIG_PATH}/server" + assert parse_qs(url.query) == {"dd_env": ["test"]} + assert requests[0]["headers"]["dd-api-key"] == "system-tests-key" + + def test_opt_in_exposure_tracking(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + with test_library: + result = test_library.ffe_core_provider({"operation": "tracking", "wire": WIRE, "contexts": CONTEXTS}) + + assert_offline(result, mocked_backend, exposure_events=6) + assert result["startup"]["hooks"] == 0 + assert result["beforeHook"] == 0 + assert result["deduplicated"] == 2 + assert result["failed"]["reason"] == "ERROR" + assert result["failed"]["errorCode"] == "GENERAL" + assert result["afterFailure"] == 2 + assert result["afterRetry"] == 4 + assert result["afterClose"] == 4 # The tracking helper owns this cache, not the provider. + exposures = result["exposures"] + assert len(exposures) == 6 + assert {(item["subject"]["id"], item["flag"]["key"], item["variant"]["key"]) for item in exposures[:4]} == { + (context["targetingKey"], flag, "on" if context["country"] == "US" else "off") + for context in CONTEXTS + for flag in ("test-flag", "prerequisite") + } + assert "private-token" not in json.dumps(result) diff --git a/utils/build/docker/nodejs/parametric/ffe-core-provider.js b/utils/build/docker/nodejs/parametric/ffe-core-provider.js new file mode 100644 index 00000000000..a20fc32b610 --- /dev/null +++ b/utils/build/docker/nodejs/parametric/ffe-core-provider.js @@ -0,0 +1,168 @@ +'use strict' + +const { channel } = require('node:diagnostics_channel') +const { writeFileSync } = require('node:fs') +const { createRequire } = require('node:module') + +async function main () { + const { operation, wire, replacementWire, contexts, fetchOptions } = JSON.parse(process.argv[2]) + let httpRequests = 0 + let exposureEvents = 0 + let outcome + const observeHttp = () => { httpRequests++ } + const observeExposure = () => { exposureEvents++ } + const subscriptions = [ + ['undici:request:create', observeHttp], + ['http.client.request.start', observeHttp], + ['ffe:exposure:submit', observeExposure] + ] + for (const [name, listener] of subscriptions) channel(name).subscribe(listener) + + // Resolve the tracer's packaged dependency without loading or initializing the tracer. + const requireLibrary = createRequire(require.resolve('dd-trace/package.json')) + const { + ConfigurationFetchError, + configurationFromString, + configurationToString, + createExposureTracking, + DatadogCoreProvider, + fetchRulesConfiguration + } = requireLibrary('@datadog/openfeature-node-server/rules-based') + const { OpenFeature, ProviderEvents } = require('@openfeature/server-sdk') + OpenFeature.setLogger({ error () {}, warn () {}, info () {}, debug () {} }) + const tracking = ['tracking', 'overlap'].includes(operation) + ? createExposureTracking({ collectDependencyEvaluations: true }) + : undefined + const exposures = [] + const sink = channel('ffe:exposure:submit') + const captureExposure = event => exposures.push(event) + sink.subscribe(captureExposure) + const provider = new DatadogCoreProvider(configurationFromString(wire), { ...tracking?.providerOptions }) + if (operation === 'overlap') provider.hooks.push(tracking.createHook(sink)) + let readyEvents = 0 + OpenFeature.addHandler(ProviderEvents.Ready, () => { readyEvents++ }) + OpenFeature.setProvider('offline-provider', provider) + let client = OpenFeature.getClient('offline-provider') + const startup = { status: client.providerStatus, readyEvents, hooks: provider.hooks.length, httpRequests } + const evaluate = (context, options) => client.getBooleanDetails('test-flag', false, context, options) + + try { + if (operation === 'bootstrap') { + outcome = { startup, results: await Promise.all(contexts.map(context => evaluate(context))) } + } else if (operation === 'overlap') { + const observations = [] + let arrivals = 0 + let release + const barrier = new Promise(resolve => { release = resolve }) + client.addHooks({ + after: async (hookContext, details) => { + if (++arrivals === contexts.length) release() + await barrier + const sidecar = tracking.providerOptions.dependencyTelemetrySidecar + const dependencies = sidecar.takeDependencyEvaluations(undefined, undefined, hookContext.context) + observations.push({ + subject: hookContext.context.targetingKey, + value: details.value, + dependencies: dependencies.map(item => ({ flag: item.flagKey, value: item.details.value })), + consumed: sidecar.takeDependencyEvaluations(details.flagMetadata, undefined, hookContext.context) + }) + } + }) + outcome = { startup, results: await Promise.all(contexts.map(context => evaluate(context))), observations, exposures } + } else if (operation === 'refresh') { + const initial = await evaluate(contexts[0]) + const notifications = [] + client.addHandler(ProviderEvents.ConfigurationChanged, () => { + notifications.push({ status: client.providerStatus, result: evaluate(contexts[0]) }) + }) + let allowFetch + let fetchEntered + const entered = new Promise(resolve => { fetchEntered = resolve }) + const proceed = new Promise(resolve => { allowFetch = resolve }) + const refresh = fetchRulesConfiguration({ + ...fetchOptions, + fetch: async (url, init) => { + fetchEntered() + await proceed + const { pathname, search } = new URL(url) + return fetch(`${process.env.SYSTEM_TESTS_FFE_RULES_BASE_URL}${pathname}${search}`, init) + } + }) + await entered + const duringRefresh = await evaluate(contexts[0]) + allowFetch() + let fetchError + try { + provider.setConfiguration(await refresh) + } catch (error) { + if (!(error instanceof ConfigurationFetchError)) throw error + fetchError = { name: error.name, code: error.code, status: error.status } + } + const afterFetch = await evaluate(contexts[0]) + const snapshot = configurationToString(provider.getConfiguration()) + let invalidUpdateError + try { + provider.setConfiguration(configurationFromString('invalid wire')) + } catch (error) { + if (!(error instanceof TypeError)) throw error + invalidUpdateError = error.name + } + const unchanged = configurationToString(provider.getConfiguration()) === snapshot + const afterInvalid = await evaluate(contexts[0]) + provider.setConfiguration(configurationFromString(replacementWire)) + outcome = { + startup, + initial, + duringRefresh, + fetchError, + afterFetch, + invalidUpdateError, + unchanged, + afterInvalid, + afterReplacement: await evaluate(contexts[0]), + notifications: await Promise.all(notifications.map(async event => ({ ...event, result: await event.result }))) + } + } else if (operation === 'tracking') { + await evaluate(contexts[0]) + const beforeHook = exposures.length + provider.hooks.push(tracking.createHook(sink)) + await Promise.all([evaluate(contexts[0]), evaluate(contexts[0])]) + const deduplicated = exposures.length + const failed = await evaluate(contexts[1], { hooks: [{ after () { throw new Error('rejected by application') } }] }) + const afterFailure = exposures.length + await evaluate(contexts[1]) + const afterRetry = exposures.length + await OpenFeature.clearProviders() + const restarted = new DatadogCoreProvider(configurationFromString(wire), { ...tracking.providerOptions }) + restarted.hooks.push(tracking.createHook(sink)) + OpenFeature.setProvider('offline-provider', restarted) + client = OpenFeature.getClient('offline-provider') + await evaluate(contexts[0]) + const afterClose = exposures.length + tracking.clear() + await evaluate(contexts[0]) + outcome = { startup, beforeHook, deduplicated, failed, afterFailure, afterRetry, afterClose, exposures } + } else { + throw new Error(`Unknown provider operation: ${operation}`) + } + outcome.status = client.providerStatus + outcome.versions = { + node: process.version, + provider: requireLibrary('@datadog/openfeature-node-server/package.json').version + } + } finally { + await OpenFeature.clearProviders() + tracking?.clear() + // Observe deferred activity until exit; a leaked worker hits the endpoint's process deadline. + process.once('exit', () => { + if (outcome !== undefined) writeFileSync(1, JSON.stringify({ ...outcome, httpRequests, exposureEvents })) + sink.unsubscribe(captureExposure) + for (const [name, listener] of subscriptions) channel(name).unsubscribe(listener) + }) + } +} + +main().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/utils/build/docker/nodejs/parametric/server.js b/utils/build/docker/nodejs/parametric/server.js index 0653a08d5b6..02fc5ac1f59 100644 --- a/utils/build/docker/nodejs/parametric/server.js +++ b/utils/build/docker/nodejs/parametric/server.js @@ -611,6 +611,27 @@ app.post("/trace/otel/otel_set_baggage", (req, res) => { }); // Feature Flag & Experimentation endpoints +app.post('/ffe/core-provider', (req, res) => { + const { execFile } = require('node:child_process') + const path = require('node:path') + const env = { ...process.env } + delete env.NODE_OPTIONS + execFile(process.execPath, [path.join(__dirname, 'ffe-core-provider.js'), JSON.stringify(req.body)], { + env, + timeout: 10000 + }, (error, stdout, stderr) => { + if (error) { + console.error('Standalone FFE provider failed:', stderr || error) + return res.status(500).json({ error: 'Standalone FFE provider failed' }) + } + try { + res.json(JSON.parse(stdout)) + } catch (error) { + res.status(500).json({ error: 'Invalid standalone FFE provider output' }) + } + }) +}) + app.post('/ffe/fetch-rules-configuration', (req, res) => { const { execFile } = require('node:child_process') const path = require('node:path') diff --git a/utils/docker_fixtures/_test_clients/_test_client_parametric.py b/utils/docker_fixtures/_test_clients/_test_client_parametric.py index 37d09b7c510..99ed5432ed3 100644 --- a/utils/docker_fixtures/_test_clients/_test_client_parametric.py +++ b/utils/docker_fixtures/_test_clients/_test_client_parametric.py @@ -816,6 +816,12 @@ def otel_current_span(self) -> _TestOtelSpan | None: return _TestOtelSpan(self, span_response["span_id"], span_response["trace_id"]) + def ffe_core_provider(self, options: dict[str, Any]) -> dict[str, Any]: + """Exercise a locally initialized provider through OpenFeature in a fresh process.""" + response = self._session.post(self._url("/ffe/core-provider"), json=options, timeout=15) + response.raise_for_status() + return cast("dict[str, Any]", response.json()) + def ffe_fetch_rules_configuration(self, options: dict[str, Any]) -> dict[str, Any]: """Fetch and serialize portable rules in a process without tracer/provider initialization.""" response = self._session.post(self._url("/ffe/fetch-rules-configuration"), json=options, timeout=15) @@ -1319,6 +1325,10 @@ def ffe_fetch_rules_configuration(self, options: dict[str, Any]) -> dict[str, An """Fetch and serialize portable rules without initializing a tracer or provider.""" return self._client.ffe_fetch_rules_configuration(options) + def ffe_core_provider(self, options: dict[str, Any]) -> dict[str, Any]: + """Exercise the standalone provider without initializing the tracer.""" + return self._client.ffe_core_provider(options) + def ffe_start( self, configuration: dict | None = None, *, flag_selection: dict[str, list[str]] | None = None ) -> bool: From 7e29d53556c1d1e0f1c54ff11e43b2536fdd8032 Mon Sep 17 00:00:00 2001 From: Sameeran Kunche Date: Fri, 20 Nov 2026 12:18:31 -0800 Subject: [PATCH 2/3] test(ffe): cover portable configuration codec round trips Verify rules and plaintext/encoded precomputed snapshots through OpenFeature, retain context and telemetry metadata, and reject malformed replacement wires without losing the active configuration. --- docs/understand/weblogs/parametric_weblog.md | 6 +- tests/ffe/README.md | 6 +- .../parametric/test_ffe/test_core_provider.py | 96 +++++++++++++++++++ .../nodejs/parametric/ffe-core-provider.js | 44 ++++++++- 4 files changed, 145 insertions(+), 7 deletions(-) diff --git a/docs/understand/weblogs/parametric_weblog.md b/docs/understand/weblogs/parametric_weblog.md index d33554f9466..bed0d8a8ca3 100644 --- a/docs/understand/weblogs/parametric_weblog.md +++ b/docs/understand/weblogs/parametric_weblog.md @@ -1001,10 +1001,14 @@ Called by `ParametricTestClientApi.ffe_core_provider()`. Node.js-only fresh-proc portable-provider probe; it resolves the built `@datadog/openfeature-node-server/rules-based` package shipped inside `dd-trace`, without importing or initializing the tracer. -The request contains `operation` (`bootstrap`, `overlap`, `refresh`, or `tracking`), +The request contains `operation` (`bootstrap`, `overlap`, `refresh`, `tracking`, `roundtrip`, or `invalid-codec`), portable `wire`, and an array of evaluation `contexts`. `refresh` additionally takes `replacementWire` and server-channel `fetchOptions`. The custom Fetch transport uses `SYSTEM_TESTS_FFE_RULES_BASE_URL`, as for the standalone rules helper. +`roundtrip` accepts `format` (`rules`, `precomputed`, or `encoded`) and an optional +`clientFingerprint`; it returns the serialized/restored snapshots and evaluations. +`invalid-codec` accepts `invalidWires` and returns codec diagnostic categories, +replacement errors, and evaluations from the retained configuration. The response reports actual OpenFeature startup/final status, operation results, configuration-change notifications or explicit sink records, package/runtime diff --git a/tests/ffe/README.md b/tests/ffe/README.md index c2f5ce49ad3..2e075d74e60 100644 --- a/tests/ffe/README.md +++ b/tests/ffe/README.md @@ -70,8 +70,10 @@ These tests report to [Offline initialization and portable configuration helpers synchronous READY registration, zero-request local evaluation, overlapping contexts with different root/dependency values, explicit server-channel refresh, rejected replacement retention, configuration-change events, and opt-in exposure sinks with -deduplication and late-hook rollback. These are package-level integration checks, -not tracer evaluation-upload or intake-delivery tests. The adapter resolves the +deduplication and late-hook rollback. +It also covers semantic codec round-trips for rules and plaintext/hashed precomputed +snapshots, metadata and context binding, and malformed/versioned input rejection. +These are package-level integration checks, not tracer evaluation-upload or intake-delivery tests. The adapter resolves the Node package from the tracer's dependencies without importing the tracer; no `dd-trace` wrapper exports are required. The Node manifest remains `missing_feature` until a containing dependency update is available; other libraries are gated too. diff --git a/tests/parametric/test_ffe/test_core_provider.py b/tests/parametric/test_ffe/test_core_provider.py index a64370b652a..197639ff5d4 100644 --- a/tests/parametric/test_ffe/test_core_provider.py +++ b/tests/parametric/test_ffe/test_core_provider.py @@ -1,6 +1,7 @@ """Offline provider lifecycle through the real OpenFeature SDK, isolated from the tracer.""" import json +import hashlib from pathlib import Path from typing import Any from urllib.parse import parse_qs, urlsplit @@ -16,6 +17,13 @@ {"targetingKey": "subject-us", "country": "US", "dd_assignment_token": "private-token-us"}, {"targetingKey": "subject-fr", "country": "FR", "dd_assignment_token": "private-token-fr"}, ] +ENCODING_FINGERPRINT = json.dumps( + { + "version": 1, + "sdk": {"name": "browser", "version": "system-test"}, + "capabilities": ["assignment-encoding-flag-key-256-v1"], + } +) @pytest.fixture @@ -44,6 +52,94 @@ def assert_offline(result: dict[str, Any], mocked_backend: MockedBackendServer, @features.feature_flags_portable_configuration @slow class Test_FFE_Core_Provider: + def test_configuration_codec_roundtrips( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + with test_library: + for format_ in ("rules", "precomputed", "encoded"): + result = test_library.ffe_core_provider( + { + "operation": "roundtrip", + "wire": WIRE, + "contexts": CONTEXTS, + "format": format_, + **({"clientFingerprint": ENCODING_FINGERPRINT} if format_ == "encoded" else {}), + } + ) + assert_offline(result, mocked_backend) + assert result["startup"]["hooks"] == 0 + serialized = json.loads(result["serialized"]) + assert json.loads(result["restored"]) == serialized + assert_evaluation(result["results"][0], value=True, variant="on", reason="TARGETING_MATCH") + metadata = result["results"][0]["flagMetadata"] + assert metadata["__dd_allocation_key"] == "allocation" + assert metadata["__dd_split_serial_id"] == 7 + assert metadata["__dd_do_log"] is True + assert metadata["__dd_observe_full_evaluation_data"] is False + if format_ == "rules": + assert set(serialized) == {"version", "rules"} + assert serialized["version"] == 1 + assert serialized["rules"]["etag"] == "rules-etag" + assert_evaluation(result["results"][1], value=False, variant="off", reason="SPLIT") + else: + assert set(serialized) == {"version", "precomputed"} + assert serialized["version"] == (2 if format_ == "encoded" else 1) + snapshot = serialized["precomputed"] + assert snapshot["context"] == {"targetingKey": "subject-us", "country": "US"} + assert snapshot["fetchedAt"] > 0 + attributes = json.loads(snapshot["response"])["data"]["attributes"] + assert attributes["format"] == "PRECOMPUTED" + assert attributes["observeFullEvaluationData"] is False + assert attributes["obfuscated"] is (format_ == "encoded") + flags = attributes["flags"] + if format_ == "encoded": + encoding = attributes["obfuscation"] + assert encoding["scheme"] == "flag-key-sha256-v1" + salt = bytes.fromhex(encoding["salt"]) + assert len(salt) == 16 + assert set(flags) == { + hashlib.sha256(b"datadog.feature-flags.flag-key.v1\0" + salt + key.encode()).hexdigest() + for key in ("test-flag", "prerequisite") + } + else: + assert set(flags) == {"test-flag", "prerequisite"} + mismatch = result["results"][1] + assert mismatch["value"] is False + assert mismatch["reason"] == "ERROR" + assert mismatch["errorCode"] == "INVALID_CONTEXT" + assert "private-token" not in json.dumps(result) + + def test_malformed_configuration_codecs( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + cases = [ + ("private-invalid-json", "configurationError"), + (json.dumps({"version": 999}), "configurationError"), + (json.dumps({"version": 1}), None), + (json.dumps({"version": 1, "rules": {"response": "!private-invalid-protobuf!"}}), "rulesError"), + (json.dumps({"version": 1, "precomputed": {"response": "private-invalid-json"}}), "precomputedError"), + (json.dumps({"version": 2, "precomputed": {"response": "{}"}}), "precomputedError"), + ] + with test_library: + result = test_library.ffe_core_provider( + { + "operation": "invalid-codec", + "wire": WIRE, + "contexts": CONTEXTS, + "invalidWires": [wire for wire, _ in cases], + } + ) + assert_offline(result, mocked_backend) + assert len(result["rejected"]) == len(cases) + for rejected, (_, diagnostic) in zip(result["rejected"], cases, strict=True): + assert rejected["errorName"] == "TypeError" + assert rejected["unchanged"] is True + assert rejected["diagnostics"] == { + key: key == diagnostic for key in ("configurationError", "rulesError", "precomputedError") + } + assert_evaluation(rejected["result"], value=True, variant="on", reason="TARGETING_MATCH") + assert "private-invalid" not in json.dumps(result) + def test_synchronous_bootstrap(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: with test_library: result = test_library.ffe_core_provider({"operation": "bootstrap", "wire": WIRE, "contexts": CONTEXTS}) diff --git a/utils/build/docker/nodejs/parametric/ffe-core-provider.js b/utils/build/docker/nodejs/parametric/ffe-core-provider.js index a20fc32b610..71245c4560f 100644 --- a/utils/build/docker/nodejs/parametric/ffe-core-provider.js +++ b/utils/build/docker/nodejs/parametric/ffe-core-provider.js @@ -5,7 +5,7 @@ const { writeFileSync } = require('node:fs') const { createRequire } = require('node:module') async function main () { - const { operation, wire, replacementWire, contexts, fetchOptions } = JSON.parse(process.argv[2]) + const { operation, wire, replacementWire, contexts, fetchOptions, format, clientFingerprint, invalidWires } = JSON.parse(process.argv[2]) let httpRequests = 0 let exposureEvents = 0 let outcome @@ -26,7 +26,8 @@ async function main () { configurationToString, createExposureTracking, DatadogCoreProvider, - fetchRulesConfiguration + fetchRulesConfiguration, + precomputeConfiguration } = requireLibrary('@datadog/openfeature-node-server/rules-based') const { OpenFeature, ProviderEvents } = require('@openfeature/server-sdk') OpenFeature.setLogger({ error () {}, warn () {}, info () {}, debug () {} }) @@ -37,7 +38,14 @@ async function main () { const sink = channel('ffe:exposure:submit') const captureExposure = event => exposures.push(event) sink.subscribe(captureExposure) - const provider = new DatadogCoreProvider(configurationFromString(wire), { ...tracking?.providerOptions }) + let configuration = configurationFromString(wire) + let serialized + if (operation === 'roundtrip') { + if (format !== 'rules') configuration = precomputeConfiguration(configuration, contexts[0], { clientFingerprint }) + serialized = configurationToString(configuration) + configuration = configurationFromString(serialized) + } + const provider = new DatadogCoreProvider(configuration, { ...tracking?.providerOptions }) if (operation === 'overlap') provider.hooks.push(tracking.createHook(sink)) let readyEvents = 0 OpenFeature.addHandler(ProviderEvents.Ready, () => { readyEvents++ }) @@ -47,7 +55,35 @@ async function main () { const evaluate = (context, options) => client.getBooleanDetails('test-flag', false, context, options) try { - if (operation === 'bootstrap') { + if (operation === 'roundtrip') { + outcome = { + startup, + serialized, + restored: configurationToString(provider.getConfiguration()), + results: await Promise.all(contexts.map(context => evaluate(context))) + } + } else if (operation === 'invalid-codec') { + const snapshot = configurationToString(provider.getConfiguration()) + const rejected = [] + for (const input of invalidWires) { + const invalid = configurationFromString(input) + let errorName + try { + provider.setConfiguration(invalid) + } catch (error) { + if (!(error instanceof TypeError)) throw error + errorName = error.name + } + rejected.push({ + errorName, + diagnostics: Object.fromEntries(['configurationError', 'rulesError', 'precomputedError'] + .map(key => [key, typeof invalid[key] === 'string'])), + unchanged: configurationToString(provider.getConfiguration()) === snapshot, + result: await evaluate(contexts[0]) + }) + } + outcome = { startup, rejected } + } else if (operation === 'bootstrap') { outcome = { startup, results: await Promise.all(contexts.map(context => evaluate(context))) } } else if (operation === 'overlap') { const observations = [] From 1404bdce4d515f6f6a1fe74ef94de068d56c7521 Mon Sep 17 00:00:00 2001 From: Sameeran Kunche Date: Fri, 20 Nov 2026 15:39:23 -0800 Subject: [PATCH 3/3] test(ffe): validate the shipped provider bundle and cache generations Load the vendored rules-based bundle instead of a development dependency. Cover generation-aware exposure deduplication, preserve overlap failure diagnostics, and clarify codec, activation, and bundle validation contracts. --- docs/understand/weblogs/parametric_weblog.md | 14 +++++--- manifests/nodejs.yml | 2 +- tests/ffe/README.md | 13 ++++--- .../parametric/test_ffe/test_core_provider.py | 31 +++++++++++++--- .../nodejs/parametric/ffe-core-provider.js | 36 +++++++++++++++---- 5 files changed, 74 insertions(+), 22 deletions(-) diff --git a/docs/understand/weblogs/parametric_weblog.md b/docs/understand/weblogs/parametric_weblog.md index bed0d8a8ca3..db8d0767c8a 100644 --- a/docs/understand/weblogs/parametric_weblog.md +++ b/docs/understand/weblogs/parametric_weblog.md @@ -998,20 +998,24 @@ and `exposureHooks` when requested. #### `POST /ffe/core-provider` Called by `ParametricTestClientApi.ffe_core_provider()`. Node.js-only fresh-process -portable-provider probe; it resolves the built `@datadog/openfeature-node-server/rules-based` -package shipped inside `dd-trace`, without importing or initializing the tracer. +portable-provider probe; it loads the `@datadog/openfeature-node-server/rules-based` +bundle that `dd-trace` ships under `vendor/dist`, without importing or initializing +the tracer. It does not require a separately installed Node provider package or +public tracer wrapper exports. The request contains `operation` (`bootstrap`, `overlap`, `refresh`, `tracking`, `roundtrip`, or `invalid-codec`), portable `wire`, and an array of evaluation `contexts`. `refresh` additionally takes `replacementWire` and server-channel `fetchOptions`. The custom Fetch transport uses `SYSTEM_TESTS_FFE_RULES_BASE_URL`, as for the standalone rules helper. -`roundtrip` accepts `format` (`rules`, `precomputed`, or `encoded`) and an optional -`clientFingerprint`; it returns the serialized/restored snapshots and evaluations. +For `roundtrip`, `format: "rules"` retains the rules snapshot; any other value +precomputes it for `contexts[0]`. Hashed (version 2) keys require a `clientFingerprint` +advertising `assignment-encoding-flag-key-256-v1`; `format: "encoded"` alone does +not select key encoding. The response includes serialized/restored snapshots and evaluations. `invalid-codec` accepts `invalidWires` and returns codec diagnostic categories, replacement errors, and evaluations from the retained configuration. The response reports actual OpenFeature startup/final status, operation results, -configuration-change notifications or explicit sink records, package/runtime +configuration-change notifications or explicit sink records, tracer/runtime versions, and HTTP/exposure-channel counts observed until child-process exit. An unexpected failure, process timeout, or invalid child output returns HTTP 500. The parent strips `NODE_OPTIONS` and imposes a 10-second deadline. diff --git a/manifests/nodejs.yml b/manifests/nodejs.yml index 71f082dfee6..f14c8eeb9bf 100644 --- a/manifests/nodejs.yml +++ b/manifests/nodejs.yml @@ -2749,7 +2749,7 @@ manifest: : # TODO: a lower version might be supported - declaration: missing_feature (Requires a release containing dd-trace-js#11111) component_version: <6.25.0 - tests/parametric/test_ffe/test_core_provider.py: missing_feature (Awaiting the DatadogCoreProvider package dependency update; validate a containing build locally) + tests/parametric/test_ffe/test_core_provider.py: 'missing_feature (Requires a dd-trace-js release whose vendored openfeature-node-server bundle contains DatadogCoreProvider, openfeature-js-client#469)' tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Dependent_Flags_RC: missing_feature (Dependent flag support must be enabled with the SDK release) tests/parametric/test_ffe/test_dependent_flags_rc.py::Test_FFE_Without_Dependent_Flags_RC: irrelevant (Requires a known legacy build without dependent flag support) tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Dynamic_Evaluation: *ref_5_75_0 diff --git a/tests/ffe/README.md b/tests/ffe/README.md index 2e075d74e60..4402362b126 100644 --- a/tests/ffe/README.md +++ b/tests/ffe/README.md @@ -70,13 +70,16 @@ These tests report to [Offline initialization and portable configuration helpers synchronous READY registration, zero-request local evaluation, overlapping contexts with different root/dependency values, explicit server-channel refresh, rejected replacement retention, configuration-change events, and opt-in exposure sinks with -deduplication and late-hook rollback. +deduplication, a hook attached after startup, rollback when a later application +hook fails, and cache retention/reset for unchanged/changed configuration generations. It also covers semantic codec round-trips for rules and plaintext/hashed precomputed snapshots, metadata and context binding, and malformed/versioned input rejection. -These are package-level integration checks, not tracer evaluation-upload or intake-delivery tests. The adapter resolves the -Node package from the tracer's dependencies without importing the tracer; no -`dd-trace` wrapper exports are required. The Node manifest remains `missing_feature` -until a containing dependency update is available; other libraries are gated too. +These are bundled-SDK integration checks, not tracer evaluation-upload or intake-delivery tests. +The adapter loads the provider bundle that `dd-trace` ships under +`vendor/dist/@datadog/openfeature-node-server/rules-based`, without importing the +tracer; no public `dd-trace` wrapper exports are required. The Node manifest remains +`missing_feature` until a tracer release contains that provider in its vendor bundle; +other libraries are gated too. With a custom containing Node build, select this file and force it with `-F`: ```sh diff --git a/tests/parametric/test_ffe/test_core_provider.py b/tests/parametric/test_ffe/test_core_provider.py index 197639ff5d4..58782872659 100644 --- a/tests/parametric/test_ffe/test_core_provider.py +++ b/tests/parametric/test_ffe/test_core_provider.py @@ -33,8 +33,8 @@ def library_env(mocked_backend: MockedBackendServer) -> dict[str, str]: def assert_evaluation(result: dict[str, Any], *, value: bool, variant: str, reason: str) -> None: assert result["value"] is value, result - assert result["variant"] == variant, result assert result["reason"] == reason, result + assert result.get("variant") == variant, result assert result.get("errorCode") is None, result @@ -118,7 +118,28 @@ def test_malformed_configuration_codecs( (json.dumps({"version": 1}), None), (json.dumps({"version": 1, "rules": {"response": "!private-invalid-protobuf!"}}), "rulesError"), (json.dumps({"version": 1, "precomputed": {"response": "private-invalid-json"}}), "precomputedError"), - (json.dumps({"version": 2, "precomputed": {"response": "{}"}}), "precomputedError"), + ( + json.dumps( + { + "version": 2, + "precomputed": { + "response": json.dumps( + { + "data": { + "attributes": { + "createdAt": "2026-11-19T00:00:00Z", + "format": "PRECOMPUTED", + "flags": {}, + "obfuscated": True, + } + } + } + ) + }, + } + ), + "precomputedError", + ), ] with test_library: result = test_library.ffe_core_provider( @@ -236,7 +257,7 @@ def test_opt_in_exposure_tracking(self, test_library: APMLibrary, mocked_backend with test_library: result = test_library.ffe_core_provider({"operation": "tracking", "wire": WIRE, "contexts": CONTEXTS}) - assert_offline(result, mocked_backend, exposure_events=6) + assert_offline(result, mocked_backend, exposure_events=8) assert result["startup"]["hooks"] == 0 assert result["beforeHook"] == 0 assert result["deduplicated"] == 2 @@ -245,8 +266,10 @@ def test_opt_in_exposure_tracking(self, test_library: APMLibrary, mocked_backend assert result["afterFailure"] == 2 assert result["afterRetry"] == 4 assert result["afterClose"] == 4 # The tracking helper owns this cache, not the provider. + assert result["afterSameGeneration"] == 4 + assert result["afterNewGeneration"] == 6 exposures = result["exposures"] - assert len(exposures) == 6 + assert len(exposures) == 8 assert {(item["subject"]["id"], item["flag"]["key"], item["variant"]["key"]) for item in exposures[:4]} == { (context["targetingKey"], flag, "on" if context["country"] == "US" else "off") for context in CONTEXTS diff --git a/utils/build/docker/nodejs/parametric/ffe-core-provider.js b/utils/build/docker/nodejs/parametric/ffe-core-provider.js index 71245c4560f..d475738a4f1 100644 --- a/utils/build/docker/nodejs/parametric/ffe-core-provider.js +++ b/utils/build/docker/nodejs/parametric/ffe-core-provider.js @@ -18,7 +18,7 @@ async function main () { ] for (const [name, listener] of subscriptions) channel(name).subscribe(listener) - // Resolve the tracer's packaged dependency without loading or initializing the tracer. + // Load the bundle shipped by the tracer, without importing or initializing the tracer. const requireLibrary = createRequire(require.resolve('dd-trace/package.json')) const { ConfigurationFetchError, @@ -28,7 +28,7 @@ async function main () { DatadogCoreProvider, fetchRulesConfiguration, precomputeConfiguration - } = requireLibrary('@datadog/openfeature-node-server/rules-based') + } = requireLibrary('./vendor/dist/@datadog/openfeature-node-server/rules-based') const { OpenFeature, ProviderEvents } = require('@openfeature/server-sdk') OpenFeature.setLogger({ error () {}, warn () {}, info () {}, debug () {} }) const tracking = ['tracking', 'overlap'].includes(operation) @@ -90,10 +90,13 @@ async function main () { let arrivals = 0 let release const barrier = new Promise(resolve => { release = resolve }) + const arrive = async () => { + if (++arrivals === contexts.length) release() + await barrier + } client.addHooks({ after: async (hookContext, details) => { - if (++arrivals === contexts.length) release() - await barrier + await arrive() const sidecar = tracking.providerOptions.dependencyTelemetrySidecar const dependencies = sidecar.takeDependencyEvaluations(undefined, undefined, hookContext.context) observations.push({ @@ -102,7 +105,8 @@ async function main () { dependencies: dependencies.map(item => ({ flag: item.flagKey, value: item.details.value })), consumed: sidecar.takeDependencyEvaluations(details.flagMetadata, undefined, hookContext.context) }) - } + }, + error: arrive }) outcome = { startup, results: await Promise.all(contexts.map(context => evaluate(context))), observations, exposures } } else if (operation === 'refresh') { @@ -175,16 +179,24 @@ async function main () { client = OpenFeature.getClient('offline-provider') await evaluate(contexts[0]) const afterClose = exposures.length + restarted.setConfiguration(restarted.getConfiguration()) + await evaluate(contexts[0]) + const afterSameGeneration = exposures.length + const nextGeneration = restarted.getConfiguration() + nextGeneration.rules.response.createdAt.seconds += 1n + restarted.setConfiguration(nextGeneration) + await evaluate(contexts[0]) + const afterNewGeneration = exposures.length tracking.clear() await evaluate(contexts[0]) - outcome = { startup, beforeHook, deduplicated, failed, afterFailure, afterRetry, afterClose, exposures } + outcome = { startup, beforeHook, deduplicated, failed, afterFailure, afterRetry, afterClose, afterSameGeneration, afterNewGeneration, exposures } } else { throw new Error(`Unknown provider operation: ${operation}`) } outcome.status = client.providerStatus outcome.versions = { node: process.version, - provider: requireLibrary('@datadog/openfeature-node-server/package.json').version + tracer: requireLibrary('./package.json').version } } finally { await OpenFeature.clearProviders() @@ -198,7 +210,17 @@ async function main () { } } +let settled = false +process.once('beforeExit', () => { + if (!settled) { + console.error('Standalone FFE provider operation did not settle') + process.exitCode = 1 + } +}) + main().catch(error => { console.error(error) process.exitCode = 1 +}).finally(() => { + settled = true })