Repository navigation
feat(server): support known-absent property keys in local evaluation - #993
marandaneto wants to merge 26 commits into
Conversation
posthog-android Compliance ReportDate: 2026-11-26T09:21:56.344422+00:00 ✅ All Tests Passed!243/243 tests passed Capture_V1 Tests✅ 111/111 tests passed View Details
Capture_Ai_V1 Tests✅ 115/115 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
dustinbyrne
left a comment
There was a problem hiding this comment.
The /flags wire format, 1000-key validation cap, known-absent operator table, FeatureFlagCacheKey isolation, and binary-compatible PostHogApi.flags overload look solid. Before approval, there are a few items to address inline:
- Local evaluation scoping (
Breaking):computeFlagLocallythreads oneknownAbsentKeysset acrossperson_metadata(created_at), dynamic cohorts inside group flags, and cross-aggregation flag dependencies, turning safe/flagsfallback into wrong local results. - Java
nullcollection elements (Concern):Arrays.asList("plan", null)crashesevaluateFlagswith an unhandledNullPointerException, andgroupPropertyKeysKnownAbsentserializesnullinto/flags, which the backend rejects with HTTP 400. - Test coverage (
Concern): the newly addedsendFeatureFlagCalledWithKnownAbsent,failedguard, and validgetFeatureFlagPayloadpaths inPostHog.ktare currently unexecuted by tests. - Spec/backend alignment (
Question) and minor KDoc/rebase suggestions inline.
Also note that this branch currently has merge conflicts with main (after posthog-android 4.0 / posthog 7.0 landed) across .github/workflows/sdk-compliance-tests.yml, sdk_compliance_adapter/docker-compose.yml, sdk_compliance_adapter/src/main/kotlin/com/posthog/compliance/ComplianceAdapter.kt, and posthog/api/posthog.api.
Follow-ups (outside this PR):
- PostHog/posthog.com (Client Libraries / Docs): update
contents/docs/feature-flags/local-evaluation/index.mdx(which still statesis_not_setcannot evaluate locally) andcontents/docs/libraries/java/index.mdxonce this ships. - PostHog/posthog (Feature Flags):
rust/feature-flags/src/properties/property_matching.rs(OperatorType::NotRegex) returnstruefor a missing/known-absent key before checking regex validity, which diverges fromPostHog/sdk-specs#233'sfalserule.
AI-assisted review.
…nt-property-keys # Conflicts: # .github/workflows/sdk-compliance-tests.yml # posthog/api/posthog.api # sdk_compliance_adapter/docker-compose.yml # sdk_compliance_adapter/src/main/kotlin/com/posthog/compliance/ComplianceAdapter.kt
dustinbyrne
left a comment
There was a problem hiding this comment.
The follow-up commits cleanly resolved the merge conflicts (ff3d0585/0da519fc), the sdk-specs#233/#239 value-parsing alignment (8c6857fe/43de3307), the person_metadata/cohort/cross-aggregation scoping (dd964eb1), and Java null list elements (260c7902). Before approval, a few items remain:
- New inline comments (3
Concern, 1Suggestion):KnownAbsentPropertyKeys.ofstill strips__posthog_person_metadata__*before/flagsfallback, which contradicts the mergedPostHog/sdk-specs(44fe27ab) wire-forwarding requirement.- The retained
sdk-test-harnessbump (1.26.0->1.34.0) introduces a failingCapture_V1compliance test (242/243:request_size.batches_close_before_byte_target) while running 0 known-absent tests. KnownAbsentKeyScope.isKnownAbsentignoresgroup_type_indexontype = "group"filters, amplifying mixed-targeting mismatch across group types.- Optional
Suggestionon guardingnullgroup-type map keys inKnownAbsentPropertyKeys.inputError.
- Still-open threads from the earlier review (not duplicated inline):
Concern: untested$feature_flag_called,failedguard, and validgetFeatureFlagPayloadpaths.Suggestion: stale KDoc onPostHogEvaluateFlagsOptions.kt:6andPostHogInterface.kt.Suggestion:"posthog": minorvspatchin.changeset/quiet-keys-absent.md(theComplianceAdapter.ktpart of that note is now resolved).
Follow-ups (outside this PR):
- PostHog/posthog.com (Client Libraries / Docs): update
contents/docs/feature-flags/local-evaluation/index.mdxandcontents/docs/libraries/java/index.mdxonce released. - Client Libraries: opt
sdk_compliance_adapterintofeature_flags_local_evaluation_v1/feature_flags_known_absent_v1when ready to run the shared known-absent harness suite in CI.
AI-assisted review.
…nt-property-keys # Conflicts: # .github/workflows/sdk-compliance-tests.yml
…nt-property-keys # Conflicts: # posthog-server/src/main/java/com/posthog/server/internal/FlagEvaluator.kt
…ith known-absent keys
ioannisj
left a comment
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
No findings. I went through the known-absent handling in local evaluation, the per-listing cache keys, the /flags fallback body and the 1000-key limit against PostHog/sdk-specs#233, plus the newer commits: group_type_index scoping for group keys, the __posthog_person_metadata__ keys forwarded to /flags, the null group type guard, dependencies evaluated in their own context, and empty group keys counting as no group. It all lines up with the spec and posthog-js.
…nt-property-keys # Conflicts: # posthog-server/src/main/java/com/posthog/server/internal/FlagEvaluator.kt # posthog-server/src/main/java/com/posthog/server/internal/PostHogFeatureFlags.kt
This SDK has no per-condition aggregation, so every condition of a group flag reads the flag-level group and the flag-level false for a missing or empty group key stays correct. Tests cover the mixed flag (person condition decides) and the pure group flag (false, no /flags request). Holdout: a group flag with a holdout above 0% and no usable group key is now inconclusive with missing_context, checked before the flag-level false. The flags service buckets the holdout on the missing key, which can't be reproduced locally. Only holdout.exclusion_percentage is parsed; a missing or malformed holdout counts as none.
💡 Motivation and Context
During local evaluation, the server SDK treats a property key that the caller left out as unknown. A filter on that key can't be decided locally, so the SDK calls
/flagsinstead. A caller has no way to say "this person definitely doesn't haveplan". This causes extra remote calls. It also means local results and the/flagsfallback could disagree about missing properties.This PR adds an optional list of property keys the caller knows are absent. It follows the cross-SDK spec in PostHog/sdk-specs#233.
New public input
PostHogEvaluateFlagsOptions,PostHogFeatureFlagOptionsandPostHogFeatureFlagResultOptionseach get two new optional fields and builder methods:personPropertyKeysKnownAbsent, a list of person property keys.groupPropertyKeysKnownAbsent, a map from group type name to a list of group property keys.These options already feed
evaluateFlags,getFeatureFlag,isFeatureEnabled,getFeatureFlagPayloadandgetFeatureFlagResult. When nothing is listed, every call behaves exactly as before.PostHogCaptureOptionsdoes not get the new fields. To attach flags evaluated with known-absent keys to an event, evaluate a snapshot with these options and pass it tocapture.Local evaluation behavior
/flagsfallback.is_not_set,is_not,not_icontains,not_starts_with,not_ends_withandnot_regexmatch.is_setand every other supported operator do not match. This includesexact,icontains,regex, the numeric operators, allsemver_*operators and the date operators.distinct_idin person properties.not_regexwith an invalid or non-portable pattern such as"["or\p{L}matches,regexwith that pattern does not, andgt,semver_*oris_date_*with a malformed operand such as"not-a-number"do not match. Malformed values on a key that is not listed behave as before.unsupported_definitionand fall back to/flags: operators the SDK doesn't support locally (icontains_multi,not_icontains_multi,between,not_between, unknown operators), even when the key is listed, and an omitted or JSON null condition value on an operator that needs one.FlagEvaluatorTest.testKnownAbsentCohortLeafChecksOperatorSupportBeforeTheTableandPostHogKnownAbsentPropertyKeysTest("an unsupported operator in a cohort leaf on a listed key falls back before known absence") cover a cohort leafplan not_between [1, 2]on a listed key, with and withoutnegation, and check that it stays unresolved withunsupported_definitionand falls back to/flags./flags, per docs(flags): resolve known-absent keys without reading the condition value sdk-specs#239.is_setandis_not_setkeep their known-absent result whatever the value is.__posthog_person_metadata__are ignored.personfilters, group keys only resolvegroupfilters in a flag aggregated on that same group type,person_metadatafilters never resolve from a listing and fall back as before, and a group filter withoutgroup_type_indexreads the flag's group type and its listed keys. To tellpersonfromperson_metadata, coreFlagPropertygets an internalrawTypefield (it is@PostHogInternal) that keeps the wire"type". Broaderperson_metadatahandling is tracked in fix(server): don't match person_metadata filters against person properties #998.negationis applied. Static cohort membership and holdouts are unchanged.group_type_indexread the condition's group type, per docs(flags): evaluate flag dependencies in their own context sdk-specs#250. A dependency is evaluated exactly as if it were evaluated directly with the same top-level inputs: its own aggregation, properties, listed keys and bucketing identifier (the group key for a group-aggregated dependency). A group-aggregated dependency whose group isn't passed skips its group conditions, like a directly requested flag, so it isfalsewith no fallback unless it has a holdout (see below). This also fixes local results without known-absent keys: before, a dependency always read the parent's identifier and properties./flagsdoes (docs(flags): evaluate flag dependencies in their own context sdk-specs#250): each condition aggregated on that group type is skipped, so a flag whose conditions all use it isfalselocally with no/flagsfallback, directly or as a dependency, and a person condition on the same flag still decides. This SDK has no per-conditionaggregation_group_type_index(mixed targeting), so every condition of a group flag uses the flag's group type; that gap predates this PR. A null key from a Java caller already behaved this way. The public group maps takeStringvalues, so booleans, lists and maps can't be passed./flagsrequest bodyWhen a call with listed keys falls back to
/flags, the request body includesperson_property_keys_known_absent(a list of strings) andgroup_property_keys_known_absent(an object from group type to a list of strings). A field is left out when the caller didn't provide it or it is empty. Calls without listed keys send the same body as before.To support this,
PostHogApi.flagsin the coreposthogmodule gets a new overload that takes the two lists. The existingflagsmethod keeps its JVM signature, so aposthog-serverbuilt against an older core still works. The Android client does not use the new overload.Over 1000 keys
Each list can hold at most 1000 keys. Duplicates count, and the limit applies to each group type separately. If a list is over the limit, the SDK logs a warning and evaluates nothing. It sends no request and never truncates the list. The call returns its normal "unavailable" result.
evaluateFlagsreturns an empty snapshot.getFeatureFlag,getFeatureFlagPayloadandisFeatureEnabledreturn the default value.getFeatureFlagResultreturnsnull.A
nullelement in the person list or in any group list (possible from Java callers) is rejected the same way: the SDK logs a warning, evaluates nothing, sends no request and returns the unavailable result.Not included
$feature_enrollment/<flag key>as known absent. Only posthog-python evaluates feature enrollment locally. Other SDKs are tracked in Support local feature enrollment evaluation across server SDKs posthog#138580.icontains_multi,not_icontains_multi,betweenandnot_betweenoperators. This SDK doesn't support them locally yet, so they keep falling back to/flags. They are tracked in Support icontains_multi and between operators in SDK local flag evaluation posthog#138581.feature_flags_local_evaluation_v1, so the harness wouldn't run the new suite against it.💚 How did you test it?
New tests:
FlagEvaluatorTestcovers the result for every operator on a listed key, an omitted key that isn't listed, unsupported operators and omitted values on a listed key, malformed present values on a listed key that resolve without being read, cohort negation, flag dependencies, the metadata prefix and empty lists, and the 1000-key limit with duplicates.PostHogKnownAbsentPropertyKeysTestruns the full client against MockWebServer. It covers a listed key overriding a supplied value with no/flagscall, overriding thedistinct_idthe SDK adds, group-type scoping, the/flagsbody with and without listed keys, separate caching for getters, fallback for an unsupported operator, and the over-limit behavior for every entry point.PostHogFlagsRequestTestchecks that the body includes the new fields when provided and leaves them out when they are null or empty.Commands run locally with JDK 17:
./gradlew :posthog:test :posthog-server:test spotlessCheck :posthog:apiCheck :posthog-server:apiCheckpassed.CI now runs SDK test harness 1.34.0. Its
Capture_V1testrequest_size.batches_close_before_byte_targetfailed because the adapter's/captureroute ignoredpad_properties_to_bytes. The route now pads properties the same way/capture_aidoes, and all 243 harness tests passed locally withdocker composeinsdk_compliance_adapter. The newnon_utc_event_timestamp_is_converted_to_utctest exposed that the adapter ignored thetimestampon/capture, so the adapter now passes it tocapture. The known-absent suite doesn't run because the adapter doesn't declarefeature_flags_local_evaluation_v1orfeature_flags_known_absent_v1.Omitted and null condition values on a listed key (PostHog/sdk-specs#239):
PostHogKnownAbsentPropertyKeysTestadds "an omitted or null condition value on a listed key stays inconclusive and falls back to flags" (is_notwith novalue, andis_not,exactandgtwith"value": null; each is unresolved withunsupported_definitionin local-only mode and falls back to/flags) and "is_set and is_not_set with a null condition value on a listed key keep their known-absent result". Both passed on their first run with no production change../gradlew spotlessCheck :posthog:apiCheck :posthog-server:apiCheck :posthog-server:test :posthog:testpassed with 2048 tests and 0 failures after mergingmain.Resolving a listed key without reading the condition value (PostHog/sdk-specs#239):
PostHogKnownAbsentPropertyKeysTestadds "a listed key resolves without reading a present condition value". It coversnot_regexandregexwith"["and\p{L},gt,gte,ltandltewith"not-a-number",semver_gt,semver_eq,semver_tilde,semver_caretandsemver_wildcardwith"not-a-version", andis_date_beforeandis_date_afterwith"not-a-date". Each case runs in local-only mode and throughgetFeatureFlag, and expects no/flagsrequest. Before the fix, 14 of the 15 cases failed. Onlyregex "["already returned false. All 15 pass after the fix. The same file adds "an operator the SDK does not implement on a listed key stays unsupported and falls back to flags" foricontains_multi,not_icontains_multi,between,not_betweenand an unknown operator. That test passed before and after the fix.FlagEvaluatorTest.testKnownAbsentKeyDoesNotParseAPresentConditionValuereplaces the old assertions that malformed values stay unresolved and that an invalidnot_regexpattern does not match. It checks each case withnegationtrue and false../gradlew :posthog-server:testpassed with 712 tests and 0 failures, andspotlessCheck :posthog-server:apiCheckpassed.Type scoping and input check:
PostHogKnownAbsentPropertyKeysTestadds "a listed person_metadata key never resolves from the listing" (flag condition and cohort leaf,is_not_setandis_date_before), "a person listing does not resolve a group filter", "a group listing does not resolve a person filter or person cohort leaf on a group flag" and "a flag dependency with a different aggregation does not use the parent's listing" (both directions). All four failed before the fix and pass after it. "a flag dependency with the same aggregation uses the listing" and corePostHogLocalEvaluationModelsTest.testFlagPropertyRawTypeSurvivesASerializerRoundTrippassed before and after as regression tests. "a null key from a Java caller returns the unavailable result without evaluating or sending a request" failed before the fix with an NPE instartsWithand passes after it../gradlew spotlessCheck :posthog:apiCheck :posthog-server:apiCheck :posthog:test :posthog-server:testpassed with JDK 17 (1340 and 718 tests, 0 failures).Dependency context and no-index group filters (PostHog/sdk-specs#250), in
PostHogKnownAbsentPropertyKeysTest:region=us, groupregion=eu; the org parent and the person child are both false with no/flagsrequest): red before (the child was true), green after.tier): red before (the child was true), green after.exact "enterprise"false,is_not_settrue with a suppliedtier="enterprise"): already green before, kept as a regression test.FlagEvaluatorTest.testFlagDependencyEvaluatesWithTheSameKnownAbsentKeysis renamed totestFlagDependencyReadsTheKnownAbsentKeysOfTheTopLevelContextand now goes through the top-level context../gradlew spotlessCheck apiCheck :posthog-server:check :posthog-server-openfeature:check :posthog:testpassed with JDK 17 (723 server tests, 0 failures).Review follow-ups, in
PostHogKnownAbsentPropertyKeysTestunless noted:__posthog_person_metadata__prefix are now sent to/flagsunchanged and only ignored in local matching. "remote fallback sends the listed keys and omits them when none were provided" now expects[plan, __posthog_person_metadata__created_at]. It failed before the fix, along with the new test "a listed person-metadata prefixed key is forwarded unchanged but never resolves a person filter locally" andFlagEvaluatorTest.testKnownAbsentPropertyKeysKeepPersonMetadataKeysAndDropEmptyLists. All three pass after it.PostHogLocalEvaluationModelsTest.testFlagPropertyRawTypeAndGroupTypeIndexSurviveASerializerRoundTripchecks that the index survives the definitions cache.sendFeatureFlagEvent(false)is respected, the event metadata, and that afailedentry returns the default value without reporting it as the response. This test passed when it was added../gradlew spotlessCheck apiCheck :posthog:test :posthog-server:test :posthog-server-openfeature:test :posthog-android:testDebugUnitTestpassed with JDK 17.Group holdout without a key (PostHog/sdk-specs#250): a group flag with a holdout above 0% and no usable group key is now inconclusive with
missing_context(falls back to/flags, unresolved in local-only mode) instead offalse;PostHogUnusableGroupKeyTest"a group flag with a holdout and an unusable group key is missing context" was red before and passes now, and a 0% holdout or a usable key is unchanged.Unusable group keys (PostHog/sdk-specs#250): the new
PostHogUnusableGroupKeyTestruns each case for""and a Javanullkey (direct flag in local-only mode and through the getters, a mixed flag, a group dependency,evaluateFlagsandcapture(appendFeatureFlags = true)with no/flagscall, plus usable-key bucketing and a usable key without properties staying inconclusive). Before the fix, the four unusable-key tests failed on""; all 6 pass after it, and./gradlew spotlessCheck :posthog-server:apiCheck :posthog-server:build :posthog-server-openfeature:testpassed with JDK 17.Not run locally: Android instrumented tests and the Compose survey tests.
📝 Checklist
If releasing new changes
pnpm changesetto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Pi coding agent (Claude) implemented this from the spec in PostHog/sdk-specs#233 as part of the same change across several SDKs. Before pushing, an automated review ran with a different model,
openai-codex/gpt-6.2-astra.PostHogApi.flagschanged its JVM signature. Aposthog-serverbuilt against an older core would fail at runtime if only core was upgraded. The old signature now stays, and the new parameters are in a separate overload.$feature_flag_error: unknown_errorin$feature_flag_called. A local check showedmainalready does this for any getter that resolves locally on a cold cache, with no listed keys. The new code path matches the existing behavior. A fix belongs in a separate PR.The new options are on all three options classes so that the deprecated per-flag getters stay consistent with
evaluateFlags.