Repository navigation
feat(flags): support known-absent property keys in local evaluation - #369
marandaneto wants to merge 20 commits into
Conversation
posthog-ruby-sync Compliance ReportDate: 2026-11-26T12:58:15.598557+00:00 ✅ All Tests Passed!47/47 tests passed Capture Tests✅ 30/30 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
posthog-ruby-async Compliance ReportDate: 2026-11-26T12:58:21.138700+00:00 ✅ All Tests Passed!47/47 tests passed Capture Tests✅ 30/30 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
SDK performance: posthog-ruby6 changes worth reviewing: 2 observed improvements, 4 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.
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 |
dustinbyrne
left a comment
There was a problem hiding this comment.
Overall the KnownAbsentPropertyKeys abstraction, operator matching table, 1000-key limit validation, /flags wire serialization, public_api_snapshot.txt update, and changeset look clean.
Three behavioral concerns came up during review and local base/head RSpec checks (see inline comments):
FeatureFlagsPoller.match_propertyappliesknown_absent_keystotype: 'person_metadata'filters (e.g.created_at), diverging fromPostHog/posthog(flag_matching.rs:2656).evaluate_flag_dependencyforwards outerknown_absent_keysacross person/group aggregation boundaries, turning a safe remote fallback onmaininto a silent wrong-truelocal result.Client#capturewithsend_feature_flags:skipsadd_local_person_and_group_properties, causing local evaluation withgroup_property_keys_known_absentto fail on mixed-targeting group conditions and hitNoMethodErrorviaon_erroron multi-filter pure group flags.
Follow-up (non-blocking, outside this PR — PostHog/team-client-libraries):
- Update
PostHog/posthog.comonce released (contents/docs/feature-flags/local-evaluation/index.mdxstill statesis_not_setcannot be evaluated locally, andcontents/docs/libraries/ruby/index.mdxomits the new options). - Coordinate merging open
PostHog/sdk-specs#233(and consider aligning it and the sibling Python/Node PRs ontype: 'person_metadata'alongside the__posthog_person_metadata__prefix rule). - Wire
person_property_keys_known_absent/group_property_keys_known_absentintosdk_compliance_adapter/adapter.rbonce the adapter declaresfeature_flags_local_evaluation_v1andfeature_flags_known_absent_v1so harness1.34.0's known-absent suite runs in CI.
AI-assisted review.
…ent input in capture
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for addressing the earlier threads — person_metadata filtering, capture(send_feature_flags:) group enrichment and fire-and-forget handling on invalid listings, Set YARD/specs, get_feature_flag_payload specs, and the sdk-specs#239 updates all look solid (648 flag/client RSpec examples, RuboCop, rake public_api:check, and all five earlier reproductions pass locally on 2b8680f0).
Two issues remain from the follow-up commits (see inline comments):
- Breaking (
8e398d56):dependency_known_absent_scopeswitchesknown_absent_scopeto a cross-aggregation dependency's aggregation whileevaluate_flag_dependencystill omits_compute_flag_locally'sgroups.key?check and passes the caller'sdistinct_idandproperties, returning wrong local booleans with 0/flagsrequests. - Concern (
bffa4f7a):KnownAbsentPropertyKeys::Scope#covers?excludes legacytype: 'group'filters omittinggroup_type_index, breaking backend parity (PropertyFilter::group_filter_index) and letting suppliedgroup_propertiesoverridegroup_property_keys_known_absent.
(The PostHog/posthog.com docs follow-up from the earlier review remains non-blocking.)
AI-assisted review.
…pe legacy group filters
|
@dustinbyrne thanks for the review. Both issues from your summary are fixed in 9b38999, which landed after your review:
Full suite green after merging main (2723 examples, 0 failures), plus RuboCop and |
A group flag no longer resolves false as a whole when its group key is missing or unusable. Each condition uses its own aggregation, so a person condition still runs, directly and as a dependency, and on the person's properties and distinct id. A group flag with a holdout that excludes anyone and no usable group key is inconclusive with missing_context instead of bucketing the holdout on an empty key.
Brings in "fix(flags): treat unsupported property-filter types as inconclusive" (#394, PostHog/sdk-specs#251). Conflict in lib/posthog/feature_flags.rb, resolved to keep both sides: - match_property checks the filter type with assert_property_filter_type_supported before the known-absent listing check, so an unsupported type such as person_metadata stays inconclusive (unsupported_definition) even when its key is listed known absent. The listing never resolves an unsupported filter. - Kept this PR's assert_operator_supported next to main's PROPERTY_FILTER_TYPES and assert_property_filter_type_supported, and made all three private. Seven known-absent specs expected a person_metadata filter to read caller properties (missing_context, or a match from a supplied value). The spec now says that filter is unsupported_definition whatever the caller passes, so those specs are updated in the next commit.
After merging #394 (PostHog/sdk-specs#251), a person_metadata filter is inconclusive with unsupported_definition whatever the caller passes, and listing its key as known absent doesn't resolve it. Update the known-absent specs that expected missing_context or a match from a supplied created_at value.
ioannisj
left a comment
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
Nothing blocking from my side. The one I'd look at before merging is the Symbol group key: groups: { organization: :acme } now resolves group flags to false locally where main returned true. The rest are smaller: a person filter, or a filter for another group type, inside a group condition still reads the condition's group where go, js and rs don't, a test gap on the known-absent forwarding, and two changeset wording nits.
|
|
||
| # A usable group key is a non-empty string or a number. Any other key counts as no key, matching | ||
| # the server: conditions aggregated on that group type are skipped. | ||
| def self.usable_group_key?(group_key) |
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
A Symbol group value like groups: { organization: :acme } now counts as no group key, so a 100% group flag that was true locally on main resolves false here with no /flags call. The server would get "acme" in the JSON and match it.
usable_group_key? only accepts a non-empty String or a Numeric, and normalize_flag_evaluation_inputs only symbolizes the hash keys, never the values. I reproduced it with get_feature_flag('org-flag', 'user-1', groups: { organization: :acme }, only_evaluate_locally: true): true on main, false on this branch.
Could we treat a non-empty Symbol as usable (or stringify Symbol values in normalize_flag_evaluation_inputs) and add :acme to the usable-key cases in spec/posthog/feature_flags_unusable_group_key_spec.rb?
| # Group property keys known to be absent, by group type. See {#evaluate_flags}. | ||
| # | ||
| # @return [Hash] String (not symbol) key value pairs of flag and their values | ||
| def get_all_flags( |
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
[suggestion] I think the known-absent forwarding in get_feature_flag, is_feature_enabled and get_all_flags isn't pinned by any spec. The only get_all_flags call passes an oversized list, which raises in KnownAbsentPropertyKeys.build before it reaches evaluation.
I dropped the two kwargs from the is_feature_enabled to _get_feature_flag_result delegation and known_absent: from the get_all_flags poller call, and the full suite still passes (2800 examples, 0 failures). So a regression there would still pass.
Worth a small table-driven case over those methods, checking that a listed is_not_set key resolves locally with no /flags request and that the fallback body carries the keys?
| "posthog-ruby": minor | ||
| --- | ||
|
|
||
| Add `person_property_keys_known_absent:` and `group_property_keys_known_absent:` to flag evaluation methods and `SendFeatureFlagsOptions`. A listed key is treated as absent during local evaluation, even when a value for it is passed, so `is_not_set` and the negated operators match and other operators don't, without a remote request. Fallback `/flags` requests carry the same keys. Each list allows at most 1000 keys, per group type for groups. A longer list raises `ArgumentError`, except on `capture(send_feature_flags:)`, which logs a warning and captures the event without flags. |
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
[nit] "Without a remote request" is a bit strong here. match_property still runs assert_operator_supported and assert_condition_value_present on a listed key, so between/not_between/icontains_multi and an omitted or null value on is_not/exact still fall back to /flags. The PR body already covers it. Maybe add "for operators the SDK evaluates locally" here and in the evaluate_flags YARD comment too?
| "posthog-ruby": patch | ||
| --- | ||
|
|
||
| Local evaluation now evaluates a flag dependency like a standalone flag, with its own aggregation, properties and bucketing identifier. A group-aggregated dependency reads its group's properties and is `false` when that group isn't passed, matching `/flags`. |
There was a problem hiding this comment.
🤖 An AI agent wrote this on behalf of @ioannisj.
[nit] This reads as if a group-aggregated dependency is always false without its group. Conditions are skipped one at a time though, so a person condition (aggregation_group_type_index: null) in that dependency still decides, which is what .changeset/group-condition-skip-per-condition.md says. Maybe reword to "its conditions on a group that isn't passed are skipped" so the two entries don't contradict each other?
| snapshot: snapshot) | ||
| snapshot: snapshot, context: context) | ||
| else | ||
| FeatureFlagsPoller.match_property(prop, properties, cohort_properties, |
There was a problem hiding this comment.
[suggestion] A type: "person" filter in a group-aggregated condition is matched against the group's properties here, and Scope#covers? never applies the person listing in a group scope, so that filter never sees the person properties or the person known-absent keys.
posthog-go routes that filter to the person properties in featureflags.go#L2191 (PostHog/posthog-go#461), and posthog-js does the same in feature-flags.ts#L847 (PostHog/posthog-js#5819), which is also what the spec's filter-type table says. Python (PostHog/posthog-python#1280) and php (PostHog/posthog-php#328) have the same gap.
Worth reading a person filter in a group condition from the person properties and listing here too?
|
|
||
| filter_group_type_index = property[:group_type_index] || property['group_type_index'] | ||
| # Like the flags service, a group filter without its own index reads the scope it is evaluated in. | ||
| type == 'group' && (filter_group_type_index.nil? || aggregation?(filter_group_type_index)) |
There was a problem hiding this comment.
[suggestion] When a group filter's own group_type_index names another group type, covers? only withholds the listing, and the filter still reads the condition's group properties, so the other group type's properties and listing are never used.
posthog-rs reads that group type's properties and listing in feature_flags.rs#L1247 (PostHog/posthog-rs#388), and go and dotnet do the same. Python (PostHog/posthog-python#1280), php (PostHog/posthog-php#328) and js (PostHog/posthog-js#5819) still read the condition's group.
Would it be worth routing that filter to its own group type's properties and known-absent keys?
💡 Motivation and Context
Local flag evaluation can't tell "the caller didn't pass
plan" from "this person has noplan". A key left out ofperson_propertiesis inconclusive. So a condition likeplan is_not_setcan't resolve locally, and the SDK falls back to/flags. Callers who know a person has noplanhad no way to say so. Local results and the/flagsfallback could then disagree.This adds an optional way to list property keys that are known to be absent. It follows the cross-SDK spec in PostHog/sdk-specs#233 and the backend support in PostHog/posthog#138239.
Issue: PostHog/posthog#88947
New input
Every flag evaluation method now accepts two optional keyword arguments:
person_property_keys_known_absent:takes an Array of String or Symbol keys.group_property_keys_known_absent:takes a Hash from group type name to an Array of keys.These methods accept them:
evaluate_flags,get_feature_flag,get_feature_flag_result,is_feature_enabled,get_feature_flag_payload,get_all_flagsandget_all_flags_and_payloads.SendFeatureFlagsOptionsalso accepts them, and so does the hash form ofcapture(send_feature_flags:). Both default tonil, so existing calls behave the same.Local evaluation behavior
is_not_set,is_not,not_icontains,not_starts_with,not_ends_withandnot_regexmatch. Every other operator does not match. That includesis_set,exact, thecontains/starts_with/ends_with/regexchecks, number comparisons, allsemver_*operators includingsemver_neq, and the date operators.distinct_idin person properties and$group_keyin group properties./flagsas before, even for a listed key. Like the flags service, a listed key resolves without parsing the condition value, so a malformed regex, number, date or semver value on a listed key still resolves from the table.dynamic cohorts check operator support before the known-absent tablecovers a cohort leafplan not_between [1, 2]with and without negation.unsupported_definitionand falls back to/flags, per docs(flags): resolve known-absent keys without reading the condition value sdk-specs#239.is_setandis_not_setstill resolve from the table whatever the value is.__posthog_person_metadata__are ignored for local matching. They are still sent to/flagsas given.type: "person"filters, group keys only totype: "group"filters of their own group type, and aperson_metadatafilter such ascreated_atnever resolves from a listing, per docs(flags): specify known-absent property keys sdk-specs#233 and chore(deps-dev): bump rake from 13.2.1 to 13.4.2 #239. Since the merge of main, aperson_metadatafilter is unresolved withunsupported_definitionwhatever the caller passes or lists. This includes group conditions inside flags that mix person and group conditions and person checks inside dynamic cohorts. A String and a Symbol that name the same group type are merged.person_metadata, is checked before the known-absent table, so it stays unresolved withunsupported_definitionand falls back to/flagseven when its key is listed. Seven known-absent tests that expectedmissing_contextor a match from a suppliedcreated_atvalue now expectunsupported_definition.falseonly when none of its other conditions match. A person-aggregated dependency of a group flag reads person properties and person keys, and a group-aggregated one reads that group type's properties and keys. This also fixes a gap onmain, where a dependency was evaluated with the calling condition's properties and bucketing ID (separate patch changeset).type: "group"filter withoutgroup_type_indexreads the group type of the condition it is in, as in the flags service (PropertyFilter::group_filter_index), so that group type's known-absent keys apply to it.nil, a boolean, an Array or a Hash counts as no group key, as in the flags service (is_usable_group_key, docs(flags): evaluate flag dependencies in their own context sdk-specs#250): a condition aggregated on that group type is skipped, and a flag whose conditions are all skipped resolvesfalselocally with no/flagscall (separate patch changeset).falseas a whole. Each condition is skipped or run on its own aggregation, as in the flags service, so a person condition (aggregation_group_type_index: null) still decides, also as a dependency. A group flag with a holdout above 0% and no usable group key is unresolved withmissing_contextand falls back to/flags(separate patch changeset). Tested inspec/posthog/feature_flags_unusable_group_key_spec.rb(a group flag with a person condition,a group flag with a holdout): 13 cases failed before the fix and pass now./flagsrequest bodyWhen a call falls back to
/flags, or skips local evaluation, the request includesperson_property_keys_known_absent: [...]andgroup_property_keys_known_absent: { group_type => [...] }. A field is left out when the caller did not provide it or when it is empty.Limits
Each list holds at most 1000 keys, counting duplicates. For groups the limit applies per group type. A longer list raises
ArgumentErrorbefore any evaluation or request. The list is never truncated. Lists that are not an Array or Set, keys that are not a String or Symbol, and group types that are not a String or Symbol also raiseArgumentError.capture(send_feature_flags:)is the exception: capture is fire-and-forget per the capture spec, so it logs a warning and sends the event without flags.Not included
$feature_enrollment/<flag>keys. Only posthog-python evaluates enrollment locally today. Tracked in Support local feature enrollment evaluation across server SDKs posthog#138580.icontains_multi,not_icontains_multi,betweenandnot_betweenoperators. Ruby doesn't support them yet, so they still fall back to/flagseven for a listed key. Tracked in Support icontains_multi and between operators in SDK local flag evaluation posthog#138581.feature_flags_local_evaluation_v1orfeature_flags_known_absent_v1.Links
💚 How did you test it?
New tests in
spec/posthog/feature_flags_known_absent_spec.rbandspec/posthog/send_feature_flags_options_spec.rbcover:distinct_idand$group_keyfilter typesblock): aperson_metadatacreated_atfilter withis_not_set,is_date_beforeandis_date_afteron a listed key, as a flag filter and as a cohort leaf, plus supplied-value and/flagsfallback cases (allunsupported_definitionsince the merge of main); a person listing against group filters; a group listing against another group type, a person filter and a person cohort leaf; and cross-aggregation dependencies in both directions, including a group dependency with a conflicting person value. 15 of these failed before the fix and all pass now. A same-aggregation group dependency already passed and stays as a regression test./flagsnot_betweenleaf in a dynamic cohort, with and without negation, staying unresolved withunsupported_definitionand falling back to/flagsfor a listed key. The new test passed without production changes, and it fails if the support check is removed.group_type_index(exactandis_not_set), plus a guard that an explicit index for another group type still ignores the listingstays unsupported for is_not omitted / is_not null / exact null / gt null condition value on a listed key,stays unsupported for a JSON null condition value with a String-keyed filter,still resolves is_not_set / is_set with a null condition value on a listed key,leave an omitted / null is_not condition value unresolved in local-only modeandfall back to /flags for an omitted / null is_not condition value. The omitted and nullis_notandexactcases failed before the fix and pass after it.gt nulland theis_set/is_not_setcases already passed./flagsbody including the fields on fallback forevaluate_flags, the older getters, all flags and payloads, andcapture(send_feature_flags:), and leaving them out when they are missing or emptyflag_keysscope, plus wrong input typesspec/posthog/feature_flags_unusable_group_key_spec.rb, parameterized over'',nil,true,false,[],{}, a non-empty Array and a non-empty Hash: group flags, mixed flags, group dependencies, the single-flag getter, all flags andcapture(send_feature_flags:). 56 failed before the fix and pass now; string, integer and float keys and a usable key without group properties stay as regression tests.Commands run on the final commit:
bundle exec rspec: 2828 examples, 0 failures, 49 pendingbundle exec rubocop: no offensesbundle exec rake public_api:check: passedThe otel gemfile suite was not run locally. No manual testing against a live PostHog project was done.
📝 Checklist
If releasing new changes
pnpm changesetto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Implemented and reviewed with the pi coding agent, using Claude. Autoreview with GPT ran four rounds against
origin/main. Accepted findings were fixed in separate signed commits. Those fixes merge String and Symbol group names, reject non-String group types, and check the key limit beforeevaluate_flagsreturns early for an emptyflag_keys. Every round also flagged that dependencies did not use their own context. Review on this PR showed it combined with known-absent keys to return wrong local values, so it is now fixed here. A later round on the filter-type scoping found that a cross-aggregation dependency dropped its own listing. That is fixed in a separate commit, with a regression test.