Repository navigation
feat(flags): support known-absent property keys in local evaluation - #1280
marandaneto wants to merge 23 commits into
Conversation
SDK performance: posthog-python46 changes worth reviewing: 46 observed regressions. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate.
Showing the 12 largest flagged changes; 34 more are in all results. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
PR overviewThe PR adds support for known-absent property keys in local feature-flag evaluation, including separate cache entries for different property-key listings. One issue remains open: listing-specific cache entries can grow without bound for a single flag and user, and expired entries are retained within the current definition generation. If an application derives these listings from request data, an attacker could drive host-memory growth; exploitability depends on how the application supplies those lists. No issues have been addressed yet. Open issues (1)
Fixed/addressed: 0 · PR risk: 4/10 Reviews |
dustinbyrne
left a comment
There was a problem hiding this comment.
Overall the additive keyword-only API, bounded iterator validation, sentinel isolation, and compliance adapter wiring look solid. Left three inline items to address before approval (one Breaking omitted-condition-value bug on negated operators, plus two Concern gaps around eager condition-value validation on known-absent keys and type: "person_metadata" dynamic cohort filters) and one small Suggestion on Mapping/bytearray validation.
Notes on existing comments & follow-ups:
- Suggestion (benchmark allocation delta — addressing the SDK performance report): A base-vs-head
tracemalloccheck confirms zero memory leak (net_delta=416Bon both base and head). The ~+0.88 KiB/op short-lived allocation increase on the default(None, None)path comes from unconditionally calling_validate_known_absent_keys(None, None), allocatinggroup_properties or {}inClient._properties_for_local_evaluation(posthog/client.py:6268-6283), and calling_mark_known_absent_properties. Remote/fallback calls also re-run_validate_known_absent_keysa second time inside_get_flags_decision(posthog/client.py:2341-2343). Consider short-circuiting when both known-absent arguments areNoneon the local-eval hot path and accepting pre-validated lists/dicts in internal_get_flags_decision(matchingAsyncClient._get_flags_decision). - Follow-up (
PostHog/posthog.com): Once this ships,contents/docs/feature-flags/local-evaluation/index.mdx(lines 365–367, which currently stateis_not_setand early-access enrollment cannot be evaluated locally) andcontents/docs/integrate/feature-flags-code/_snippets/feature-flags-code-api.mdxwill need a follow-up docs update.
AI-assisted review.
…nt-property-keys # Conflicts: # .github/workflows/sdk-compliance.yml
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for addressing all four prior threads across b142a176..98124ab5 — omitted/None condition values, skipping condition-value validation on known-absent keys, person_metadata isolation from known-absent listings, duplicate-key marking, and Mapping/bytearray input checks all look good now.
The filter-type scoping change in b6c0dd3b introduced two issues on group_property_keys_known_absent to address before approval (left inline): one Breaking cold-start lazy-load / snapshot-tearing bug in Client._properties_for_local_evaluation, and one Concern where legacy type: "group" / $group_key filters omitting group_type_index diverge from Rust /flags.
Notes on existing comments & follow-ups:
- Suggestion (hot-path overhead — updating the prior note on the SDK performance report): Comparing
46a88b5c→98124ab5still shows zero memory leak (tracemallocnet delta ~1.5 KiB on head vs ~1.6 KiB on base), while the CI benchmark now flags 14 regressions (+5.9–6.7% short-lived allocated memory/op onflags-single, +5.2–5.4% CPU/time onEvaluate a flag (no match)andEvaluate all 10 flags). Alongside short-circuiting(None, None)before_validate_known_absent_keys/_mark_known_absent_propertiesand avoiding re-validation in internal_get_flags_decision, consider inlining_supplied_valuein_match_property_value(posthog/feature_flags.py:1629) with a singletype(override_value) is _KnownAbsentcheck so the non-known-absent hot loop pays neither an extra function call nor a secondisinstancecheck per property. - Follow-up (
PostHog/posthog.com): Post-release docs updates noted in the prior review remain unchanged.
AI-assisted review.
Build the local evaluation property maps after definitions load, from the same snapshot that evaluates the flags, so a cold-start client marks group keys with their group type index.
| self.flag_cache.set_cached_flag( | ||
| distinct_id, key, cached_flag_result, local_definition_version | ||
| distinct_id, | ||
| cache_flag_key, |
There was a problem hiding this comment.
Medium: Bound listing-specific cache entries
cache_flag_key creates a separate entry for every listing, but FlagCache bounds only distinct IDs and does not prune expired entries within the current definition generation; checking the key/cache functions confirmed that 2,000 different one-key listings retain 2,000 entries for one flag/user even with size=1, including after expiry. If an application derives these lists from request data, this permits unbounded host-memory growth, so cap cached variants per user or total entries and evict expired entries while preserving listing isolation.
💡 Motivation and Context
Closes the Python part of PostHog/posthog#88947.
Local flag evaluation can't tell a missing property apart from one the caller didn't pass. If a key is left out of
person_properties, the condition that reads it is inconclusive and the SDK asks/flags. Callers had no way to say "this person definitely doesn't haveplan". So a flag withplan is_not_setcould never resolve locally. The local result and the/flagsresult could also disagree.The flags service now accepts known-absent keys (PostHog/posthog#138239). This PR adds the same input to the SDK, following the cross-SDK spec in PostHog/sdk-specs#233.
New input
Two optional keyword arguments:
person_property_keys_known_absent: a collection of person property keys.group_property_keys_known_absent: a mapping from group type to a collection of group property keys.They are accepted by
evaluate_flags,get_feature_flag,get_feature_flag_result,feature_enabled,get_feature_flag_payload,get_all_flags,get_all_flags_and_payloads,get_feature_variants,get_feature_payloads,get_feature_flags_and_payloads,get_flags_decision, and the module-level wrappers. They also work incapture(send_feature_flags={...})and inAsyncClient.evaluate_flags. Existing signatures don't change.Local evaluation
distinct_idand$group_key.is_not_set,is_not,not_icontains,not_starts_with,not_ends_withandnot_regexmatch. Every other supported operator does not match. That includesis_set,exact,gt, allsemver_*operators and the date operators. The result is final, with no/flagsrequest./flagseven when the key is listed.test_cohort_leaf_unsupported_operator_falls_back_before_known_absencecovers a cohort leafplan not_between [1, 2]with and withoutnegation./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 apply togroupfilters of their own group type,person_metadatafilters (such as acreated_atcohort leaf) never resolve from a listing and read the supplied value instead. A group filter withoutgroup_type_indexreads the condition's group type.negation. Flag dependencies are evaluated in their own context with the same listed keys (see below).$feature_enrollment/<flag key>means the person is not enrolled. Evaluation then continues to holdouts and release conditions instead of returning early or falling back. Python is the only SDK with local enrollment handling.Flag dependencies and group filters without an index
Per PostHog/sdk-specs#250, a flag dependency is now evaluated in its own context: the referenced flag is evaluated as if it were evaluated directly with the same distinct id, groups, person and group properties, known-absent keys and device id, using its own aggregation, properties and bucketing value, and a group-aggregated dependency whose group isn't supplied resolves as
false. Atype: "group"filter withoutgroup_type_indexnow reads the condition's group type, including its known-absent keys, as the flags service does. This also fixes local results without known-absent keys: before, a person flag that depended on a group flag evaluated the group flag with the person's properties and distinct id, so it could differ from/flags, and a group dependency without its group fell back to/flags.Per PostHog/sdk-specs#250 a usable group key is a non-empty string or a number. An empty-string,
None, boolean, list or dict group key counts as no group key: a flag aggregated on that group type resolves asfalselocally with no/flagsrequest (also as a dependency), and a mixed flag skips its conditions on that group type. Before, an empty string was used as the bucketing key and the other kinds fell back to/flags./flagsrequest bodyWhen the SDK calls
/flagsand the caller listed keys, the body includesperson_property_keys_known_absent: [...]andgroup_property_keys_known_absent: {"<group type>": [...]}. This happens for local fallback, forced remote calls, and remote-only calls. A field is left out when it wasn't provided or is empty.Limits
Each list holds at most 1000 keys. Duplicates count. For groups the limit applies per group type. A longer list raises
ValueErrorfrom the flag getters. Nothing is evaluated and no request is sent. The SDK never truncates the list. Wrong types raiseTypeError, for example a plain string or a non-string group type. Abytearrayor a mapping (such as a property dict passed by mistake) also raisesTypeError, while a dict's.keys()view is accepted. Withcapture(send_feature_flags={...}), the error is handled like othercaptureerrors.capturelogs it and returnsNone, and no event is sent. Withdebug=Trueit raises.Compliance adapter
The adapter now declares
feature_flags_known_absent_v1./get_feature_flagpasses both new params to the SDK unchanged. It also acceptsallow_remote_fallback: true, which calls the default getter on the client with local definitions. That mode returns HTTP 400 when combined withforce_remote: trueoronly_evaluate_locally: true.Not included
icontains_multi,not_icontains_multi,betweenandnot_betweenoperators. The SDK doesn't support them yet, so a listed key with these operators still falls back to/flags. Tracked in Support icontains_multi and between operators in SDK local flag evaluation posthog#138581.Links
💚 How did you test it?
New tests in
posthog/test/test_feature_flags_known_absent.py:distinct_id, and$group_key./flags.negation, and a flag dependency./flagsbody including the fields on fallback and on every remote entry point, includingcapture(send_feature_flags=...)and asyncevaluate_flags. The fields are left out when not provided or empty.capturepath with default and debug settings, and wrong types./flagsbody.sdk_compliance_adapter/test_adapter.pycovers the new adapter params andallow_remote_fallback.Commands run locally with
uv run --no-syncon macOS:ruff format --check .passed.ruff check .passed.mypy --no-site-packages --config-file mypy.ini . | mypy-baseline filterpassed.make public_api_checkpassed. The snapshot is updated in this PR.python -W error -c "import posthog"passed.pytest sdk_compliance_adapter/test_adapter.pypassed.pytest --timeout=30gave 8397 passed and 3 failed. The 3 failures are fork tests inposthog/test/test_metrics_autocapture.py. They also fail on unchangedmainon macOS.After the spec revision I added the cohort-leaf test. It passed with no production change. I re-ran
ruff format --check .,ruff check ., mypy with the baseline filter,make public_api_checkandpython -W error -c "import posthog", and all passed.pytest --timeout=30gave 8399 passed and the same 3 fork test failures inposthog/test/test_metrics_autocapture.py.For PostHog/sdk-specs#239 I added
test_listed_key_with_omitted_or_null_value_stays_inconclusive(is_notwith the value omitted, andis_not,exactandgtwith"value": null) andtest_listed_key_with_null_value_resolves_presence_operator(is_not_setandis_setwith"value": null). Before the fix, theis_notomitted,is_notnull andexactnull cases failed because the known-absent table resolved them.gtnull already fell back. After the fix all 6 cases pass. In local-only mode the flag is unresolved withunsupported_definition, which matches an omitted condition value on a present key, and the default getter falls back to/flags.ruff format --check .,ruff check ., mypy with the baseline filter,make public_api_checkandpython -W error -c "import posthog"passed.pytest posthog/testgave 8467 passed and the same 3 fork test failures inposthog/test/test_metrics_autocapture.py.For filter type scoping (b6c0dd3) I added 19 cases:
test_listed_key_does_not_resolve_a_person_metadata_filter,test_person_metadata_filter_on_listed_key_reads_the_supplied_value,test_listed_key_does_not_resolve_a_person_metadata_cohort_leaf,test_person_keys_do_not_resolve_a_group_filter_in_a_person_flag,test_group_keys_do_not_resolve_a_person_filter_in_a_group_flag,test_group_keys_do_not_resolve_a_person_cohort_leaf_in_a_group_flag,test_group_keys_do_not_resolve_a_filter_for_another_group_typeandtest_flag_dependency_does_not_read_keys_of_another_aggregation. All 19 failed before the fix, and the file gave 110 passed after it. For the input check (da10384) thebytearray, person dict, empty person dict and group dict cases oftest_wrong_type_raises_without_a_requestfailed before the fix, and the file gave 117 passed after it. For repeated keys (98124ab)test_duplicate_person_key_still_reads_the_supplied_value_outside_its_scopeandtest_duplicate_group_key_still_reads_the_supplied_value_outside_its_scopefailed before the fix because a repeated key wrapped its own marker, and the file gave 119 passed after it.ruff format --check,ruff checkand mypy with the baseline filter passed.For PostHog/sdk-specs#250 I added these tests to
posthog/test/test_feature_flags_known_absent.py. Each failed before its fix and passes after it:test_group_filter_without_index_reads_the_condition_group_type(exact"enterprise"givesfalseandis_not_setgivestruewith a suppliedtier="enterprise"listed for organization, plus a null index and$group_key is_set) andtest_group_filter_without_index_reads_the_condition_level_group_type(mixed targeting). Before ddc25fa they read the supplied value.test_group_filter_without_index_ignores_keys_of_another_group_typealready passed and stays as a regression test.test_dependency_is_evaluated_with_its_own_aggregation(personregion=us, organizationregion=eu: parent and child bothfalse, no request). Before 6f71109 the child wastrue.test_group_dependency_without_its_group_resolves_as_false(no organization group,tierlisted for organization: parent and child bothfalse, no request). Before 6f71109 the child fell back to/flags.test_group_dependency_is_bucketed_by_the_group_key(50% rollout:org-0out andorg-1in, matching direct evaluation). Before 6f71109 the dependency hashed the distinct id.test_person_dependency_of_a_group_flag_reads_person_context(organization child with a person parent reads person properties and hashes the distinct id). Before 6f71109 it read the organization properties.test_property_matching_version.pyandtest_redis_flag_cache_snapshot.pynow patchposthog.feature_flags.match_feature_flag_properties, because the client delegates to the shared_compute_flag_locally.ruff format --check .,ruff check ., mypy with the baseline filter andmake public_api_checkpassed, andpytest posthog/testpassed apart from the same fork tests inposthog/test/test_metrics_autocapture.py.For cold-start group known-absent keys (7bd5a4b) I added
TestKnownAbsentColdStarttoposthog/test/test_feature_flags_known_absent.py. It uses a fresh client that never calledload_feature_flags(), liststierand$group_keyfor organization, suppliestier="gold"and allows no/flagscall. Its three tests,test_evaluate_flags_marks_group_keys_after_lazy_load,test_get_feature_flag_marks_group_keys_after_lazy_loadandtest_get_all_flags_marks_group_keys_after_lazy_load, failed before the fix because the keys were marked before the definitions loaded, so they carried no group type index (org-tier-flagwasfalseandorg-key-flagwastrue). All three pass now.ruff check,ruff format --check, mypy with the baseline filter andmake public_api_checkpassed.pytest posthog/testgave 8555 passed and the same 3 fork test failures inposthog/test/test_metrics_autocapture.py.For group cohort leaves without an index (a2e6e9e) I added
test_group_cohort_leaf_reads_the_condition_group_type(organization flag, cohort leaftier exact "enterprise"with the index omitted, null or 0,tier="enterprise"supplied and listed for organization:false, no request) andtest_group_cohort_leaf_with_another_index_ignores_the_condition_keys(leaf with index 1 reads the supplied value:true). The omitted and null cases failed before the fix because the supplied value won. A group filter without an index now reads the condition's listing everywhere, so_with_condition_group_typeis removed.ruff, mypy with the baseline filter andmake public_api_checkpassed,pytestgave 8559 passed and the same 3 fork test failures, and CI passed.For the outage fallback cache (52dd053, d96892d) I added
TestKnownAbsentFallbackCache: results are cached under the flag key plus a digest of the sorted, deduplicated person and group listings, so a result cached for one listing is not served to a call with a different listing during a/flagsoutage, and a stale result is only served for the flag it belongs to. Known limit: a flag literally named<flag>:known_absent:<64-character hex digest>shares a cache slot with that flag's listed entry for the same user. A wrong value is never returned, but one entry can evict the other's outage fallback. The flags service has no such cache, so there is nothing to mirror there. The person, group and unlisted-to-listed cases and the literal-key case failed before the fix.ruff, mypy with the baseline filter andmake public_api_checkpassed, andpytestgave 8564 passed and the same 3 fork test failures.For unusable group keys (2705b8c) I added
TestUnusableGroupKeystoposthog/test/test_feature_flags.py, parameterized over"",None,True,False,[]and{}: direct group flag, mixed flag, group dependency,_compute_flag_locally,get_all_flags,evaluate_flagsandcapture(send_feature_flags=...). All 30 cases failed before the fix and pass after it; string, integer and float keys still evaluate and bucket as before, and a usable key without the needed group properties still falls back.ruff, mypy with the baseline filter andmake public_api_checkpassed, andpytestgave 8595 passed and the same 3 fork test failures.CI now runs SDK test harness 1.34.0. The
feature_flags_known_absentsuite ran and passed 12/12 in each compliance job (gzip, deflate and zstd).📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Written with Pi (Claude) and reviewed with the autoreview skill (GPT model, branch mode). Review found three real problems, which are fixed in separate commits. Validation consumed one-shot iterators before the
/flagscall. Unbounded iterables were read fully before the limit check. Non-string group types andNonegroup lists were accepted. A fourth review run was clean.capturekeeps its existing error handling for invalid known-absent keys instead of raising. This matches how it already treats an invalidsend_feature_flagsvalue.