Skip to content

Commit 775da0a

Browse files
committed
fix(ffe): record terminal OpenFeature evaluation metrics
1 parent 85f8fda commit 775da0a

4 files changed

Lines changed: 102 additions & 16 deletions

File tree

‎src/DDTrace/OpenFeature/DataDogProvider.php‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,11 @@ public function getHooks(): array
126126
{
127127
// The SDK asks once per invocation. A fresh hook keeps finalization
128128
// state separate even when a before hook fails before ours runs.
129-
return array_merge(parent::getHooks(), [new FlagEvaluationHook($this->observationScope(), $this->exposureRecorder)]);
129+
return array_merge(parent::getHooks(), [new FlagEvaluationHook(
130+
$this->observationScope(),
131+
$this->exposureRecorder,
132+
$this->metricRecorder
133+
)]);
130134
}
131135

132136
private function observationScope(): object
@@ -245,9 +249,8 @@ private function resolveWithObservation(
245249
$details
246250
);
247251
$this->warnIfRuntimeNotReady($details);
248-
// The PHP OpenFeature SDK does not pass ResolutionDetails to finally
249-
// hooks, so PHP records metrics here after native evaluation has the
250-
// final provider result.
252+
// Stage the provider result until application hooks finish. Direct
253+
// provider calls have no SDK lifecycle and record immediately.
251254
$this->recordEvaluationMetric($flagKey, $details);
252255
// APM span enrichment is recorded inside NativeEvaluator::evaluate()
253256
// (the shared choke point), so there is nothing to do here.
@@ -335,13 +338,19 @@ private function openFeatureMetadata(EvaluationDetails $details): array
335338

336339
private function recordEvaluationMetric(string $flagKey, EvaluationDetails $details): void
337340
{
338-
$this->metricRecorder->record(EvaluationMetric::create(
341+
$metric = EvaluationMetric::create(
339342
$flagKey,
340343
$details->getVariant(),
341344
$details->getReason(),
342345
$details->getErrorCode(),
343346
$this->allocationKey($details)
344-
));
347+
);
348+
$observation = $this->observationScope()->recorder;
349+
if ($observation !== null) {
350+
$observation->captureMetric($metric);
351+
} else {
352+
$this->metricRecorder->record($metric);
353+
}
345354
}
346355

347356
private function allocationKey(EvaluationDetails $details): ?string

‎src/DDTrace/OpenFeature/FlagEvaluationHook.php‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
namespace DDTrace\OpenFeature;
66

7+
use DDTrace\FeatureFlags\EvaluationReason;
8+
use DDTrace\FeatureFlags\Internal\Metric\EvaluationMetric;
9+
use DDTrace\FeatureFlags\Internal\Metric\EvaluationMetricRecorder;
710
use DDTrace\FeatureFlags\Internal\NativeEvaluator;
811
use OpenFeature\interfaces\flags\EvaluationContext;
912
use OpenFeature\interfaces\hooks\Hook;
@@ -18,6 +21,8 @@ final class FlagEvaluationHook implements Hook
1821
private object $scope;
1922
/** @var callable|null */
2023
private $exposureRecorder;
24+
private ?EvaluationMetricRecorder $metricRecorder;
25+
private ?EvaluationMetric $metric = null;
2126
private ?self $previous = null;
2227
private ?array $observation = null;
2328
private ?array $exposure = null;
@@ -26,10 +31,14 @@ final class FlagEvaluationHook implements Hook
2631
private int $startedAtMs;
2732
private static ?\WeakMap $exposureEvaluations = null;
2833

29-
public function __construct(object $scope, ?callable $exposureRecorder = null)
30-
{
34+
public function __construct(
35+
object $scope,
36+
?callable $exposureRecorder = null,
37+
?EvaluationMetricRecorder $metricRecorder = null
38+
) {
3139
$this->scope = $scope;
3240
$this->exposureRecorder = $exposureRecorder;
41+
$this->metricRecorder = $metricRecorder;
3342
$this->startedAtMs = (int) (microtime(true) * 1000);
3443
}
3544

@@ -60,6 +69,11 @@ public function capture(array $observation): void
6069
$this->observation = $observation;
6170
}
6271

