diff --git a/.changeset/quiet-keys-vanish.md b/.changeset/quiet-keys-vanish.md new file mode 100644 index 00000000..d25c930b --- /dev/null +++ b/.changeset/quiet-keys-vanish.md @@ -0,0 +1,6 @@ +--- +"posthog-php": minor +"posthog-laravel": minor +--- + +Flag evaluation methods take optional `personPropertyKeysKnownAbsent` and `groupPropertyKeysKnownAbsent` arguments listing property keys known to be absent. Local evaluation resolves a listed key without falling back to `/flags`: `is_not_set`, `is_not` and the `not_*` string operators match, and every other operator doesn't. A remote request carries the keys. A list over 1000 keys throws `InvalidArgumentException`. diff --git a/.github/workflows/sdk-compliance.yml b/.github/workflows/sdk-compliance.yml index 388c5eac..d69bd5be 100644 --- a/.github/workflows/sdk-compliance.yml +++ b/.github/workflows/sdk-compliance.yml @@ -24,11 +24,11 @@ jobs: dockerfile: sdk_compliance_adapter/Dockerfile.socket - consumer: fork_curl dockerfile: sdk_compliance_adapter/Dockerfile.fork_curl - uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@dde638562d33572b5c8ac3a2eafc98b92ffa2261 + uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@574c029da75e96d55c11a54d942a6df983a58ea2 with: adapter-dockerfile: ${{ matrix.dockerfile }} adapter-context: "." - test-harness-version: "1.32.0" + test-harness-version: "1.34.0" report-name: sdk-compliance-${{ matrix.consumer }} sdk-type: server concurrency: 1 diff --git a/api/laravel-public-api.json b/api/laravel-public-api.json index cbe0efc8..e1c1d78d 100644 --- a/api/laravel-public-api.json +++ b/api/laravel-public-api.json @@ -512,6 +512,26 @@ "default": null, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -577,6 +597,26 @@ "default": false, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -662,6 +702,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -720,6 +780,26 @@ "default": [], "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -798,6 +878,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -930,6 +1030,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -1303,6 +1423,26 @@ "default": null, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, diff --git a/api/public-api.json b/api/public-api.json index 31f3953e..63f75949 100644 --- a/api/public-api.json +++ b/api/public-api.json @@ -150,6 +150,34 @@ } ] }, + "assertKnownAbsentKeysValid": { + "static": true, + "abstract": false, + "final": false, + "returnType": "void", + "parameters": [ + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + } + ] + }, "capture": { "static": false, "abstract": false, @@ -412,6 +440,26 @@ "default": null, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -460,6 +508,26 @@ "default": [], "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -528,6 +596,26 @@ "default": null, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -593,6 +681,26 @@ "default": false, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -678,6 +786,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -736,6 +864,26 @@ "default": [], "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -814,6 +962,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -953,6 +1121,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -2798,6 +2986,16 @@ "default": 1, "defaultConstant": null, "hasDefault": true + }, + { + "name": "knownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true } ] }, @@ -2924,6 +3122,16 @@ "default": 1, "defaultConstant": null, "hasDefault": true + }, + { + "name": "knownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true } ] }, @@ -3032,6 +3240,26 @@ "default": 1, "defaultConstant": null, "hasDefault": true + }, + { + "name": "knownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupKnownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true } ] }, @@ -3070,6 +3298,16 @@ "default": 1, "defaultConstant": null, "hasDefault": true + }, + { + "name": "knownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true } ] }, @@ -3148,6 +3386,16 @@ "default": 1, "defaultConstant": null, "hasDefault": true + }, + { + "name": "knownAbsentKeys", + "type": null, + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true } ] }, @@ -4540,6 +4788,26 @@ "default": null, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -4633,6 +4901,26 @@ "default": false, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -4725,6 +5013,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -4783,6 +5091,26 @@ "default": [], "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -4861,6 +5189,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, @@ -5051,6 +5399,26 @@ "default": true, "defaultConstant": null, "hasDefault": true + }, + { + "name": "personPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "groupPropertyKeysKnownAbsent", + "type": "?array", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true } ] }, diff --git a/lib/Client.php b/lib/Client.php index f9925b4a..d47fae87 100644 --- a/lib/Client.php +++ b/lib/Client.php @@ -19,6 +19,11 @@ class Client implements FeatureFlagEvaluationsHost { private const SIZE_LIMIT = 50_000; + // The flags service rejects a known-absent list longer than this, counted with duplicates. + private const KNOWN_ABSENT_KEYS_LIMIT = 1000; + + private const PERSON_METADATA_KEY_PREFIX = '__posthog_person_metadata__'; + private const ENV_RELEASE_ID = "POSTHOG_RELEASE_ID"; /** @@ -870,6 +875,10 @@ public function identify(array $message) * @param array> $groupProperties Group properties to use for flag evaluation. * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return bool|null * @throws Exception */ @@ -880,7 +889,9 @@ public function isFeatureEnabled( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): null | bool { trigger_error( 'Client::isFeatureEnabled() is deprecated and will be removed in a future major ' @@ -899,7 +910,9 @@ public function isFeatureEnabled( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); if ($result === null) { @@ -921,6 +934,10 @@ public function isFeatureEnabled( * @param array> $groupProperties Group properties to use for flag evaluation. * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return bool|string|null * @throws Exception */ @@ -931,7 +948,9 @@ public function getFeatureFlag( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): null | bool | string { trigger_error( 'Client::getFeatureFlag() is deprecated and will be removed in a future major ' @@ -949,7 +968,9 @@ public function getFeatureFlag( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); return $result?->getValue(); @@ -967,6 +988,10 @@ public function getFeatureFlag( * @param array> $groupProperties Group properties to use for flag evaluation. * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return FeatureFlagResult|null * @throws Exception */ @@ -977,7 +1002,9 @@ public function getFeatureFlagResult( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): ?FeatureFlagResult { trigger_error( 'Client::getFeatureFlagResult() is deprecated and will be removed in a future major ' @@ -994,7 +1021,9 @@ public function getFeatureFlagResult( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -1007,6 +1036,8 @@ public function getFeatureFlagResult( * @param array $groups * @param array $personProperties * @param array> $groupProperties + * @param list|null $personPropertyKeysKnownAbsent + * @param array>|null $groupPropertyKeysKnownAbsent * @throws Exception */ private function doGetFeatureFlagResult( @@ -1016,8 +1047,11 @@ private function doGetFeatureFlagResult( array $personProperties = [], array $groupProperties = [], bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): ?FeatureFlagResult { + self::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); $distinctId = $this->resolveDistinctId($distinctId); if ($distinctId === '') { $this->warnMissingDistinctId('Feature flag evaluation'); @@ -1045,7 +1079,9 @@ private function doGetFeatureFlagResult( $distinctId, $groups, $personProperties, - $groupProperties + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } catch (RequiresServerEvaluationException $e) { $result = null; @@ -1074,7 +1110,9 @@ private function doGetFeatureFlagResult( $personProperties, $groupProperties, null, - [$key] + [$key], + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); $errors = []; @@ -1199,6 +1237,10 @@ private function doGetFeatureFlagResult( * @param array $groups Group identifiers for group-based flags. * @param array $personProperties Person properties to use for flag evaluation. * @param array> $groupProperties Group properties to use for flag evaluation. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return mixed */ public function getFeatureFlagPayload( @@ -1207,6 +1249,8 @@ public function getFeatureFlagPayload( array $groups = array(), array $personProperties = array(), array $groupProperties = array(), + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): mixed { trigger_error( 'Client::getFeatureFlagPayload() is deprecated and will be removed in a future major ' @@ -1224,7 +1268,9 @@ public function getFeatureFlagPayload( $personProperties, $groupProperties, false, - false + false, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); return $result?->getPayload(); @@ -1323,6 +1369,10 @@ public function getRemoteConfigPayload(string $key): mixed * @param array $personProperties Person properties to use for flag evaluation. * @param array> $groupProperties Group properties to use for flag evaluation. * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return array * @throws Exception */ @@ -1331,8 +1381,11 @@ public function getAllFlags( array $groups = array(), array $personProperties = array(), array $groupProperties = array(), - bool $onlyEvaluateLocally = false + bool $onlyEvaluateLocally = false, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { + self::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); $distinctId = $this->resolveDistinctId($distinctId); if ($distinctId === '') { $this->warnMissingDistinctId('getAllFlags()'); @@ -1357,7 +1410,9 @@ public function getAllFlags( $distinctId, $groups, $personProperties, - $groupProperties + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } catch (RequiresServerEvaluationException $e) { $fallbackToFlags = true; @@ -1374,7 +1429,14 @@ public function getAllFlags( if ($fallbackToFlags && !$onlyEvaluateLocally) { try { - $featureFlags = $this->fetchFeatureVariants($distinctId, $groups, $personProperties, $groupProperties); + $featureFlags = $this->fetchFeatureVariants( + $distinctId, + $groups, + $personProperties, + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent + ); $response = array_merge($response, $featureFlags); } catch (Exception $e) { error_log("[PostHog][Client] Unable to get feature variants:" . $e->getMessage()); @@ -1405,7 +1467,17 @@ public function getAllFlags( * an empty snapshot without local or remote evaluation. Use this when you only need a * handful of flags out of many. Distinct from FeatureFlagEvaluations::only(), which scopes * which already-evaluated flags get attached to a captured event. + * @param list|null $personPropertyKeysKnownAbsent Person property keys the caller knows the + * person doesn't have. A listed key is absent even when $personProperties holds a value for it, + * so local evaluation resolves it instead of falling back to /flags: `is_not_set`, `is_not` and + * the `not_*` string operators match, and every other operator doesn't. An operator the SDK + * can't evaluate locally still falls back. Keys starting with `__posthog_person_metadata__` + * are ignored. The keys are also sent with any /flags request. At most 1000 keys. + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to + * be absent, by group type name. Keys apply only to their own group type. At most 1000 keys per + * group type. * @return FeatureFlagEvaluations + * @throws InvalidArgumentException When a known-absent list holds more than 1000 keys or a non-string key. */ public function evaluateFlags( ?string $distinctId = null, @@ -1414,8 +1486,11 @@ public function evaluateFlags( array $groupProperties = [], bool $onlyEvaluateLocally = false, ?bool $disableGeoip = null, - ?array $flagKeys = null + ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): FeatureFlagEvaluations { + self::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); $distinctId = $this->resolveDistinctId($distinctId); $host = new Internal\ContextualFeatureFlagEvaluationsHost( $this, @@ -1482,7 +1557,9 @@ public function evaluateFlags( $distinctId, $groups, $personProperties, - $groupProperties + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } catch (RequiresServerEvaluationException | InconclusiveMatchException $e) { $fallbackToRemote = true; @@ -1538,7 +1615,9 @@ public function evaluateFlags( $personProperties, $groupProperties, $disableGeoip, - $flagKeys + $flagKeys, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); $requestId = $response['requestId'] ?? null; @@ -1737,11 +1816,25 @@ private function computeFlagLocally( string $distinctId, array $groups = array(), array $personProperties = array(), - array $groupProperties = array() + array $groupProperties = array(), + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): bool | string { // Create evaluation cache for flag dependencies $evaluationCache = []; + $personKnownAbsentKeys = []; + foreach ($personPropertyKeysKnownAbsent ?? [] as $absentKey) { + // Known absence never hides a persons-table field read through the metadata prefix. + if (!str_starts_with($absentKey, self::PERSON_METADATA_KEY_PREFIX)) { + $personKnownAbsentKeys[$absentKey] = true; + } + } + $groupKnownAbsentKeys = []; + foreach ($groupPropertyKeysKnownAbsent ?? [] as $groupType => $absentKeys) { + $groupKnownAbsentKeys[$groupType] = array_fill_keys($absentKeys, true); + } + if (!$featureFlag["active"]) { return false; } @@ -1781,7 +1874,9 @@ private function computeFlagLocally( $groups, $groupProperties, $definitionSnapshot['group_type_mapping'], - $definitionSnapshot['property_matching_version'] + $definitionSnapshot['property_matching_version'], + $groupKnownAbsentKeys[$groupName] ?? [], + $groupKnownAbsentKeys ); } else { $localPersonProperties = $personProperties; @@ -1799,7 +1894,9 @@ private function computeFlagLocally( $groups, $groupProperties, $definitionSnapshot['group_type_mapping'], - $definitionSnapshot['property_matching_version'] + $definitionSnapshot['property_matching_version'], + $personKnownAbsentKeys, + $groupKnownAbsentKeys ); } } @@ -1812,15 +1909,28 @@ private function computeFlagLocally( * @param array $groups Group identifiers for group-based flags. * @param array $personProperties Person properties to use for flag evaluation. * @param array> $groupProperties Group properties to use for flag evaluation. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return array Feature flag values by key. */ public function fetchFeatureVariants( string $distinctId, array $groups = [], array $personProperties = [], - array $groupProperties = [] + array $groupProperties = [], + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { - $response = $this->fetchFlagsResponse($distinctId, $groups, $personProperties, $groupProperties); + $response = $this->fetchFlagsResponse( + $distinctId, + $groups, + $personProperties, + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent + ); return $response['featureFlags'] ?? []; } @@ -1829,15 +1939,28 @@ public function fetchFeatureVariants( * @param array $groups * @param array $personProperties * @param array> $groupProperties + * @param list|null $personPropertyKeysKnownAbsent + * @param array>|null $groupPropertyKeysKnownAbsent * @return array Feature flags response. */ private function fetchFlagsResponse( string $distinctId, array $groups = [], array $personProperties = [], - array $groupProperties = [] + array $groupProperties = [], + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { - return $this->flags($distinctId, $groups, $personProperties, $groupProperties); + return $this->flags( + $distinctId, + $groups, + $personProperties, + $groupProperties, + null, + null, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent + ); } /** @@ -2359,6 +2482,10 @@ private function normalizeFeatureFlags(string $response): array * @param array> $groupProperties Group properties for flag evaluation. * @param bool|null $disableGeoip Override GeoIP enrichment; null inherits the client setting. * @param list|null $flagKeys Optional list of flag keys to evaluate. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent for + * this evaluation. See evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See evaluateFlags(). * @return array The normalized feature flags response. */ public function flags( @@ -2367,7 +2494,9 @@ public function flags( array $personProperties = [], array $groupProperties = [], ?bool $disableGeoip = null, - ?array $flagKeys = null + ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { try { return $this->requestFlags( @@ -2376,7 +2505,9 @@ public function flags( $personProperties, $groupProperties, $disableGeoip, - $flagKeys + $flagKeys, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } catch (HttpException $e) { error_log('[PostHog][Client] Unable to fetch feature flags: ' . $e->getMessage()); @@ -2385,8 +2516,11 @@ public function flags( } /** + * @param list|null $personPropertyKeysKnownAbsent + * @param array>|null $groupPropertyKeysKnownAbsent * @return array * @throws HttpException On network errors, API errors, or quota limits. + * @throws InvalidArgumentException When a known-absent list is invalid. */ private function requestFlags( string $distinctId, @@ -2394,8 +2528,11 @@ private function requestFlags( array $personProperties = [], array $groupProperties = [], ?bool $disableGeoip = null, - ?array $flagKeys = null + ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { + self::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); if (!$this->enabled) { return $this->emptyFlagsResponse(); } @@ -2413,6 +2550,15 @@ private function requestFlags( $payload["flag_keys_to_evaluate"] = array_values($flagKeys); } + if (!empty($personPropertyKeysKnownAbsent)) { + $payload["person_property_keys_known_absent"] = array_values($personPropertyKeysKnownAbsent); + } + + $groupKeysKnownAbsent = array_map('array_values', array_filter($groupPropertyKeysKnownAbsent ?? [])); + if (!empty($groupKeysKnownAbsent)) { + $payload["group_property_keys_known_absent"] = (object) $groupKeysKnownAbsent; + } + $httpResponse = $this->sendFeatureFlagsRequest($payload); $responseCode = $httpResponse->getResponseCode(); @@ -2923,6 +3069,45 @@ private function message($msg) return $msg; } + /** + * Reject known-absent lists the flags service would refuse, before any evaluation or request. + * Lists are never truncated. + * + * @internal Used by PostHog framework integrations that return before calling the client; + * not part of the customer API. + * @param list|null $personPropertyKeysKnownAbsent + * @param array>|null $groupPropertyKeysKnownAbsent + * @throws InvalidArgumentException + */ + public static function assertKnownAbsentKeysValid( + ?array $personPropertyKeysKnownAbsent, + ?array $groupPropertyKeysKnownAbsent + ): void { + self::assertKnownAbsentKeyList($personPropertyKeysKnownAbsent ?? [], 'personPropertyKeysKnownAbsent'); + foreach ($groupPropertyKeysKnownAbsent ?? [] as $groupType => $absentKeys) { + if (!is_array($absentKeys)) { + throw new InvalidArgumentException( + "groupPropertyKeysKnownAbsent['{$groupType}'] must be a list of property keys." + ); + } + self::assertKnownAbsentKeyList($absentKeys, "groupPropertyKeysKnownAbsent['{$groupType}']"); + } + } + + private static function assertKnownAbsentKeyList(array $absentKeys, string $name): void + { + if (count($absentKeys) > self::KNOWN_ABSENT_KEYS_LIMIT) { + throw new InvalidArgumentException( + "{$name} can hold at most " . self::KNOWN_ABSENT_KEYS_LIMIT . " keys, got " . count($absentKeys) . "." + ); + } + foreach ($absentKeys as $absentKey) { + if (!is_string($absentKey)) { + throw new InvalidArgumentException("{$name} must hold only string property keys."); + } + } + } + private function addLocalPersonAndGroupProperties( array $groups, array $personProperties, diff --git a/lib/FeatureFlag.php b/lib/FeatureFlag.php index 0f6b0540..59cf017c 100644 --- a/lib/FeatureFlag.php +++ b/lib/FeatureFlag.php @@ -22,17 +22,35 @@ class FeatureFlag UnresolvedFlagReason::MISSING_CONTEXT, ]; + // Operators that match a property key the caller listed as known absent; every other operator doesn't. + private const KNOWN_ABSENT_MATCHING_OPERATORS = [ + "is_not_set", "is_not", "not_icontains", "not_starts_with", "not_ends_with", "not_regex", + ]; + /** * Match a single property filter against provided property values. * * @param array $property Feature flag property filter. * @param array $propertyValues Available property values keyed by property name. * @param mixed $propertyMatchingVersion Definition snapshot selector; only 2 enables explicit matching. + * @param array $knownAbsentKeys Property keys known to be absent, as array keys. A listed + * key is absent even when $propertyValues holds a value for it. * @return bool Whether the property matches. * @throws InconclusiveMatchException When the property cannot be evaluated locally. */ - public static function matchProperty($property, $propertyValues, $propertyMatchingVersion = 1) - { + public static function matchProperty( + $property, + $propertyValues, + $propertyMatchingVersion = 1, + $knownAbsentKeys = [] + ) { + $key = $property["key"] ?? null; + if ((is_string($key) || is_int($key)) && isset($knownAbsentKeys[$key])) { + // An unsupported operator or malformed filter stays inconclusive even for a known-absent key. + FeatureFlag::assertFilterSupported($property); + return in_array($property["operator"] ?? "exact", self::KNOWN_ABSENT_MATCHING_OPERATORS, true); + } + try { return FeatureFlag::matchPropertyValue($property, $propertyValues, $propertyMatchingVersion); } catch (InconclusiveMatchException $e) { @@ -305,7 +323,8 @@ public static function matchCohort( $flagsByKey = null, $evaluationCache = null, $distinctId = null, - $propertyMatchingVersion = 1 + $propertyMatchingVersion = 1, + $knownAbsentKeys = [] ) { return FeatureFlag::matchCohortForIdentity( $property, @@ -315,7 +334,8 @@ public static function matchCohort( $evaluationCache, $distinctId, $propertyMatchingVersion, - false + false, + $knownAbsentKeys ); } @@ -328,7 +348,8 @@ private static function matchCohortForIdentity( &$evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + array $knownAbsentKeys ) { $cohortId = strval($property["value"]); if (!array_key_exists($cohortId, $cohortProperties)) { @@ -347,7 +368,8 @@ private static function matchCohortForIdentity( $evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); } @@ -372,7 +394,8 @@ public static function matchPropertyGroup( $flagsByKey = null, $evaluationCache = null, $distinctId = null, - $propertyMatchingVersion = 1 + $propertyMatchingVersion = 1, + $knownAbsentKeys = [] ) { return FeatureFlag::matchPropertyGroupForIdentity( $propertyGroup, @@ -382,7 +405,8 @@ public static function matchPropertyGroup( $evaluationCache, $distinctId, $propertyMatchingVersion, - false + false, + $knownAbsentKeys ); } @@ -395,7 +419,8 @@ private static function matchPropertyGroupForIdentity( &$evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + array $knownAbsentKeys ) { if (!$propertyGroup) { return true; @@ -423,7 +448,8 @@ private static function matchPropertyGroupForIdentity( $evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); if ($propertyGroupType === 'AND') { if (!$matches) { @@ -465,7 +491,8 @@ private static function matchPropertyGroupForIdentity( $evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); } elseif ($propType === 'flag') { $matches = FeatureFlag::evaluateFlagDependencyForIdentity( @@ -476,10 +503,16 @@ private static function matchPropertyGroupForIdentity( $propertyValues, $cohortProperties, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); } else { - $matches = FeatureFlag::matchProperty($prop, $propertyValues, $propertyMatchingVersion); + $matches = FeatureFlag::matchProperty( + $prop, + $propertyValues, + $propertyMatchingVersion, + $knownAbsentKeys + ); } $negation = $prop["negation"] ?? false; @@ -1247,6 +1280,9 @@ private static function variantLookupTable($featureFlag) * @param array> $groupProperties Group properties for evaluation. * @param array $groupTypeMapping Mapping from group type index to group type name. * @param mixed $propertyMatchingVersion Definition snapshot selector; defaults to legacy matching. + * @param array $knownAbsentKeys Keys of $properties known to be absent, as array keys. + * @param array> $groupKnownAbsentKeys Group property keys known to be absent, + * as array keys, by group type name. * @return bool|string False for disabled, true for enabled boolean flags, or variant key. * @throws RequiresServerEvaluationException When server-side data is required. * @throws InconclusiveMatchException When the flag cannot be evaluated locally. @@ -1261,7 +1297,9 @@ public static function matchFeatureFlagProperties( $groups = [], $groupProperties = [], $groupTypeMapping = [], - $propertyMatchingVersion = 1 + $propertyMatchingVersion = 1, + $knownAbsentKeys = [], + $groupKnownAbsentKeys = [] ) { return FeatureFlag::matchFeatureFlagPropertiesForIdentity( $flag, @@ -1274,7 +1312,9 @@ public static function matchFeatureFlagProperties( $groupProperties, $groupTypeMapping, $propertyMatchingVersion, - ($flag["filters"] ?? [])["aggregation_group_type_index"] ?? null + ($flag["filters"] ?? [])["aggregation_group_type_index"] ?? null, + $knownAbsentKeys, + $groupKnownAbsentKeys ); } @@ -1295,7 +1335,9 @@ private static function matchFeatureFlagPropertiesForIdentity( $groupProperties, $groupTypeMapping, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + array $knownAbsentKeys, + array $groupKnownAbsentKeys ) { $flagFilters = $flag["filters"] ?? []; @@ -1322,6 +1364,7 @@ private static function matchFeatureFlagPropertiesForIdentity( : $flagAggregation; $effectiveProperties = $properties; + $effectiveKnownAbsentKeys = $knownAbsentKeys; $effectiveBucketing = $distinctId; $effectiveAggregation = $identityAggregation; $conditionEvaluationCache = &$evaluationCache; @@ -1342,6 +1385,7 @@ private static function matchFeatureFlagPropertiesForIdentity( continue; } $effectiveProperties = $groupProperties[$groupName]; + $effectiveKnownAbsentKeys = $groupKnownAbsentKeys[$groupName] ?? []; $effectiveBucketing = $groups[$groupName]; $effectiveAggregation = $conditionAggregation; // Dependency results depend on the bucketing identity, so each group keeps its own. @@ -1359,7 +1403,8 @@ private static function matchFeatureFlagPropertiesForIdentity( $flagsByKey, $conditionEvaluationCache, $propertyMatchingVersion, - $effectiveAggregation + $effectiveAggregation, + $effectiveKnownAbsentKeys ); if ($matchResult === ConditionMatch::Match) { @@ -1430,7 +1475,8 @@ private static function isConditionMatch( $flagsByKey, &$evaluationCache, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + array $knownAbsentKeys ): ConditionMatch { $rolloutPercentage = array_key_exists("rollout_percentage", $condition) ? $condition["rollout_percentage"] : null; @@ -1452,7 +1498,8 @@ private static function isConditionMatch( $evaluationCache, $distinctId, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); } elseif ($propertyType == 'flag') { $matches = FeatureFlag::evaluateFlagDependencyForIdentity( @@ -1463,10 +1510,16 @@ private static function isConditionMatch( $properties, $cohorts, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys ); } else { - $matches = FeatureFlag::matchProperty($property, $properties, $propertyMatchingVersion); + $matches = FeatureFlag::matchProperty( + $property, + $properties, + $propertyMatchingVersion, + $knownAbsentKeys + ); } } catch (RequiresServerEvaluationException $e) { // Fall back to the server only when this is the first filter that could not be @@ -1730,7 +1783,8 @@ public static function evaluateFlagDependency( $distinctId, $properties, $cohortProperties, - $propertyMatchingVersion = 1 + $propertyMatchingVersion = 1, + $knownAbsentKeys = [] ) { return FeatureFlag::evaluateFlagDependencyForIdentity( $property, @@ -1740,7 +1794,8 @@ public static function evaluateFlagDependency( $properties, $cohortProperties, $propertyMatchingVersion, - false + false, + $knownAbsentKeys ); } @@ -1756,7 +1811,8 @@ private static function evaluateFlagDependencyForIdentity( $properties, $cohortProperties, $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + array $knownAbsentKeys ) { if ($flagsByKey === null || $evaluationCache === null) { throw new InconclusiveMatchException( @@ -1821,7 +1877,9 @@ private static function evaluateFlagDependencyForIdentity( [], [], $propertyMatchingVersion, - $identityAggregation + $identityAggregation, + $knownAbsentKeys, + [] ); $evaluationCache[$depFlagKey] = $depResult; } catch (RequiresServerEvaluationException $e) { diff --git a/lib/PostHog.php b/lib/PostHog.php index fafbaef5..863ef80a 100644 --- a/lib/PostHog.php +++ b/lib/PostHog.php @@ -264,6 +264,10 @@ public static function groupIdentify(array $message) * @param array> $groupProperties * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return bool|null * @throws Exception */ @@ -274,7 +278,9 @@ public static function isFeatureEnabled( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): null | bool { self::checkClient(); return self::$client->isFeatureEnabled( @@ -284,7 +290,9 @@ public static function isFeatureEnabled( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -300,6 +308,10 @@ public static function isFeatureEnabled( * @param array> $groupProperties * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return bool|string|null * @throws Exception */ @@ -310,7 +322,9 @@ public static function getFeatureFlag( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): null | bool | string { self::checkClient(); return self::$client->GetFeatureFlag( @@ -320,7 +334,9 @@ public static function getFeatureFlag( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -336,6 +352,10 @@ public static function getFeatureFlag( * @param array> $groupProperties Group properties to use for flag evaluation. * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. * @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return FeatureFlagResult|null * @throws Exception */ @@ -346,7 +366,9 @@ public static function getFeatureFlagResult( array $personProperties = array(), array $groupProperties = array(), bool $onlyEvaluateLocally = false, - bool $sendFeatureFlagEvents = true + bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): ?FeatureFlagResult { self::checkClient(); return self::$client->getFeatureFlagResult( @@ -356,7 +378,9 @@ public static function getFeatureFlagResult( $personProperties, $groupProperties, $onlyEvaluateLocally, - $sendFeatureFlagEvents + $sendFeatureFlagEvents, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -373,6 +397,10 @@ public static function getFeatureFlagResult( * @param array $groups * @param array $personProperties * @param array> $groupProperties + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return mixed */ public static function getFeatureFlagPayload( @@ -381,6 +409,8 @@ public static function getFeatureFlagPayload( array $groups = array(), array $personProperties = array(), array $groupProperties = array(), + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): mixed { self::checkClient(); @@ -389,7 +419,9 @@ public static function getFeatureFlagPayload( $distinctId, $groups, $personProperties, - $groupProperties + $groupProperties, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -429,6 +461,10 @@ public static function getRemoteConfigPayload(string $key): mixed * subset, which makes the response smaller and the request cheaper. Use this when you * only need a handful of flags out of many. Distinct from FeatureFlagEvaluations::only(), * which scopes which already-evaluated flags get attached to a captured event. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return FeatureFlagEvaluations * @throws Exception */ @@ -439,7 +475,9 @@ public static function evaluateFlags( array $groupProperties = array(), bool $onlyEvaluateLocally = false, ?bool $disableGeoip = null, - ?array $flagKeys = null + ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): FeatureFlagEvaluations { self::checkClient(); return self::$client->evaluateFlags( @@ -449,7 +487,9 @@ public static function evaluateFlags( $groupProperties, $onlyEvaluateLocally, $disableGeoip, - $flagKeys + $flagKeys, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } @@ -461,6 +501,10 @@ public static function evaluateFlags( * @param array $personProperties * @param array> $groupProperties * @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback. + * @param list|null $personPropertyKeysKnownAbsent Person property keys known to be absent. + * See Client::evaluateFlags(). + * @param array>|null $groupPropertyKeysKnownAbsent Group property keys known to be + * absent, by group type name. See Client::evaluateFlags(). * @return array * @throws Exception */ @@ -469,7 +513,9 @@ public static function getAllFlags( array $groups = array(), array $personProperties = array(), array $groupProperties = array(), - bool $onlyEvaluateLocally = false + bool $onlyEvaluateLocally = false, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null ): array { self::checkClient(); return self::$client->getAllFlags( @@ -477,7 +523,9 @@ public static function getAllFlags( $groups, $personProperties, $groupProperties, - $onlyEvaluateLocally + $onlyEvaluateLocally, + $personPropertyKeysKnownAbsent, + $groupPropertyKeysKnownAbsent ); } diff --git a/packages/laravel/src/PostHog.php b/packages/laravel/src/PostHog.php index 4b256e04..a1c357d5 100644 --- a/packages/laravel/src/PostHog.php +++ b/packages/laravel/src/PostHog.php @@ -149,7 +149,10 @@ public function evaluateFlags( bool $onlyEvaluateLocally = false, ?bool $disableGeoip = null, ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): FeatureFlagEvaluations { + Client::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); $context = $this->app->make(Context::class); $data = $context->data(); $distinctId ??= $data['distinctId'] ?? null; @@ -157,6 +160,7 @@ public function evaluateFlags( $disableGeoip ??= $this->app['config']->get('posthog.sdk.disableGeoip', true); $inputs = [ $distinctId, $groups, $personProperties, $groupProperties, $onlyEvaluateLocally, $disableGeoip, $flagKeys, + $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ]; if (!$this->enabled() || $distinctId === null || $distinctId === '') { return new FeatureFlagEvaluations( @@ -262,10 +266,12 @@ public function isFeatureEnabled( array $groupProperties = [], bool $onlyEvaluateLocally = false, bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): ?bool { return $this->callFlagMethod(__FUNCTION__, [ $key, $distinctId, $groups, $personProperties, $groupProperties, - $onlyEvaluateLocally, $sendFeatureFlagEvents, + $onlyEvaluateLocally, $sendFeatureFlagEvents, $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ], $distinctId); } @@ -278,10 +284,12 @@ public function getFeatureFlag( array $groupProperties = [], bool $onlyEvaluateLocally = false, bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): bool|string|null { return $this->callFlagMethod(__FUNCTION__, [ $key, $distinctId, $groups, $personProperties, $groupProperties, - $onlyEvaluateLocally, $sendFeatureFlagEvents, + $onlyEvaluateLocally, $sendFeatureFlagEvents, $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ], $distinctId); } @@ -294,10 +302,12 @@ public function getFeatureFlagResult( array $groupProperties = [], bool $onlyEvaluateLocally = false, bool $sendFeatureFlagEvents = true, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): ?FeatureFlagResult { return $this->callFlagMethod(__FUNCTION__, [ $key, $distinctId, $groups, $personProperties, $groupProperties, - $onlyEvaluateLocally, $sendFeatureFlagEvents, + $onlyEvaluateLocally, $sendFeatureFlagEvents, $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ], $distinctId); } @@ -313,9 +323,12 @@ public function getFeatureFlagPayload( array $groups = [], array $personProperties = [], array $groupProperties = [], + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): mixed { return $this->callFlagMethod(__FUNCTION__, [ $key, $distinctId, $groups, $personProperties, $groupProperties, + $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ], $distinctId); } @@ -339,9 +352,12 @@ public function getAllFlags( array $personProperties = [], array $groupProperties = [], bool $onlyEvaluateLocally = false, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): array { return $this->callFlagMethod(__FUNCTION__, [ $distinctId, $groups, $personProperties, $groupProperties, $onlyEvaluateLocally, + $personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent, ], $distinctId); } diff --git a/packages/laravel/src/Testing/PostHogFake.php b/packages/laravel/src/Testing/PostHogFake.php index d555c60d..6de664b7 100644 --- a/packages/laravel/src/Testing/PostHogFake.php +++ b/packages/laravel/src/Testing/PostHogFake.php @@ -60,7 +60,10 @@ public function evaluateFlags( bool $onlyEvaluateLocally = false, ?bool $disableGeoip = null, ?array $flagKeys = null, + ?array $personPropertyKeysKnownAbsent = null, + ?array $groupPropertyKeysKnownAbsent = null, ): FeatureFlagEvaluations { + Client::assertKnownAbsentKeysValid($personPropertyKeysKnownAbsent, $groupPropertyKeysKnownAbsent); return $this->flagSnapshot ?? new FeatureFlagEvaluations($distinctId ?? '', [], $groups, $this->client()); } diff --git a/packages/laravel/tests/ApiSurfaceTest.php b/packages/laravel/tests/ApiSurfaceTest.php index 21c3a461..aea26873 100644 --- a/packages/laravel/tests/ApiSurfaceTest.php +++ b/packages/laravel/tests/ApiSurfaceTest.php @@ -74,15 +74,18 @@ public static function flagMethods(): array 'key' => 'checkout', 'distinctId' => 'explicit', 'groups' => ['team' => 'one'], 'personProperties' => ['plan' => 'pro'], 'groupProperties' => ['team' => ['size' => 2]], ]; - $options = ['onlyEvaluateLocally' => true, 'sendFeatureFlagEvents' => false]; + $knownAbsent = [ + 'personPropertyKeysKnownAbsent' => ['email'], 'groupPropertyKeysKnownAbsent' => ['team' => ['tier']], + ]; + $options = ['onlyEvaluateLocally' => true, 'sendFeatureFlagEvents' => false] + $knownAbsent; $methods = [ 'boolean' => ['isFeatureEnabled', $single + $options, true], 'value' => ['getFeatureFlag', $single + $options, 'variant'], 'result' => ['getFeatureFlagResult', $single + $options, null], - 'payload' => ['getFeatureFlagPayload', $single, ['color' => 'blue']], + 'payload' => ['getFeatureFlagPayload', $single + $knownAbsent, ['color' => 'blue']], 'all' => ['getAllFlags', array_diff_key($single, ['key' => true]) + [ 'onlyEvaluateLocally' => true, - ], ['checkout' => true]], + ] + $knownAbsent, ['checkout' => true]], ]; $cases = $methods; foreach ($methods as $name => [$method, $arguments, $result]) { diff --git a/packages/laravel/tests/RuntimeTest.php b/packages/laravel/tests/RuntimeTest.php index ed448684..f5014f86 100644 --- a/packages/laravel/tests/RuntimeTest.php +++ b/packages/laravel/tests/RuntimeTest.php @@ -373,6 +373,51 @@ public function testFlagsAreLazyScopedAndValidNoopStillEvaluates(): void } } + public function testEvaluateFlagsForwardsKnownAbsentKeysAndScopesTheSnapshotByThem(): void + { + $bodies = []; + $http = $this->createMock(HttpClient::class); + $http->expects($this->exactly(2))->method('sendRequest')->willReturnCallback( + function ($path, $payload) use (&$bodies) { + $bodies[] = json_decode($payload, true); + return new HttpResponse(json_encode(['flags' => []]), 200); + }, + ); + $sdk = new Client('project-key', ['consumer' => 'noop'], $http, loadFeatureFlags: false); + $manager = $this->app->make(PostHog::class); + (new \ReflectionProperty(PostHog::class, 'client'))->setValue($manager, $sdk); + $context = $this->app->make(Context::class); + $context->begin(['distinctId' => 'user']); + try { + $listed = $manager->evaluateFlags( + personPropertyKeysKnownAbsent: ['plan'], + groupPropertyKeysKnownAbsent: ['team' => ['tier']], + ); + $this->assertSame($listed, $manager->evaluateFlags( + personPropertyKeysKnownAbsent: ['plan'], + groupPropertyKeysKnownAbsent: ['team' => ['tier']], + )); + $this->assertNotSame($listed, $manager->evaluateFlags()); + } finally { + $context->end(); + } + $this->assertSame(['plan'], $bodies[0]['person_property_keys_known_absent']); + $this->assertSame(['team' => ['tier']], $bodies[0]['group_property_keys_known_absent']); + $this->assertArrayNotHasKey('person_property_keys_known_absent', $bodies[1]); + } + + public function testEvaluateFlagsRejectsTooManyKnownAbsentKeysWithoutAnIdentity(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->app->make(PostHog::class)->evaluateFlags(personPropertyKeysKnownAbsent: array_fill(0, 1001, 'plan')); + } + + public function testFakeEvaluateFlagsRejectsTooManyKnownAbsentKeys(): void + { + $this->expectException(\InvalidArgumentException::class); + Facade::fake()->evaluateFlags(groupPropertyKeysKnownAbsent: ['team' => array_fill(0, 1001, 'tier')]); + } + public function testNoIdentityNeverLoadsPrivilegedDefinitionsAndResolversUseContainer(): void { $this->app['config']->set('posthog.secret_key', 'server-secret'); diff --git a/sdk_compliance_adapter/README.md b/sdk_compliance_adapter/README.md index 72dab5d4..55eeae18 100644 --- a/sdk_compliance_adapter/README.md +++ b/sdk_compliance_adapter/README.md @@ -1,7 +1,7 @@ # PostHog PHP SDK compliance adapter The adapter runs the repository's `PostHog\Client` with production capture consumers -and production `HttpClient` feature-flag requests. Harness 1.32.0 selects **30 server +and production `HttpClient` feature-flag requests. Harness 1.34.0 selects **30 server capture V0 tests and 17 flag tests per profile**, including UTC timestamp overrides and gzip. No tests are filtered; compliance assertions remain advisory in CI. @@ -15,7 +15,7 @@ and gzip. No tests are filtered; compliance assertions remain advisory in CI. CI runs all three profiles with distinct report artifacts. An independent `report-completeness` job checks each artifact against `expected_inventory.json` -(the harness 1.32.0 server V0 and flags IDs). Missing, empty, incomplete, duplicate, +(the harness 1.34.0 server V0 and flags IDs). Missing, empty, incomplete, duplicate, or unexpected results and inconsistent summary counts fail this gate. Complete reports with failing assertions still pass the inventory gate; SDK compliance assertions remain advisory. The checker reads the pinned harness's Markdown result diff --git a/sdk_compliance_adapter/__pycache__/check_report.cpython-314.pyc b/sdk_compliance_adapter/__pycache__/check_report.cpython-314.pyc new file mode 100644 index 00000000..90dc2a8a Binary files /dev/null and b/sdk_compliance_adapter/__pycache__/check_report.cpython-314.pyc differ diff --git a/sdk_compliance_adapter/__pycache__/test_check_report.cpython-314.pyc b/sdk_compliance_adapter/__pycache__/test_check_report.cpython-314.pyc new file mode 100644 index 00000000..d146b2e1 Binary files /dev/null and b/sdk_compliance_adapter/__pycache__/test_check_report.cpython-314.pyc differ diff --git a/sdk_compliance_adapter/check_report.py b/sdk_compliance_adapter/check_report.py index 2e181c24..f272165f 100644 --- a/sdk_compliance_adapter/check_report.py +++ b/sdk_compliance_adapter/check_report.py @@ -1,4 +1,4 @@ -"""Check inventory completeness in harness 1.32.0 Markdown; assertions stay advisory.""" +"""Check inventory completeness in harness 1.34.0 Markdown; assertions stay advisory.""" import argparse import json diff --git a/sdk_compliance_adapter/docker-compose.yml b/sdk_compliance_adapter/docker-compose.yml index 1c31d9c4..90c20ad4 100644 --- a/sdk_compliance_adapter/docker-compose.yml +++ b/sdk_compliance_adapter/docker-compose.yml @@ -11,7 +11,7 @@ services: - test-network test-harness: - image: ghcr.io/posthog/sdk-test-harness:1.32.0 + image: ghcr.io/posthog/sdk-test-harness:1.34.0@sha256:43f75861fbcf5bc6c3d35511caa2be2d55274054c6071ebeb943aca0bcd0633a command: ["run", "--adapter-url", "http://sdk-adapter:8080", "--mock-url", "http://test-harness:8081"] networks: - test-network diff --git a/test/FeatureFlagKnownAbsentTest.php b/test/FeatureFlagKnownAbsentTest.php new file mode 100644 index 00000000..2b1bfaf4 --- /dev/null +++ b/test/FeatureFlagKnownAbsentTest.php @@ -0,0 +1,532 @@ + $flag['key'], + 'enabled' => true, + 'variant' => self::REMOTE_VALUE, + 'reason' => ['description' => 'Matched condition set 1'], + 'metadata' => ['id' => 1, 'version' => 1], + ]; + } + $this->httpClient = new MockedHttpClient( + 'app.posthog.com', + flagEndpointResponse: [ + 'flags' => $flags, + 'group_type_mapping' => (object) $groupTypeMapping, + 'cohorts' => (object) $cohorts, + ], + flagsEndpointResponse: ['flags' => $remoteFlags], + ); + $this->client = new Client('random_key', [], $this->httpClient, 'test-personal-key'); + PostHog::init(null, null, $this->client); + } + + private static function flag(string $key, array $properties, ?int $aggregation = null): array + { + $filters = ['groups' => [['properties' => $properties, 'rollout_percentage' => 100]]]; + if ($aggregation !== null) { + $filters['aggregation_group_type_index'] = $aggregation; + } + return ['id' => 1, 'key' => $key, 'active' => true, 'filters' => $filters]; + } + + private static function personFilter(string $operator, mixed $value = 'pro', string $key = 'plan'): array + { + return ['key' => $key, 'type' => 'person', 'operator' => $operator, 'value' => $value]; + } + + /** @return list> */ + private function flagsRequestBodies(): array + { + $bodies = []; + foreach ($this->httpClient->calls ?? [] as $call) { + if (str_starts_with($call['path'], '/flags/?')) { + $bodies[] = json_decode($call['payload'], true); + } + } + return $bodies; + } + + #[DataProvider('knownAbsentOperatorProvider')] + public function testKnownAbsentKeyResolvesOperatorLocally(string $operator, mixed $value, bool $expected): void + { + $this->makeClient([self::flag('flag', [self::personFilter($operator, $value)])]); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['plan']); + + $this->assertSame($expected, $snapshot->getFlag('flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public static function knownAbsentOperatorProvider(): iterable + { + yield 'is_not_set' => ['is_not_set', null, true]; + yield 'is_set' => ['is_set', null, false]; + yield 'exact' => ['exact', 'pro', false]; + yield 'is_not' => ['is_not', 'pro', true]; + yield 'icontains' => ['icontains', 'pro', false]; + yield 'not_icontains' => ['not_icontains', 'pro', true]; + yield 'starts_with' => ['starts_with', 'pro', false]; + yield 'not_starts_with' => ['not_starts_with', 'pro', true]; + yield 'ends_with' => ['ends_with', 'pro', false]; + yield 'not_ends_with' => ['not_ends_with', 'pro', true]; + yield 'regex' => ['regex', '^pro', false]; + yield 'not_regex' => ['not_regex', '^pro', true]; + yield 'gt' => ['gt', '10', false]; + yield 'gte' => ['gte', '10', false]; + yield 'lt' => ['lt', '10', false]; + yield 'lte' => ['lte', '10', false]; + yield 'semver_eq' => ['semver_eq', '1.2.3', false]; + yield 'semver_neq' => ['semver_neq', '1.2.3', false]; + yield 'semver_tilde' => ['semver_tilde', '1.2.3', false]; + yield 'semver_caret' => ['semver_caret', '1.2.3', false]; + yield 'semver_wildcard' => ['semver_wildcard', '1.2.*', false]; + yield 'is_date_before' => ['is_date_before', '2025-01-01T10:00:00Z', false]; + yield 'is_date_after' => ['is_date_after', '2025-01-01T10:00:00Z', false]; + } + + #[DataProvider('unsupportedFilterProvider')] + public function testUnsupportedFilterOnKnownAbsentKeyStillFallsBack(string $operator, mixed $value): void + { + $this->makeClient([self::flag('flag', [self::personFilter($operator, $value)])]); + + $local = $this->client->evaluateFlags( + 'user-1', + onlyEvaluateLocally: true, + personPropertyKeysKnownAbsent: ['plan'] + ); + $this->assertSame( + ['flag' => UnresolvedFlagReason::UNSUPPORTED_DEFINITION], + $local->getUnresolvedFlags() + ); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['plan']); + $this->assertSame(self::REMOTE_VALUE, $snapshot->getFlag('flag')); + $this->assertCount(1, $this->flagsRequestBodies()); + } + + public static function unsupportedFilterProvider(): iterable + { + yield 'not_icontains_multi' => ['not_icontains_multi', ['pro']]; + yield 'icontains_multi' => ['icontains_multi', ['pro']]; + yield 'not_between' => ['not_between', [1, 2]]; + yield 'between' => ['between', [1, 2]]; + yield 'unknown operator' => ['future_operator', 'pro']; + yield 'malformed numeric filter' => ['gt', 'not-a-number']; + yield 'malformed semver filter' => ['semver_neq', 'not-a-version']; + yield 'malformed date filter' => ['is_date_before', 'not-a-date']; + yield 'non-portable regex' => ['not_regex', '(?<=a+)b']; + } + + public function testKnownAbsentKeyOverridesSuppliedValue(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('is_not_set', null)])]); + + $snapshot = $this->client->evaluateFlags( + 'user-1', + personProperties: ['plan' => 'pro'], + personPropertyKeysKnownAbsent: ['plan'] + ); + + $this->assertTrue($snapshot->getFlag('flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testKnownAbsentKeyOverridesInjectedDistinctId(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('is_not_set', null, 'distinct_id')])]); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['distinct_id']); + + $this->assertTrue($snapshot->getFlag('flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testUnlistedOmittedKeyStaysInconclusive(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('is_not_set', null)])]); + + $local = $this->client->evaluateFlags( + 'user-1', + onlyEvaluateLocally: true, + personPropertyKeysKnownAbsent: ['region'] + ); + $this->assertSame(['flag' => UnresolvedFlagReason::MISSING_CONTEXT], $local->getUnresolvedFlags()); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['region']); + $this->assertSame(self::REMOTE_VALUE, $snapshot->getFlag('flag')); + $this->assertCount(1, $this->flagsRequestBodies()); + } + + public function testPersonMetadataKeyIsIgnored(): void + { + $metadataKey = '__posthog_person_metadata__created_at'; + $this->makeClient([self::flag('flag', [self::personFilter('is_set', null, $metadataKey)])]); + + $snapshot = $this->client->evaluateFlags( + 'user-1', + personProperties: [$metadataKey => '2024-01-01T00:00:00Z'], + personPropertyKeysKnownAbsent: [$metadataKey] + ); + + $this->assertTrue($snapshot->getFlag('flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testGroupKnownAbsentKeyAppliesToItsGroupType(): void + { + $tierNotSet = [ + 'key' => 'tier', 'type' => 'group', 'group_type_index' => 0, 'operator' => 'is_not_set', 'value' => null, + ]; + $this->makeClient([self::flag('org-flag', [$tierNotSet], 0)], groupTypeMapping: ['0' => 'organization']); + $groups = ['organization' => 'org-1', 'project' => 'project-1']; + + $listed = $this->client->evaluateFlags( + 'user-1', + groups: $groups, + groupProperties: ['organization' => ['tier' => 'gold']], + groupPropertyKeysKnownAbsent: ['organization' => ['tier']] + ); + $this->assertTrue($listed->getFlag('org-flag')); + $this->assertSame([], $this->flagsRequestBodies()); + + $otherType = $this->client->evaluateFlags( + 'user-1', + groups: $groups, + onlyEvaluateLocally: true, + groupPropertyKeysKnownAbsent: ['project' => ['tier']] + ); + $this->assertSame(['org-flag' => UnresolvedFlagReason::MISSING_CONTEXT], $otherType->getUnresolvedFlags()); + + $personListed = $this->client->evaluateFlags( + 'user-1', + groups: $groups, + onlyEvaluateLocally: true, + personPropertyKeysKnownAbsent: ['tier'] + ); + $this->assertSame(['org-flag' => UnresolvedFlagReason::MISSING_CONTEXT], $personListed->getUnresolvedFlags()); + } + + public function testGroupKnownAbsentKeyOverridesInjectedGroupKey(): void + { + $groupKeyNotSet = [ + 'key' => '$group_key', 'type' => 'group', 'group_type_index' => 0, + 'operator' => 'is_not_set', 'value' => null, + ]; + $this->makeClient([self::flag('org-flag', [$groupKeyNotSet], 0)], groupTypeMapping: ['0' => 'organization']); + + $snapshot = $this->client->evaluateFlags( + 'user-1', + groups: ['organization' => 'org-1'], + groupPropertyKeysKnownAbsent: ['organization' => ['$group_key']] + ); + + $this->assertTrue($snapshot->getFlag('org-flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testMixedTargetingConditionUsesTheConditionGroupTypeKeys(): void + { + $flag = [ + 'id' => 1, + 'key' => 'mixed-flag', + 'active' => true, + 'filters' => ['groups' => [[ + 'aggregation_group_type_index' => 0, + 'properties' => [[ + 'key' => 'tier', 'type' => 'group', 'group_type_index' => 0, + 'operator' => 'is_not_set', 'value' => null, + ]], + 'rollout_percentage' => 100, + ]]], + ]; + $this->makeClient([$flag], groupTypeMapping: ['0' => 'organization']); + + $snapshot = $this->client->evaluateFlags( + 'user-1', + groups: ['organization' => 'org-1'], + groupProperties: ['organization' => ['tier' => 'gold']], + groupPropertyKeysKnownAbsent: ['organization' => ['tier']] + ); + $this->assertTrue($snapshot->getFlag('mixed-flag')); + $this->assertSame([], $this->flagsRequestBodies()); + + $personListed = $this->client->evaluateFlags( + 'user-1', + groups: ['organization' => 'org-1'], + personPropertyKeysKnownAbsent: ['tier'] + ); + $this->assertSame(self::REMOTE_VALUE, $personListed->getFlag('mixed-flag')); + $this->assertCount(1, $this->flagsRequestBodies()); + } + + #[DataProvider('cohortNegationProvider')] + public function testDynamicCohortLeafAppliesNegationAfterKnownAbsence( + string $operator, + bool $negation, + bool $expected + ): void { + $leaf = self::personFilter($operator) + ['negation' => $negation]; + $this->makeClient( + [self::flag('cohort-flag', [['key' => 'id', 'type' => 'cohort', 'value' => 1]])], + cohorts: ['1' => ['type' => 'AND', 'values' => [$leaf]]] + ); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['plan']); + + $this->assertSame($expected, $snapshot->getFlag('cohort-flag')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public static function cohortNegationProvider(): iterable + { + yield 'exact' => ['exact', false, false]; + yield 'negated exact' => ['exact', true, true]; + yield 'is_not' => ['is_not', false, true]; + yield 'negated is_not' => ['is_not', true, false]; + } + + #[DataProvider('cohortUnsupportedLeafProvider')] + public function testDynamicCohortUnsupportedLeafOnKnownAbsentKeyFallsBack(bool $negation): void + { + $leaf = self::personFilter('not_between', [1, 2]) + ['negation' => $negation]; + $this->makeClient( + [self::flag('cohort-flag', [['key' => 'id', 'type' => 'cohort', 'value' => 1]])], + cohorts: ['1' => ['type' => 'AND', 'values' => [$leaf]]] + ); + + $local = $this->client->evaluateFlags( + 'user-1', + onlyEvaluateLocally: true, + personPropertyKeysKnownAbsent: ['plan'] + ); + $this->assertSame( + ['cohort-flag' => UnresolvedFlagReason::UNSUPPORTED_DEFINITION], + $local->getUnresolvedFlags() + ); + + $snapshot = $this->client->evaluateFlags('user-1', personPropertyKeysKnownAbsent: ['plan']); + $this->assertSame(self::REMOTE_VALUE, $snapshot->getFlag('cohort-flag')); + $this->assertCount(1, $this->flagsRequestBodies()); + } + + public static function cohortUnsupportedLeafProvider(): iterable + { + yield 'not_between' => [false]; + yield 'negated not_between' => [true]; + } + + public function testFlagDependencyUsesKnownAbsentKeys(): void + { + $dependency = self::flag('profile-incomplete', [self::personFilter('is_not_set', null)]); + $dependent = self::flag('dependent', [[ + 'key' => 'profile-incomplete', + 'type' => 'flag', + 'value' => true, + 'operator' => 'flag_evaluates_to', + 'dependency_chain' => ['profile-incomplete'], + ]]); + $this->makeClient([$dependency, $dependent]); + + $snapshot = $this->client->evaluateFlags( + 'user-1', + personProperties: ['plan' => 'pro'], + personPropertyKeysKnownAbsent: ['plan'] + ); + + $this->assertTrue($snapshot->getFlag('dependent')); + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testRemoteFallbackSendsKnownAbsentKeys(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + + $this->client->evaluateFlags( + 'user-1', + personPropertyKeysKnownAbsent: ['plan'], + groupPropertyKeysKnownAbsent: ['organization' => ['tier'], 'project' => []] + ); + + $bodies = $this->flagsRequestBodies(); + $this->assertCount(1, $bodies); + $this->assertSame(['plan'], $bodies[0]['person_property_keys_known_absent']); + $this->assertSame(['organization' => ['tier']], $bodies[0]['group_property_keys_known_absent']); + } + + public function testRemoteRequestOmitsKnownAbsentFieldsWhenNotProvided(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + + $this->client->evaluateFlags('user-1'); + $this->client->evaluateFlags( + 'user-1', + personPropertyKeysKnownAbsent: [], + groupPropertyKeysKnownAbsent: ['organization' => []] + ); + + $bodies = $this->flagsRequestBodies(); + $this->assertCount(2, $bodies); + foreach ($bodies as $body) { + $this->assertArrayNotHasKey('person_property_keys_known_absent', $body); + $this->assertArrayNotHasKey('group_property_keys_known_absent', $body); + } + } + + #[IgnoreDeprecations] + public function testLegacyFlagMethodsAcceptKnownAbsentKeys(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('is_not_set', null)])]); + $absent = ['plan']; + + $this->assertTrue(PostHog::isFeatureEnabled('flag', 'user-1', personPropertyKeysKnownAbsent: $absent)); + $this->assertTrue(PostHog::getFeatureFlag('flag', 'user-1', personPropertyKeysKnownAbsent: $absent)); + $this->assertTrue( + PostHog::getFeatureFlagResult('flag', 'user-1', personPropertyKeysKnownAbsent: $absent)->getValue() + ); + $this->assertNull(PostHog::getFeatureFlagPayload('flag', 'user-1', personPropertyKeysKnownAbsent: $absent)); + $this->assertSame( + ['flag' => true], + PostHog::getAllFlags('user-1', personPropertyKeysKnownAbsent: $absent) + ); + $this->assertTrue( + PostHog::evaluateFlags('user-1', personPropertyKeysKnownAbsent: $absent)->getFlag('flag') + ); + $this->assertSame([], $this->flagsRequestBodies()); + } + + #[IgnoreDeprecations] + public function testLegacyRemoteFallbackSendsKnownAbsentKeys(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + + $this->client->getFeatureFlag('flag', 'user-1', personPropertyKeysKnownAbsent: ['plan']); + $this->client->getAllFlags('user-1', personPropertyKeysKnownAbsent: ['plan']); + + $bodies = $this->flagsRequestBodies(); + $this->assertCount(2, $bodies); + foreach ($bodies as $body) { + $this->assertSame(['plan'], $body['person_property_keys_known_absent']); + } + } + + public function testThousandKnownAbsentKeysAreAccepted(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + $keys = array_fill(0, 1000, 'plan'); + + $this->client->evaluateFlags( + 'user-1', + personPropertyKeysKnownAbsent: $keys, + groupPropertyKeysKnownAbsent: ['organization' => $keys, 'project' => $keys] + ); + + $bodies = $this->flagsRequestBodies(); + $this->assertCount(1, $bodies); + $this->assertCount(1000, $bodies[0]['person_property_keys_known_absent']); + $this->assertCount(1000, $bodies[0]['group_property_keys_known_absent']['project']); + } + + #[DataProvider('invalidKnownAbsentKeysProvider')] + public function testInvalidKnownAbsentKeysFailWithoutRequest(?array $personKeys, ?array $groupKeys): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + + try { + $this->client->evaluateFlags( + 'user-1', + personPropertyKeysKnownAbsent: $personKeys, + groupPropertyKeysKnownAbsent: $groupKeys + ); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString('KnownAbsent', $e->getMessage()); + } + + $this->assertSame([], $this->flagsRequestBodies()); + } + + public static function invalidKnownAbsentKeysProvider(): iterable + { + yield 'person keys over the limit, counting duplicates' => [array_fill(0, 1001, 'plan'), null]; + yield 'group keys over the limit for one group type' => [null, ['organization' => array_fill(0, 1001, 'tier')]]; + yield 'non-string person key' => [[1], null]; + yield 'group keys not a list' => [null, ['organization' => 'tier']]; + } + + #[IgnoreDeprecations] + public function testLegacyMethodsRejectKnownAbsentKeysOverTheLimit(): void + { + $this->makeClient([self::flag('flag', [self::personFilter('exact', 'pro', 'region')])]); + $keys = array_fill(0, 1001, 'plan'); + + foreach ( + [ + fn () => $this->client->getFeatureFlag('flag', 'user-1', personPropertyKeysKnownAbsent: $keys), + fn () => $this->client->getAllFlags('user-1', personPropertyKeysKnownAbsent: $keys), + fn () => $this->client->flags('user-1', personPropertyKeysKnownAbsent: $keys), + ] as $call + ) { + try { + $call(); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException) { + } + } + + $this->assertSame([], $this->flagsRequestBodies()); + } + + public function testMatchPropertyTreatsListedKeyAsAbsent(): void + { + $this->assertTrue(FeatureFlag::matchProperty( + self::personFilter('is_not_set', null), + ['plan' => 'pro'], + 1, + ['plan' => true] + )); + $this->assertFalse(FeatureFlag::matchProperty( + self::personFilter('exact', 'pro'), + ['plan' => 'pro'], + 1, + ['plan' => true] + )); + + $this->expectException(InconclusiveMatchException::class); + FeatureFlag::matchProperty(self::personFilter('is_not_set', null), [], 1, ['region' => true]); + } +} diff --git a/test/JsonEncoderTest.php b/test/JsonEncoderTest.php index e8e641bf..e059314b 100644 --- a/test/JsonEncoderTest.php +++ b/test/JsonEncoderTest.php @@ -734,10 +734,12 @@ public function jsonSerialize(): mixed }; self::assertFalse(json_encode(["\xB1" => $serializer])); self::assertSame(JSON_ERROR_UTF8, json_last_error()); - self::assertSame(1, $serializer->calls); + // PHP 8.4.28 and 8.5.13 stopped calling jsonSerialize() before rejecting a malformed key. + $nativeCalls = $serializer->calls; + self::assertContains($nativeCalls, [0, 1]); self::assertFalse(JsonEncoder::encode(["\xB1" => $serializer])); self::assertSame(JSON_ERROR_UTF8, json_last_error()); - self::assertSame(2, $serializer->calls); + self::assertSame(2 * $nativeCalls, $serializer->calls); self::assertSame('7', JsonEncoder::encode(7)); self::assertSame(JSON_ERROR_NONE, json_last_error()); }