Skip to content

Commit bc40e89

Browse files
hhan2024Codex GPT-6
andcommitted
feat(ffe): support dependent flag evaluations on the shared engine
Carry prerequisite evaluation observations and successful-path exposure candidates through the native bridge. Commit OpenFeature exposures only after application hooks succeed, preserving the current runtime lifecycle. Environment: Datadog workspace Co-Authored-By: Codex GPT-6 <noreply@localhost>
1 parent 62fea42 commit bc40e89

18 files changed

Lines changed: 967 additions & 35 deletions

‎components-rs/common.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,8 @@ typedef struct ddog_FfeAttribute {
618618
bool bool_value;
619619
} ddog_FfeAttribute;
620620

621+
typedef void (*ddog_FfeDependencyCallback)(void*, ddog_CharSlice, struct ddog_FfeResult, bool);
622+
621623
/**
622624
* Flags selecting which Remote Config products/capabilities to subscribe to.
623625
*

‎components-rs/datadog.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,14 @@ struct ddog_FfeResult ddog_ffe_evaluate(ddog_CharSlice flag_key,
300300
const struct ddog_FfeAttribute *attributes,
301301
uintptr_t attributes_count);
302302

303+
struct ddog_FfeResult ddog_ffe_evaluate_with_dependencies(ddog_CharSlice flag_key,
304+
int32_t expected_type,
305+
ddog_CharSlice targeting_key,
306+
const struct ddog_FfeAttribute *attributes,
307+
uintptr_t attributes_count,
308+
ddog_FfeDependencyCallback callback,
309+
void *callback_context);
310+
303311
void ddog_init_remote_config(struct ddog_RemoteConfigFlags flags);
304312

305313
struct ddog_RemoteConfigState *ddog_init_remote_config_state(const struct ddog_Endpoint *endpoint,

‎components-rs/tracer_runtime/ffe.rs‎

Lines changed: 197 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,54 @@ pub extern "C" fn ddog_ffe_evaluate(
338338
targeting_key: CharSlice<'_>,
339339
attributes: *const FfeAttribute<'_>,
340340
attributes_count: usize,
341+
) -> FfeResult {
342+
evaluate_with_dependencies(
343+
flag_key,
344+
expected_type,
345+
targeting_key,
346+
attributes,
347+
attributes_count,
348+
None,
349+
std::ptr::null_mut(),
350+
)
351+
}
352+
353+
pub fn supports_dependent_flags() -> bool {
354+
true
355+
}
356+
357+
pub type FfeDependencyCallback =
358+
extern "C" fn(*mut std::ffi::c_void, CharSlice<'_>, FfeResult, bool);
359+
360+
#[no_mangle]
361+
pub extern "C" fn ddog_ffe_evaluate_with_dependencies(
362+
flag_key: CharSlice<'_>,
363+
expected_type: i32,
364+
targeting_key: CharSlice<'_>,
365+
attributes: *const FfeAttribute<'_>,
366+
attributes_count: usize,
367+
callback: FfeDependencyCallback,
368+
callback_context: *mut std::ffi::c_void,
369+
) -> FfeResult {
370+
evaluate_with_dependencies(
371+
flag_key,
372+
expected_type,
373+
targeting_key,
374+
attributes,
375+
attributes_count,
376+
Some(callback),
377+
callback_context,
378+
)
379+
}
380+
381+
fn evaluate_with_dependencies(
382+
flag_key: CharSlice<'_>,
383+
expected_type: i32,
384+
targeting_key: CharSlice<'_>,
385+
attributes: *const FfeAttribute<'_>,
386+
attributes_count: usize,
387+
callback: Option<FfeDependencyCallback>,
388+
callback_context: *mut std::ffi::c_void,
341389
) -> FfeResult {
342390
if flag_key.as_raw_parts().0.is_null() {
343391
return invalid_result();
@@ -370,15 +418,13 @@ pub extern "C" fn ddog_ffe_evaluate(
370418
let context = EvaluationContext::new(targeting_key, Arc::new(attributes));
371419
let expects_object = matches!(expected_type, ExpectedFlagType::Object);
372420

373-
FFE_STATE.with(|state| {
421+
let (result, evaluations) = FFE_STATE.with(|state| {
374422
let state = state.borrow();
375-
let assignment = ffe::get_assignment(
376-
state.config.as_ref(),
377-
flag_key,
378-
&context,
379-
expected_type,
380-
ffe::now(),
381-
);
423+
let evaluation = match state.config.as_ref() {
424+
Some(config) => config.eval_flag_with_trace(flag_key, &context, expected_type, ffe::now(), ffe::EvaluationOptions::default()),
425+
None => ffe::EvaluationResult::from_error(EvaluationError::ConfigurationMissing),
426+
};
427+
let assignment = evaluation.result;
382428
if let Err(error) = &assignment {
383429
debug!("Feature Flags: native resolution failed (flagKey={flag_key:?}, configVersion={}): {error}", state.version);
384430
}
@@ -402,8 +448,30 @@ pub extern "C" fn ddog_ffe_evaluate(
402448
.config
403449
.as_ref()
404450
.is_some_and(Configuration::observe_full_evaluation_data);
405-
result
406-
})
451+
(result, evaluation.evaluations)
452+
});
453+
// Release the configuration borrow before calling into Zend; callbacks may reenter.
454+
if let Some(callback) = callback {
455+
for record in evaluations {
456+
let mut dependency = match record.result {
457+
Err(EvaluationError::FlagDisabled | EvaluationError::DefaultAllocationNull) => {
458+
error_result(ERROR_GENERAL, REASON_ERROR)
459+
}
460+
assignment => result_from_assignment(assignment),
461+
};
462+
dependency.observe_full_evaluation_data = result.observe_full_evaluation_data;
463+
let eligible = record.exposure_eligible
464+
&& result.error_code == ERROR_NONE
465+
&& result.variant.is_some();
466+
callback(
467+
callback_context,
468+
CharSlice::from(record.flag_key.as_str()),
469+
dependency,
470+
eligible,
471+
);
472+
}
473+
}
474+
result
407475
}
408476

409477
fn is_json_container(value: &AssignmentValue) -> bool {
@@ -696,6 +764,125 @@ mod tests {
696764
}
697765
}"#;
698766

767+
extern "C" fn collect_dependency(
768+
context: *mut std::ffi::c_void,
769+
key: CharSlice<'_>,
770+
result: FfeResult,
771+
eligible: bool,
772+
) {
773+
// SAFETY: tests pass an exclusive pointer to this vector for the synchronous call.
774+
let results = unsafe { &mut *context.cast::<Vec<(String, FfeResult, bool)>>() };
775+
results.push((key.try_to_utf8().unwrap().to_owned(), result, eligible));
776+
}
777+
778+
#[test]
779+
fn prerequisite_callbacks_keep_failed_and_rejected_evaluations() {
780+
setup_zend_string_functions();
781+
let wire = include_str!("../../tests/ext/ffe/dependent_flags.json");
782+
let json = CString::new(wire).unwrap();
783+
assert!(ddog_ffe_load_config(char_slice(&json)));
784+
for (key, expected_error, prerequisite, eligible) in [
785+
("root", ERROR_NONE, "parent", true),
786+
("rejected", ERROR_NONE, "parent", false),
787+
("missing", ERROR_GENERAL, "absent", false),
788+
("requires-disabled", ERROR_GENERAL, "disabled", false),
789+
] {
790+
let mut records: Vec<(String, FfeResult, bool)> = Vec::new();
791+
let result = ddog_ffe_evaluate_with_dependencies(
792+
CharSlice::from(key),
793+
TYPE_BOOLEAN,
794+
CharSlice::from("subject"),
795+
std::ptr::null(),
796+
0,
797+
collect_dependency,
798+
std::ptr::from_mut(&mut records).cast(),
799+
);
800+
assert_eq!(result.error_code, expected_error, "{key}");
801+
assert_eq!(
802+
records.len(),
803+
1,
804+
"{key}: memoization must not duplicate records"
805+
);
806+
assert_eq!(records[0].0, prerequisite);
807+
assert_eq!(records[0].2, eligible);
808+
assert!(!records[0].1.observe_full_evaluation_data);
809+
}
810+
clear_config();
811+
}
812+
813+
#[test]
814+
fn disabled_and_unassigned_prerequisites_are_errors_but_direct_results_are_not() {
815+
setup_zend_string_functions();
816+
let wire: serde_json::Value =
817+
serde_json::from_str(include_str!("../../tests/ext/ffe/dependent_flags.json")).unwrap();
818+
for (enabled, direct_reason) in [(false, REASON_DISABLED), (true, REASON_DEFAULT)] {
819+
let mut config = wire.clone();
820+
config["flags"]["parent"]["enabled"] = enabled.into();
821+
if enabled {
822+
config["flags"]["parent"]["allocations"] = serde_json::json!([]);
823+
}
824+
let json = CString::new(config.to_string()).unwrap();
825+
assert!(ddog_ffe_load_config(char_slice(&json)));
826+
let mut records: Vec<(String, FfeResult, bool)> = Vec::new();
827+
let result = ddog_ffe_evaluate_with_dependencies(
828+
CharSlice::from("root"),
829+
TYPE_BOOLEAN,
830+
CharSlice::from("subject"),
831+
std::ptr::null(),
832+
0,
833+
collect_dependency,
834+
std::ptr::from_mut(&mut records).cast(),
835+
);
836+
assert_eq!(result.error_code, ERROR_GENERAL);
837+
assert_eq!(records.len(), 1);
838+
assert_eq!(records[0].0, "parent");
839+
assert_eq!(records[0].1.error_code, ERROR_GENERAL);
840+
assert_eq!(records[0].1.reason, REASON_ERROR);
841+
assert!(records[0].1.variant.is_none());
842+
assert!(!records[0].2);
843+
844+
let direct = ddog_ffe_evaluate(
845+
CharSlice::from("parent"),
846+
TYPE_BOOLEAN,
847+
CharSlice::from("subject"),
848+
std::ptr::null(),
849+
0,
850+
);
851+
assert_eq!(direct.error_code, ERROR_NONE);
852+
assert_eq!(direct.reason, direct_reason);
853+
assert!(direct.variant.is_none());
854+
}
855+
clear_config();
856+
}
857+
858+
#[test]
859+
fn scalar_json_root_suppresses_prerequisite_exposures() {
860+
setup_zend_string_functions();
861+
let mut wire: serde_json::Value =
862+
serde_json::from_str(include_str!("../../tests/ext/ffe/dependent_flags.json")).unwrap();
863+
wire["observeFullEvaluationData"] = true.into();
864+
wire["flags"]["root"]["variationType"] = "JSON".into();
865+
wire["flags"]["root"]["variations"] = serde_json::json!({"on":{"key":"on","value":42}});
866+
let json = CString::new(wire.to_string()).unwrap();
867+
assert!(ddog_ffe_load_config(char_slice(&json)));
868+
let mut records: Vec<(String, FfeResult, bool)> = Vec::new();
869+
let result = ddog_ffe_evaluate_with_dependencies(
870+
CharSlice::from("root"),
871+
TYPE_OBJECT,
872+
CharSlice::from("subject"),
873+
std::ptr::null(),
874+
0,
875+
collect_dependency,
876+
std::ptr::from_mut(&mut records).cast(),
877+
);
878+
assert_eq!(result.error_code, ERROR_TYPE_MISMATCH);
879+
assert_eq!(records.len(), 1);
880+
assert!(!records[0].2);
881+
assert!(records[0].1.observe_full_evaluation_data);
882+
assert!(supports_dependent_flags());
883+
clear_config();
884+
}
885+
699886
#[test]
700887
fn empty_targeting_key_is_not_dropped() {
701888
setup_zend_string_functions();

‎components-rs/tracer_runtime/remote_config.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ pub unsafe extern "C" fn ddog_init_remote_config(flags: RemoteConfigFlags) {
173173
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::FfeFlags);
174174
DATADOG_REMOTE_CONFIG_CAPABILITIES
175175
.push(RemoteConfigCapabilities::FfeFlagConfigurationRules);
176+
if crate::ffe::supports_dependent_flags() {
177+
DATADOG_REMOTE_CONFIG_CAPABILITIES
178+
.push(RemoteConfigCapabilities::FfeFlagDependentFlagVariantKeyV1);
179+
}
176180
}
177181

178182
if live_debugging_enabled {

‎src/DDTrace/OpenFeature/DataDogProvider.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ public function __construct(?LoggerInterface $logger = null)
5555
} else {
5656
NativeEvaluator::submitFlagEvaluation($observation);
5757
}
58+
}, function (array $batch): void {
59+
$recorder = $this->observationScope()->recorder;
60+
if ($recorder !== null) {
61+
$recorder->captureExposures($batch);
62+
} else {
63+
NativeEvaluator::submitExposures($batch);
64+
}
5865
});
5966
$this->datadogLogger = new NonThrowingLogger($logger ?: GlobalLogger::get());
6067
$this->metricRecorder = EvaluationMetricRecorder::createDefault();

‎src/DDTrace/OpenFeature/FlagEvaluationHook.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ final class FlagEvaluationHook implements Hook
1818
private object $scope;
1919
private ?self $previous = null;
2020
private ?array $observation = null;
21+
private ?array $exposures = null;
2122
private int $startedAtMs;
2223

2324
public function __construct(object $scope)
@@ -53,6 +54,11 @@ public function capture(array $observation): void
5354
$this->observation = $observation;
5455
}
5556

57+
public function captureExposures(array $batch): void
58+
{
59+
$this->exposures = $batch;
60+
}
61+
5662
public function after(HookContext $context, ResolutionDetails $details, HookHints $hints): void
5763
{
5864
if ($this->observation === null) {
@@ -68,6 +74,7 @@ public function after(HookContext $context, ResolutionDetails $details, HookHint
6874

6975
public function error(HookContext $context, \Throwable $error, HookHints $hints): void
7076
{
77+
$this->exposures = null;
7178
$this->observation = $this->observation ?? $this->protectedObservation($context);
7279
// Before/after failures replace the SDK result with the caller default.
7380
// Keep evaluated consent/time, but not the successful variant/allocation.
@@ -81,12 +88,16 @@ public function error(HookContext $context, \Throwable $error, HookHints $hints)
8188
public function finally(HookContext $context, HookHints $hints): void
8289
{
8390
try {
91+
if ($this->exposures !== null) {
92+
NativeEvaluator::submitExposures($this->exposures);
93+
}
8494
if ($this->observation !== null) {
8595
NativeEvaluator::submitFlagEvaluation($this->observation);
8696
}
8797
} finally {
8898
$this->claim();
8999
$this->observation = null;
100+
$this->exposures = null;
90101
}
91102
}
92103

0 commit comments

Comments
 (0)