72+
public function captureMetric(EvaluationMetric $metric): void
73+
{
74+
$this->metric = $metric;
75+
}
76+
6377
public function captureExposures(array $exposures): void
6478
{
6579
$this->exposures = $exposures;
@@ -104,12 +118,24 @@ public function error(HookContext $context, \Throwable $error, HookHints $hints)
104118
? $error->getResolutionError()->getResolutionErrorCode()->getValue() : 'GENERAL';
105119
$this->observation[6] = true;
106120
$this->observation[10] = [];
121+
$this->metric = EvaluationMetric::create(
122+
$context->getFlagKey(),
123+
null,
124+
EvaluationReason::ERROR,
125+
$this->observation[5],
126+
null
127+
);
107128
$this->successful = false;
108129
}
109130

110131
public function finally(HookContext $context, HookHints $hints): void
111132
{
112133
try {
134+
// Unlike after, finally runs after every application after hook.
135+
// error() replaces a staged success if the SDK returns a default.
136+
if ($this->metric !== null && $this->metricRecorder !== null) {
137+
$this->metricRecorder->record($this->metric);
138+
}
113139
if ($this->successful && $this->exposures !== null && $this->exposureRecorder !== null) {
114140
NativeEvaluator::submitExposures($this->exposures, $this->exposureRecorder);
115141
}
@@ -120,6 +146,7 @@ public function finally(HookContext $context, HookHints $hints): void
120146
} finally {
121147
$this->claim();
122148
$this->observation = null;
149+
$this->metric = null;
123150
$this->exposure = null;
124151
$this->exposures = null;
125152
$this->successful = false;

‎tests/OpenFeature/OpenFeatureEvaluationMetricsTest.php‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818

1919
/**
2020
* Verifies the PHP 8 OpenFeature path records `feature_flag.evaluations` from
21-
* provider-owned EvaluationDetails. Native metric recording is disabled for the
22-
* OpenFeature evaluator path, so the provider records exactly once per evaluation.
21+
* the terminal SDK outcome. Native root metric recording is disabled for the
22+
* OpenFeature evaluator path, so the invocation hook records the root once.
2323
*/
2424
final class OpenFeatureEvaluationMetricsTest extends TestCase
2525
{
@@ -59,8 +59,8 @@ public function testRecordsMetricThroughProviderOnTypeMismatch(): void
5959
{
6060
$recorder = new EvalMetricsRecordingRecorder();
6161
$evaluator = new OpenFeatureMetricEvaluator();
62-
// Provider resolves a type mismatch before returning to the OpenFeature
63-
// SDK, so no separate PHP OpenFeature hook is needed for this case.
62+
// The provider resolves the type mismatch before returning to the SDK;
63+
// its error code must survive terminal metric recording.
6464
$evaluator->setSuccess('flag.mismatch', 'not-an-int', EvaluationReason::STATIC_REASON);
6565

6666
$provider = DataDogProvider::createWithDependencies(

‎tests/OpenFeature/dependent_exposures_final_outcome.phpt‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
--TEST--
2-
FFE OpenFeature commits prerequisite exposures only after all hooks succeed
2+
FFE OpenFeature finalizes root metrics and prerequisite exposures after hooks
33
--SKIPIF--
44
<?php
55
if (PHP_VERSION_ID < 80100) die('skip: fibers require PHP 8.1+');
@@ -42,7 +42,13 @@ $committed = [];
4242
DDTrace\install_hook('DDTrace\\Internal\\record_ffe_exposure', function ($hook) use (&$committed) {
4343
$committed[] = $hook->args;
4444
});
45-
$provider = new DDTrace\OpenFeature\DataDogProvider();
45+
$metrics = [];
46+
$provider = DDTrace\OpenFeature\DataDogProvider::createWithDependencies(null, null,
47+
function ($metric) use (&$metrics) {
48+
$metrics[] = [$metric->getFlagKey(), $metric->getVariant(), $metric->getReason(),
49+
$metric->getErrorCode(), $metric->getAllocationKey()];
50+
return true;
51+
});
4652
$hook = new FfeOutcomeHook();
4753
$client = ffeOutcomeClient($provider, $hook);
4854
$customerExposures = [];
@@ -52,25 +58,30 @@ OpenFeature\OpenFeatureAPI::getInstance()->addHooks(new DDTrace\OpenFeature\Expo
5258
}
5359
));
5460
$context = new OpenFeature\implementation\flags\EvaluationContext('same-subject', new OpenFeature\implementation\flags\Attributes(['plan' => 'pro']));
55-
$hook->onAfter = function () use (&$committed) {
61+
$hook->onAfter = function () use (&$committed, &$metrics) {
5662
if ($committed !== []) throw new LogicException('exposures committed before after hooks');
63+
if ($metrics !== []) throw new LogicException('root metric committed before after hooks');
5764
throw new RuntimeException('reject result');
5865
};
5966
$details = $client->getStringDetails('root', 'fallback', $context);
6067
echo 'after_error='; var_dump($details->getValue() === 'fallback' && $committed === [] && queuedExposureCount() === 0
6168
&& array_map(function ($r) { return [$r[0], $r[5]]; }, $ffeRecords) === [['parent', null], ['root', 'GENERAL']]
6269
&& $customerExposures === [['root', false, []]]);
70+
echo 'after_error_metric='; var_dump($metrics === [['root', null, 'ERROR', 'GENERAL', null]]);
6371

6472
$ffeRecords = [];
6573
$customerExposures = [];
66-
$hook->onAfter = function () use (&$committed) {
74+
$metrics = [];
75+
$hook->onAfter = function () use (&$committed, &$metrics) {
6776
if ($committed !== []) throw new LogicException('exposures committed before after hooks');
77+
if ($metrics !== []) throw new LogicException('root metric committed before after hooks');
6878
};
6979
$details = $client->getStringDetails('root', 'fallback', $context);
7080
echo 'retry='; var_dump($details->getValue() === 'on' && count($committed) === 2 && queuedExposureCount() === 2
7181
&& $committed[0] === ['parent', 'same-subject', ['plan' => 'pro'], 'parent-allocation', 'on', 7, ['parent-exposure' => true]]
7282
&& $committed[1] === ['root', 'same-subject', ['plan' => 'pro'], 'root-allocation', 'on', 0, ['root-exposure' => true]]);
7383
echo 'root_only_hook='; var_dump($customerExposures === [['root', true, ['root-hook' => 'root']]]);
84+
echo 'success_metric='; var_dump($metrics === [['root', 'on', 'TARGETING_MATCH', null, 'root-allocation']]);
7485

7586
$committed = [];
7687
$ffeRecords = [];
@@ -83,13 +94,16 @@ echo 'features_and_cache='; var_dump(count($committed) === 2 && queuedExposureCo
8394
$committed = [];
8495
$ffeRecords = [];
8596
$hook->onAfter = null;
97+
$metrics = [];
8698
$hook->onBefore = function () { throw new RuntimeException('before failed'); };
8799
$details = $client->getStringDetails('root', 'fallback', $context);
88100
echo 'before_error='; var_dump($details->getValue() === 'fallback' && $committed === []
89101
&& queuedExposureCount() === 2 && count($ffeRecords) === 1 && $ffeRecords[0][0] === 'root' && $ffeRecords[0][5] === 'GENERAL');
102+
echo 'before_error_metric='; var_dump($metrics === [['root', null, 'ERROR', 'GENERAL', null]]);
90103
$hook->onBefore = null;
91104

92105
// Direct-provider calls follow the OpenFeature contract: no exposure without its invocation hook.
106+
$metrics = [];
93107
$hook->onAfter = function ($context) use ($provider) {
94108
if ($context->getFlagKey() === 'root') {
95109
$provider->resolveStringValue('parent', 'fallback');
@@ -98,9 +112,14 @@ $hook->onAfter = function ($context) use ($provider) {
98112
};
99113
$client->getStringDetails('root', 'fallback', $context);
100114
echo 'nested='; var_dump($committed === []);
115+
echo 'nested_metrics='; var_dump($metrics === [
116+
['parent', 'on', 'STATIC', null, 'parent-allocation'],
117+
['root', null, 'ERROR', 'GENERAL', null],
118+
]);
101119

102120
// Suspend after native evaluation, then complete another invocation on the same provider.
103121
$committed = [];
122+
$metrics = [];
104123
$hook->onAfter = function ($context) {
105124
if ($context->getFlagKey() === 'root') {
106125
Fiber::suspend();
@@ -113,28 +132,59 @@ $second = new Fiber(function () use ($client) {
113132
});
114133
$first->start();
115134
echo 'suspended='; var_dump($committed === []);
135+
echo 'suspended_metric='; var_dump($metrics === []);
116136
$second->start();
117137
$first->resume();
118138
echo 'fibers='; var_dump($first->getReturn() === 'fallback' && $second->getReturn() === 'on'
119139
&& count($committed) === 1 && $committed[0][0] === 'parent' && $committed[0][1] === 'other-subject');
140+
echo 'fiber_metrics='; var_dump($metrics === [
141+
['parent', 'on', 'STATIC', null, 'parent-allocation'],
142+
['root', null, 'ERROR', 'GENERAL', null],
143+
]);
120144

121145
// A provider failure keeps its prerequisite observation without an exposure.
122146
$committed = [];
123147
$ffeRecords = [];
148+
$metrics = [];
124149
$hook->onAfter = null;
125150
$details = $client->getStringDetails('missing', 'fallback', $context);
126151
echo 'graph_error='; var_dump($details->getValue() === 'fallback' && $committed === []
127152
&& count($ffeRecords) === 2 && $ffeRecords[0][5] === 'FLAG_NOT_FOUND' && $ffeRecords[1][5] === 'GENERAL');
153+
echo 'graph_error_metric='; var_dump($metrics === [['missing', null, 'ERROR', 'GENERAL', null]]);
154+
155+
// Preserve SDK error codes from hooks, including after a successful resolution.
156+
$metrics = [];
157+
$hook->onAfter = function () {
158+
throw new class extends RuntimeException implements OpenFeature\interfaces\provider\ThrowableWithResolutionError {
159+
public function getResolutionError(): OpenFeature\interfaces\provider\ResolutionError {
160+
return new OpenFeature\implementation\provider\ResolutionError(
161+
OpenFeature\interfaces\provider\ErrorCode::INVALID_CONTEXT()
162+
);
163+
}
164+
};
165+
};
166+
$details = $client->getStringDetails('root', 'fallback', $context);
167+
echo 'typed_hook_error='; var_dump($details->getValue() === 'fallback'
168+
&& $details->getError()->getResolutionErrorCode()->getValue() === 'INVALID_CONTEXT'
169+
&& $metrics === [['root', null, 'ERROR', 'INVALID_CONTEXT', null]]);
128170
?>
129171
--EXPECT--
130172
after_error=bool(true)
173+
after_error_metric=bool(true)
131174
retry=bool(true)
132175
root_only_hook=bool(true)
176+
success_metric=bool(true)
133177
features_and_cache=bool(true)
134178
before_error=bool(true)
179+
before_error_metric=bool(true)
135180
nested=bool(true)
181+
nested_metrics=bool(true)
136182
suspended=bool(true)
183+
suspended_metric=bool(true)
137184
fibers=bool(true)
185+
fiber_metrics=bool(true)
138186
graph_error=bool(true)
187+
graph_error_metric=bool(true)
188+
typed_hook_error=bool(true)
139189
--CLEAN--
140190
<?php @unlink(__DIR__ . '/dependent_exposures_final_outcome.debug.log'); ?>

0 commit comments

Comments
 (0)